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    pub fn view_id(&self) -> usize {
2423        self.view_id
2424    }
2425}
2426
2427impl AsRef<AppContext> for &AppContext {
2428    fn as_ref(&self) -> &AppContext {
2429        self
2430    }
2431}
2432
2433impl<V: View> Deref for RenderContext<'_, V> {
2434    type Target = MutableAppContext;
2435
2436    fn deref(&self) -> &Self::Target {
2437        self.app
2438    }
2439}
2440
2441impl<V: View> DerefMut for RenderContext<'_, V> {
2442    fn deref_mut(&mut self) -> &mut Self::Target {
2443        self.app
2444    }
2445}
2446
2447impl<V: View> ReadModel for RenderContext<'_, V> {
2448    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2449        self.app.read_model(handle)
2450    }
2451}
2452
2453impl<V: View> UpdateModel for RenderContext<'_, V> {
2454    fn update_model<T: Entity, O>(
2455        &mut self,
2456        handle: &ModelHandle<T>,
2457        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
2458    ) -> O {
2459        self.app.update_model(handle, update)
2460    }
2461}
2462
2463impl<V: View> ReadView for RenderContext<'_, V> {
2464    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2465        self.app.read_view(handle)
2466    }
2467}
2468
2469impl<M> AsRef<AppContext> for ViewContext<'_, M> {
2470    fn as_ref(&self) -> &AppContext {
2471        &self.app.cx
2472    }
2473}
2474
2475impl<M> Deref for ViewContext<'_, M> {
2476    type Target = MutableAppContext;
2477
2478    fn deref(&self) -> &Self::Target {
2479        &self.app
2480    }
2481}
2482
2483impl<M> DerefMut for ViewContext<'_, M> {
2484    fn deref_mut(&mut self) -> &mut Self::Target {
2485        &mut self.app
2486    }
2487}
2488
2489impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
2490    fn as_mut(&mut self) -> &mut MutableAppContext {
2491        self.app
2492    }
2493}
2494
2495impl<V> ReadModel for ViewContext<'_, V> {
2496    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2497        self.app.read_model(handle)
2498    }
2499}
2500
2501impl<V> UpgradeModelHandle for ViewContext<'_, V> {
2502    fn upgrade_model_handle<T: Entity>(
2503        &self,
2504        handle: WeakModelHandle<T>,
2505    ) -> Option<ModelHandle<T>> {
2506        self.cx.upgrade_model_handle(handle)
2507    }
2508}
2509
2510impl<V: View> UpdateModel for ViewContext<'_, V> {
2511    fn update_model<T: Entity, O>(
2512        &mut self,
2513        handle: &ModelHandle<T>,
2514        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> O,
2515    ) -> O {
2516        self.app.update_model(handle, update)
2517    }
2518}
2519
2520impl<V: View> ReadView for ViewContext<'_, V> {
2521    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2522        self.app.read_view(handle)
2523    }
2524}
2525
2526impl<V: View> UpdateView for ViewContext<'_, V> {
2527    fn update_view<T, S>(
2528        &mut self,
2529        handle: &ViewHandle<T>,
2530        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
2531    ) -> S
2532    where
2533        T: View,
2534    {
2535        self.app.update_view(handle, update)
2536    }
2537}
2538
2539pub trait Handle<T> {
2540    type Weak: 'static;
2541    fn id(&self) -> usize;
2542    fn location(&self) -> EntityLocation;
2543    fn downgrade(&self) -> Self::Weak;
2544    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2545    where
2546        Self: Sized;
2547}
2548
2549#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
2550pub enum EntityLocation {
2551    Model(usize),
2552    View(usize, usize),
2553}
2554
2555pub struct ModelHandle<T> {
2556    model_id: usize,
2557    model_type: PhantomData<T>,
2558    ref_counts: Arc<Mutex<RefCounts>>,
2559}
2560
2561impl<T: Entity> ModelHandle<T> {
2562    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2563        ref_counts.lock().inc_model(model_id);
2564        Self {
2565            model_id,
2566            model_type: PhantomData,
2567            ref_counts: ref_counts.clone(),
2568        }
2569    }
2570
2571    pub fn downgrade(&self) -> WeakModelHandle<T> {
2572        WeakModelHandle::new(self.model_id)
2573    }
2574
2575    pub fn id(&self) -> usize {
2576        self.model_id
2577    }
2578
2579    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
2580        cx.read_model(self)
2581    }
2582
2583    pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
2584    where
2585        C: ReadModelWith,
2586        F: FnOnce(&T, &AppContext) -> S,
2587    {
2588        let mut read = Some(read);
2589        cx.read_model_with(self, &mut |model, cx| {
2590            let read = read.take().unwrap();
2591            read(model, cx)
2592        })
2593    }
2594
2595    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2596    where
2597        C: UpdateModel,
2598        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2599    {
2600        let mut update = Some(update);
2601        cx.update_model(self, &mut |model, cx| {
2602            let update = update.take().unwrap();
2603            update(model, cx)
2604        })
2605    }
2606
2607    pub fn next_notification(&self, cx: &TestAppContext) -> impl Future<Output = ()> {
2608        let (mut tx, mut rx) = mpsc::channel(1);
2609        let mut cx = cx.cx.borrow_mut();
2610        let subscription = cx.observe(self, move |_, _| {
2611            tx.blocking_send(()).ok();
2612        });
2613
2614        let duration = if std::env::var("CI").is_ok() {
2615            Duration::from_secs(5)
2616        } else {
2617            Duration::from_secs(1)
2618        };
2619
2620        async move {
2621            let notification = timeout(duration, rx.recv())
2622                .await
2623                .expect("next notification timed out");
2624            drop(subscription);
2625            notification.expect("model dropped while test was waiting for its next notification")
2626        }
2627    }
2628
2629    pub fn next_event(&self, cx: &TestAppContext) -> impl Future<Output = T::Event>
2630    where
2631        T::Event: Clone,
2632    {
2633        let (mut tx, mut rx) = mpsc::channel(1);
2634        let mut cx = cx.cx.borrow_mut();
2635        let subscription = cx.subscribe(self, move |_, event, _| {
2636            tx.blocking_send(event.clone()).ok();
2637        });
2638
2639        let duration = if std::env::var("CI").is_ok() {
2640            Duration::from_secs(5)
2641        } else {
2642            Duration::from_secs(1)
2643        };
2644
2645        async move {
2646            let event = timeout(duration, rx.recv())
2647                .await
2648                .expect("next event timed out");
2649            drop(subscription);
2650            event.expect("model dropped while test was waiting for its next event")
2651        }
2652    }
2653
2654    pub fn condition(
2655        &self,
2656        cx: &TestAppContext,
2657        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2658    ) -> impl Future<Output = ()> {
2659        let (tx, mut rx) = mpsc::channel(1024);
2660
2661        let mut cx = cx.cx.borrow_mut();
2662        let subscriptions = (
2663            cx.observe(self, {
2664                let mut tx = tx.clone();
2665                move |_, _| {
2666                    tx.blocking_send(()).ok();
2667                }
2668            }),
2669            cx.subscribe(self, {
2670                let mut tx = tx.clone();
2671                move |_, _, _| {
2672                    tx.blocking_send(()).ok();
2673                }
2674            }),
2675        );
2676
2677        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2678        let handle = self.downgrade();
2679        let duration = if std::env::var("CI").is_ok() {
2680            Duration::from_secs(5)
2681        } else {
2682            Duration::from_secs(1)
2683        };
2684
2685        async move {
2686            timeout(duration, async move {
2687                loop {
2688                    {
2689                        let cx = cx.borrow();
2690                        let cx = cx.as_ref();
2691                        if predicate(
2692                            handle
2693                                .upgrade(cx)
2694                                .expect("model dropped with pending condition")
2695                                .read(cx),
2696                            cx,
2697                        ) {
2698                            break;
2699                        }
2700                    }
2701
2702                    rx.recv()
2703                        .await
2704                        .expect("model dropped with pending condition");
2705                }
2706            })
2707            .await
2708            .expect("condition timed out");
2709            drop(subscriptions);
2710        }
2711    }
2712}
2713
2714impl<T> Clone for ModelHandle<T> {
2715    fn clone(&self) -> Self {
2716        self.ref_counts.lock().inc_model(self.model_id);
2717        Self {
2718            model_id: self.model_id,
2719            model_type: PhantomData,
2720            ref_counts: self.ref_counts.clone(),
2721        }
2722    }
2723}
2724
2725impl<T> PartialEq for ModelHandle<T> {
2726    fn eq(&self, other: &Self) -> bool {
2727        self.model_id == other.model_id
2728    }
2729}
2730
2731impl<T> Eq for ModelHandle<T> {}
2732
2733impl<T> Hash for ModelHandle<T> {
2734    fn hash<H: Hasher>(&self, state: &mut H) {
2735        self.model_id.hash(state);
2736    }
2737}
2738
2739impl<T> std::borrow::Borrow<usize> for ModelHandle<T> {
2740    fn borrow(&self) -> &usize {
2741        &self.model_id
2742    }
2743}
2744
2745impl<T> Debug for ModelHandle<T> {
2746    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2747        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
2748            .field(&self.model_id)
2749            .finish()
2750    }
2751}
2752
2753unsafe impl<T> Send for ModelHandle<T> {}
2754unsafe impl<T> Sync for ModelHandle<T> {}
2755
2756impl<T> Drop for ModelHandle<T> {
2757    fn drop(&mut self) {
2758        self.ref_counts.lock().dec_model(self.model_id);
2759    }
2760}
2761
2762impl<T: Entity> Handle<T> for ModelHandle<T> {
2763    type Weak = WeakModelHandle<T>;
2764
2765    fn id(&self) -> usize {
2766        self.model_id
2767    }
2768
2769    fn location(&self) -> EntityLocation {
2770        EntityLocation::Model(self.model_id)
2771    }
2772
2773    fn downgrade(&self) -> Self::Weak {
2774        self.downgrade()
2775    }
2776
2777    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
2778    where
2779        Self: Sized,
2780    {
2781        weak.upgrade(cx)
2782    }
2783}
2784
2785pub struct WeakModelHandle<T> {
2786    model_id: usize,
2787    model_type: PhantomData<T>,
2788}
2789
2790unsafe impl<T> Send for WeakModelHandle<T> {}
2791unsafe impl<T> Sync for WeakModelHandle<T> {}
2792
2793impl<T: Entity> WeakModelHandle<T> {
2794    fn new(model_id: usize) -> Self {
2795        Self {
2796            model_id,
2797            model_type: PhantomData,
2798        }
2799    }
2800
2801    pub fn upgrade(self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
2802        cx.upgrade_model_handle(self)
2803    }
2804}
2805
2806impl<T> Hash for WeakModelHandle<T> {
2807    fn hash<H: Hasher>(&self, state: &mut H) {
2808        self.model_id.hash(state)
2809    }
2810}
2811
2812impl<T> PartialEq for WeakModelHandle<T> {
2813    fn eq(&self, other: &Self) -> bool {
2814        self.model_id == other.model_id
2815    }
2816}
2817
2818impl<T> Eq for WeakModelHandle<T> {}
2819
2820impl<T> Clone for WeakModelHandle<T> {
2821    fn clone(&self) -> Self {
2822        Self {
2823            model_id: self.model_id,
2824            model_type: PhantomData,
2825        }
2826    }
2827}
2828
2829impl<T> Copy for WeakModelHandle<T> {}
2830
2831pub struct ViewHandle<T> {
2832    window_id: usize,
2833    view_id: usize,
2834    view_type: PhantomData<T>,
2835    ref_counts: Arc<Mutex<RefCounts>>,
2836}
2837
2838impl<T: View> ViewHandle<T> {
2839    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2840        ref_counts.lock().inc_view(window_id, view_id);
2841        Self {
2842            window_id,
2843            view_id,
2844            view_type: PhantomData,
2845            ref_counts: ref_counts.clone(),
2846        }
2847    }
2848
2849    pub fn downgrade(&self) -> WeakViewHandle<T> {
2850        WeakViewHandle::new(self.window_id, self.view_id)
2851    }
2852
2853    pub fn window_id(&self) -> usize {
2854        self.window_id
2855    }
2856
2857    pub fn id(&self) -> usize {
2858        self.view_id
2859    }
2860
2861    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
2862        cx.read_view(self)
2863    }
2864
2865    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
2866    where
2867        C: ReadViewWith,
2868        F: FnOnce(&T, &AppContext) -> S,
2869    {
2870        let mut read = Some(read);
2871        cx.read_view_with(self, &mut |view, cx| {
2872            let read = read.take().unwrap();
2873            read(view, cx)
2874        })
2875    }
2876
2877    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2878    where
2879        C: UpdateView,
2880        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2881    {
2882        let mut update = Some(update);
2883        cx.update_view(self, &mut |view, cx| {
2884            let update = update.take().unwrap();
2885            update(view, cx)
2886        })
2887    }
2888
2889    pub fn is_focused(&self, cx: &AppContext) -> bool {
2890        cx.focused_view_id(self.window_id)
2891            .map_or(false, |focused_id| focused_id == self.view_id)
2892    }
2893
2894    pub fn condition(
2895        &self,
2896        cx: &TestAppContext,
2897        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2898    ) -> impl Future<Output = ()> {
2899        let (tx, mut rx) = mpsc::channel(1024);
2900
2901        let mut cx = cx.cx.borrow_mut();
2902        let subscriptions = self.update(&mut *cx, |_, cx| {
2903            (
2904                cx.observe(self, {
2905                    let mut tx = tx.clone();
2906                    move |_, _, _| {
2907                        tx.blocking_send(()).ok();
2908                    }
2909                }),
2910                cx.subscribe(self, {
2911                    let mut tx = tx.clone();
2912                    move |_, _, _, _| {
2913                        tx.blocking_send(()).ok();
2914                    }
2915                }),
2916            )
2917        });
2918
2919        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2920        let handle = self.downgrade();
2921        let duration = if std::env::var("CI").is_ok() {
2922            Duration::from_secs(2)
2923        } else {
2924            Duration::from_millis(500)
2925        };
2926
2927        async move {
2928            timeout(duration, async move {
2929                loop {
2930                    {
2931                        let cx = cx.borrow();
2932                        let cx = cx.as_ref();
2933                        if predicate(
2934                            handle
2935                                .upgrade(cx)
2936                                .expect("view dropped with pending condition")
2937                                .read(cx),
2938                            cx,
2939                        ) {
2940                            break;
2941                        }
2942                    }
2943
2944                    rx.recv()
2945                        .await
2946                        .expect("view dropped with pending condition");
2947                }
2948            })
2949            .await
2950            .expect("condition timed out");
2951            drop(subscriptions);
2952        }
2953    }
2954}
2955
2956impl<T> Clone for ViewHandle<T> {
2957    fn clone(&self) -> Self {
2958        self.ref_counts
2959            .lock()
2960            .inc_view(self.window_id, self.view_id);
2961        Self {
2962            window_id: self.window_id,
2963            view_id: self.view_id,
2964            view_type: PhantomData,
2965            ref_counts: self.ref_counts.clone(),
2966        }
2967    }
2968}
2969
2970impl<T> PartialEq for ViewHandle<T> {
2971    fn eq(&self, other: &Self) -> bool {
2972        self.window_id == other.window_id && self.view_id == other.view_id
2973    }
2974}
2975
2976impl<T> Eq for ViewHandle<T> {}
2977
2978impl<T> Debug for ViewHandle<T> {
2979    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2980        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
2981            .field("window_id", &self.window_id)
2982            .field("view_id", &self.view_id)
2983            .finish()
2984    }
2985}
2986
2987impl<T> Drop for ViewHandle<T> {
2988    fn drop(&mut self) {
2989        self.ref_counts
2990            .lock()
2991            .dec_view(self.window_id, self.view_id);
2992    }
2993}
2994
2995impl<T: View> Handle<T> for ViewHandle<T> {
2996    type Weak = WeakViewHandle<T>;
2997
2998    fn id(&self) -> usize {
2999        self.view_id
3000    }
3001
3002    fn location(&self) -> EntityLocation {
3003        EntityLocation::View(self.window_id, self.view_id)
3004    }
3005
3006    fn downgrade(&self) -> Self::Weak {
3007        self.downgrade()
3008    }
3009
3010    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3011    where
3012        Self: Sized,
3013    {
3014        weak.upgrade(cx)
3015    }
3016}
3017
3018pub struct AnyViewHandle {
3019    window_id: usize,
3020    view_id: usize,
3021    view_type: TypeId,
3022    ref_counts: Arc<Mutex<RefCounts>>,
3023}
3024
3025impl AnyViewHandle {
3026    pub fn id(&self) -> usize {
3027        self.view_id
3028    }
3029
3030    pub fn is<T: 'static>(&self) -> bool {
3031        TypeId::of::<T>() == self.view_type
3032    }
3033
3034    pub fn is_focused(&self, cx: &AppContext) -> bool {
3035        cx.focused_view_id(self.window_id)
3036            .map_or(false, |focused_id| focused_id == self.view_id)
3037    }
3038
3039    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
3040        if self.is::<T>() {
3041            let result = Some(ViewHandle {
3042                window_id: self.window_id,
3043                view_id: self.view_id,
3044                ref_counts: self.ref_counts.clone(),
3045                view_type: PhantomData,
3046            });
3047            unsafe {
3048                Arc::decrement_strong_count(&self.ref_counts);
3049            }
3050            std::mem::forget(self);
3051            result
3052        } else {
3053            None
3054        }
3055    }
3056}
3057
3058impl Clone for AnyViewHandle {
3059    fn clone(&self) -> Self {
3060        self.ref_counts
3061            .lock()
3062            .inc_view(self.window_id, self.view_id);
3063        Self {
3064            window_id: self.window_id,
3065            view_id: self.view_id,
3066            view_type: self.view_type,
3067            ref_counts: self.ref_counts.clone(),
3068        }
3069    }
3070}
3071
3072impl From<&AnyViewHandle> for AnyViewHandle {
3073    fn from(handle: &AnyViewHandle) -> Self {
3074        handle.clone()
3075    }
3076}
3077
3078impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
3079    fn from(handle: &ViewHandle<T>) -> Self {
3080        handle
3081            .ref_counts
3082            .lock()
3083            .inc_view(handle.window_id, handle.view_id);
3084        AnyViewHandle {
3085            window_id: handle.window_id,
3086            view_id: handle.view_id,
3087            view_type: TypeId::of::<T>(),
3088            ref_counts: handle.ref_counts.clone(),
3089        }
3090    }
3091}
3092
3093impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
3094    fn from(handle: ViewHandle<T>) -> Self {
3095        let any_handle = AnyViewHandle {
3096            window_id: handle.window_id,
3097            view_id: handle.view_id,
3098            view_type: TypeId::of::<T>(),
3099            ref_counts: handle.ref_counts.clone(),
3100        };
3101        unsafe {
3102            Arc::decrement_strong_count(&handle.ref_counts);
3103        }
3104        std::mem::forget(handle);
3105        any_handle
3106    }
3107}
3108
3109impl Drop for AnyViewHandle {
3110    fn drop(&mut self) {
3111        self.ref_counts
3112            .lock()
3113            .dec_view(self.window_id, self.view_id);
3114    }
3115}
3116
3117pub struct AnyModelHandle {
3118    model_id: usize,
3119    ref_counts: Arc<Mutex<RefCounts>>,
3120}
3121
3122impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
3123    fn from(handle: ModelHandle<T>) -> Self {
3124        handle.ref_counts.lock().inc_model(handle.model_id);
3125        Self {
3126            model_id: handle.model_id,
3127            ref_counts: handle.ref_counts.clone(),
3128        }
3129    }
3130}
3131
3132impl Drop for AnyModelHandle {
3133    fn drop(&mut self) {
3134        self.ref_counts.lock().dec_model(self.model_id);
3135    }
3136}
3137pub struct WeakViewHandle<T> {
3138    window_id: usize,
3139    view_id: usize,
3140    view_type: PhantomData<T>,
3141}
3142
3143impl<T: View> WeakViewHandle<T> {
3144    fn new(window_id: usize, view_id: usize) -> Self {
3145        Self {
3146            window_id,
3147            view_id,
3148            view_type: PhantomData,
3149        }
3150    }
3151
3152    pub fn id(&self) -> usize {
3153        self.view_id
3154    }
3155
3156    pub fn upgrade(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
3157        if cx.ref_counts.lock().is_entity_alive(self.view_id) {
3158            Some(ViewHandle::new(
3159                self.window_id,
3160                self.view_id,
3161                &cx.ref_counts,
3162            ))
3163        } else {
3164            None
3165        }
3166    }
3167}
3168
3169impl<T> Clone for WeakViewHandle<T> {
3170    fn clone(&self) -> Self {
3171        Self {
3172            window_id: self.window_id,
3173            view_id: self.view_id,
3174            view_type: PhantomData,
3175        }
3176    }
3177}
3178
3179#[derive(Clone, Copy, PartialEq, Eq, Hash)]
3180pub struct ElementStateId(usize, usize);
3181
3182impl From<usize> for ElementStateId {
3183    fn from(id: usize) -> Self {
3184        Self(id, 0)
3185    }
3186}
3187
3188impl From<(usize, usize)> for ElementStateId {
3189    fn from(id: (usize, usize)) -> Self {
3190        Self(id.0, id.1)
3191    }
3192}
3193
3194pub struct ElementStateHandle<T> {
3195    value_type: PhantomData<T>,
3196    tag_type_id: TypeId,
3197    id: ElementStateId,
3198    ref_counts: Weak<Mutex<RefCounts>>,
3199}
3200
3201impl<T: 'static> ElementStateHandle<T> {
3202    fn new(tag_type_id: TypeId, id: ElementStateId, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3203        ref_counts.lock().inc_element_state(tag_type_id, id);
3204        Self {
3205            value_type: PhantomData,
3206            tag_type_id,
3207            id,
3208            ref_counts: Arc::downgrade(ref_counts),
3209        }
3210    }
3211
3212    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3213        cx.element_states
3214            .get(&(self.tag_type_id, self.id))
3215            .unwrap()
3216            .downcast_ref()
3217            .unwrap()
3218    }
3219
3220    pub fn update<C, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
3221    where
3222        C: DerefMut<Target = MutableAppContext>,
3223    {
3224        let mut element_state = cx
3225            .deref_mut()
3226            .cx
3227            .element_states
3228            .remove(&(self.tag_type_id, self.id))
3229            .unwrap();
3230        let result = f(element_state.downcast_mut().unwrap(), cx);
3231        cx.deref_mut()
3232            .cx
3233            .element_states
3234            .insert((self.tag_type_id, self.id), element_state);
3235        result
3236    }
3237}
3238
3239impl<T> Drop for ElementStateHandle<T> {
3240    fn drop(&mut self) {
3241        if let Some(ref_counts) = self.ref_counts.upgrade() {
3242            ref_counts
3243                .lock()
3244                .dec_element_state(self.tag_type_id, self.id);
3245        }
3246    }
3247}
3248
3249pub struct CursorStyleHandle {
3250    id: usize,
3251    next_cursor_style_handle_id: Arc<AtomicUsize>,
3252    platform: Arc<dyn Platform>,
3253}
3254
3255impl Drop for CursorStyleHandle {
3256    fn drop(&mut self) {
3257        if self.id + 1 == self.next_cursor_style_handle_id.load(SeqCst) {
3258            self.platform.set_cursor_style(CursorStyle::Arrow);
3259        }
3260    }
3261}
3262
3263#[must_use]
3264pub enum Subscription {
3265    Subscription {
3266        id: usize,
3267        entity_id: usize,
3268        subscriptions: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, SubscriptionCallback>>>>>,
3269    },
3270    Observation {
3271        id: usize,
3272        entity_id: usize,
3273        observations: Option<Weak<Mutex<HashMap<usize, BTreeMap<usize, ObservationCallback>>>>>,
3274    },
3275}
3276
3277impl Subscription {
3278    pub fn detach(&mut self) {
3279        match self {
3280            Subscription::Subscription { subscriptions, .. } => {
3281                subscriptions.take();
3282            }
3283            Subscription::Observation { observations, .. } => {
3284                observations.take();
3285            }
3286        }
3287    }
3288}
3289
3290impl Drop for Subscription {
3291    fn drop(&mut self) {
3292        match self {
3293            Subscription::Observation {
3294                id,
3295                entity_id,
3296                observations,
3297            } => {
3298                if let Some(observations) = observations.as_ref().and_then(Weak::upgrade) {
3299                    if let Some(observations) = observations.lock().get_mut(entity_id) {
3300                        observations.remove(id);
3301                    }
3302                }
3303            }
3304            Subscription::Subscription {
3305                id,
3306                entity_id,
3307                subscriptions,
3308            } => {
3309                if let Some(subscriptions) = subscriptions.as_ref().and_then(Weak::upgrade) {
3310                    if let Some(subscriptions) = subscriptions.lock().get_mut(entity_id) {
3311                        subscriptions.remove(id);
3312                    }
3313                }
3314            }
3315        }
3316    }
3317}
3318
3319#[derive(Default)]
3320struct RefCounts {
3321    entity_counts: HashMap<usize, usize>,
3322    element_state_counts: HashMap<(TypeId, ElementStateId), usize>,
3323    dropped_models: HashSet<usize>,
3324    dropped_views: HashSet<(usize, usize)>,
3325    dropped_element_states: HashSet<(TypeId, ElementStateId)>,
3326}
3327
3328impl RefCounts {
3329    fn inc_model(&mut self, model_id: usize) {
3330        match self.entity_counts.entry(model_id) {
3331            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3332            Entry::Vacant(entry) => {
3333                entry.insert(1);
3334                self.dropped_models.remove(&model_id);
3335            }
3336        }
3337    }
3338
3339    fn inc_view(&mut self, window_id: usize, view_id: usize) {
3340        match self.entity_counts.entry(view_id) {
3341            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3342            Entry::Vacant(entry) => {
3343                entry.insert(1);
3344                self.dropped_views.remove(&(window_id, view_id));
3345            }
3346        }
3347    }
3348
3349    fn inc_element_state(&mut self, tag_type_id: TypeId, id: ElementStateId) {
3350        match self.element_state_counts.entry((tag_type_id, id)) {
3351            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
3352            Entry::Vacant(entry) => {
3353                entry.insert(1);
3354                self.dropped_element_states.remove(&(tag_type_id, id));
3355            }
3356        }
3357    }
3358
3359    fn dec_model(&mut self, model_id: usize) {
3360        let count = self.entity_counts.get_mut(&model_id).unwrap();
3361        *count -= 1;
3362        if *count == 0 {
3363            self.entity_counts.remove(&model_id);
3364            self.dropped_models.insert(model_id);
3365        }
3366    }
3367
3368    fn dec_view(&mut self, window_id: usize, view_id: usize) {
3369        let count = self.entity_counts.get_mut(&view_id).unwrap();
3370        *count -= 1;
3371        if *count == 0 {
3372            self.entity_counts.remove(&view_id);
3373            self.dropped_views.insert((window_id, view_id));
3374        }
3375    }
3376
3377    fn dec_element_state(&mut self, tag_type_id: TypeId, id: ElementStateId) {
3378        let key = (tag_type_id, id);
3379        let count = self.element_state_counts.get_mut(&key).unwrap();
3380        *count -= 1;
3381        if *count == 0 {
3382            self.element_state_counts.remove(&key);
3383            self.dropped_element_states.insert(key);
3384        }
3385    }
3386
3387    fn is_entity_alive(&self, entity_id: usize) -> bool {
3388        self.entity_counts.contains_key(&entity_id)
3389    }
3390
3391    fn take_dropped(
3392        &mut self,
3393    ) -> (
3394        HashSet<usize>,
3395        HashSet<(usize, usize)>,
3396        HashSet<(TypeId, ElementStateId)>,
3397    ) {
3398        let mut dropped_models = HashSet::new();
3399        let mut dropped_views = HashSet::new();
3400        let mut dropped_element_states = HashSet::new();
3401        std::mem::swap(&mut self.dropped_models, &mut dropped_models);
3402        std::mem::swap(&mut self.dropped_views, &mut dropped_views);
3403        std::mem::swap(
3404            &mut self.dropped_element_states,
3405            &mut dropped_element_states,
3406        );
3407        (dropped_models, dropped_views, dropped_element_states)
3408    }
3409}
3410
3411#[cfg(test)]
3412mod tests {
3413    use super::*;
3414    use crate::elements::*;
3415    use smol::future::poll_once;
3416    use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
3417
3418    #[crate::test(self)]
3419    fn test_model_handles(cx: &mut MutableAppContext) {
3420        struct Model {
3421            other: Option<ModelHandle<Model>>,
3422            events: Vec<String>,
3423        }
3424
3425        impl Entity for Model {
3426            type Event = usize;
3427        }
3428
3429        impl Model {
3430            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
3431                if let Some(other) = other.as_ref() {
3432                    cx.observe(other, |me, _, _| {
3433                        me.events.push("notified".into());
3434                    })
3435                    .detach();
3436                    cx.subscribe(other, |me, _, event, _| {
3437                        me.events.push(format!("observed event {}", event));
3438                    })
3439                    .detach();
3440                }
3441
3442                Self {
3443                    other,
3444                    events: Vec::new(),
3445                }
3446            }
3447        }
3448
3449        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
3450        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
3451        assert_eq!(cx.cx.models.len(), 2);
3452
3453        handle_1.update(cx, |model, cx| {
3454            model.events.push("updated".into());
3455            cx.emit(1);
3456            cx.notify();
3457            cx.emit(2);
3458        });
3459        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3460        assert_eq!(
3461            handle_2.read(cx).events,
3462            vec![
3463                "observed event 1".to_string(),
3464                "notified".to_string(),
3465                "observed event 2".to_string(),
3466            ]
3467        );
3468
3469        handle_2.update(cx, |model, _| {
3470            drop(handle_1);
3471            model.other.take();
3472        });
3473
3474        assert_eq!(cx.cx.models.len(), 1);
3475        assert!(cx.subscriptions.lock().is_empty());
3476        assert!(cx.observations.lock().is_empty());
3477    }
3478
3479    #[crate::test(self)]
3480    fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
3481        #[derive(Default)]
3482        struct Model {
3483            events: Vec<usize>,
3484        }
3485
3486        impl Entity for Model {
3487            type Event = usize;
3488        }
3489
3490        let handle_1 = cx.add_model(|_| Model::default());
3491        let handle_2 = cx.add_model(|_| Model::default());
3492        let handle_2b = handle_2.clone();
3493
3494        handle_1.update(cx, |_, c| {
3495            c.subscribe(&handle_2, move |model: &mut Model, _, event, c| {
3496                model.events.push(*event);
3497
3498                c.subscribe(&handle_2b, |model, _, event, _| {
3499                    model.events.push(*event * 2);
3500                })
3501                .detach();
3502            })
3503            .detach();
3504        });
3505
3506        handle_2.update(cx, |_, c| c.emit(7));
3507        assert_eq!(handle_1.read(cx).events, vec![7]);
3508
3509        handle_2.update(cx, |_, c| c.emit(5));
3510        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
3511    }
3512
3513    #[crate::test(self)]
3514    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
3515        #[derive(Default)]
3516        struct Model {
3517            count: usize,
3518            events: Vec<usize>,
3519        }
3520
3521        impl Entity for Model {
3522            type Event = ();
3523        }
3524
3525        let handle_1 = cx.add_model(|_| Model::default());
3526        let handle_2 = cx.add_model(|_| Model::default());
3527        let handle_2b = handle_2.clone();
3528
3529        handle_1.update(cx, |_, c| {
3530            c.observe(&handle_2, move |model, observed, c| {
3531                model.events.push(observed.read(c).count);
3532                c.observe(&handle_2b, |model, observed, c| {
3533                    model.events.push(observed.read(c).count * 2);
3534                })
3535                .detach();
3536            })
3537            .detach();
3538        });
3539
3540        handle_2.update(cx, |model, c| {
3541            model.count = 7;
3542            c.notify()
3543        });
3544        assert_eq!(handle_1.read(cx).events, vec![7]);
3545
3546        handle_2.update(cx, |model, c| {
3547            model.count = 5;
3548            c.notify()
3549        });
3550        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
3551    }
3552
3553    #[crate::test(self)]
3554    fn test_view_handles(cx: &mut MutableAppContext) {
3555        struct View {
3556            other: Option<ViewHandle<View>>,
3557            events: Vec<String>,
3558        }
3559
3560        impl Entity for View {
3561            type Event = usize;
3562        }
3563
3564        impl super::View for View {
3565            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3566                Empty::new().boxed()
3567            }
3568
3569            fn ui_name() -> &'static str {
3570                "View"
3571            }
3572        }
3573
3574        impl View {
3575            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
3576                if let Some(other) = other.as_ref() {
3577                    cx.subscribe(other, |me, _, event, _| {
3578                        me.events.push(format!("observed event {}", event));
3579                    })
3580                    .detach();
3581                }
3582                Self {
3583                    other,
3584                    events: Vec::new(),
3585                }
3586            }
3587        }
3588
3589        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
3590        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
3591        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
3592        assert_eq!(cx.cx.views.len(), 3);
3593
3594        handle_1.update(cx, |view, cx| {
3595            view.events.push("updated".into());
3596            cx.emit(1);
3597            cx.emit(2);
3598        });
3599        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3600        assert_eq!(
3601            handle_2.read(cx).events,
3602            vec![
3603                "observed event 1".to_string(),
3604                "observed event 2".to_string(),
3605            ]
3606        );
3607
3608        handle_2.update(cx, |view, _| {
3609            drop(handle_1);
3610            view.other.take();
3611        });
3612
3613        assert_eq!(cx.cx.views.len(), 2);
3614        assert!(cx.subscriptions.lock().is_empty());
3615        assert!(cx.observations.lock().is_empty());
3616    }
3617
3618    #[crate::test(self)]
3619    fn test_add_window(cx: &mut MutableAppContext) {
3620        struct View {
3621            mouse_down_count: Arc<AtomicUsize>,
3622        }
3623
3624        impl Entity for View {
3625            type Event = ();
3626        }
3627
3628        impl super::View for View {
3629            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3630                let mouse_down_count = self.mouse_down_count.clone();
3631                EventHandler::new(Empty::new().boxed())
3632                    .on_mouse_down(move |_| {
3633                        mouse_down_count.fetch_add(1, SeqCst);
3634                        true
3635                    })
3636                    .boxed()
3637            }
3638
3639            fn ui_name() -> &'static str {
3640                "View"
3641            }
3642        }
3643
3644        let mouse_down_count = Arc::new(AtomicUsize::new(0));
3645        let (window_id, _) = cx.add_window(Default::default(), |_| View {
3646            mouse_down_count: mouse_down_count.clone(),
3647        });
3648        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
3649        // Ensure window's root element is in a valid lifecycle state.
3650        presenter.borrow_mut().dispatch_event(
3651            Event::LeftMouseDown {
3652                position: Default::default(),
3653                cmd: false,
3654            },
3655            cx,
3656        );
3657        assert_eq!(mouse_down_count.load(SeqCst), 1);
3658    }
3659
3660    #[crate::test(self)]
3661    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
3662        struct Model {
3663            released: Arc<Mutex<bool>>,
3664        }
3665
3666        struct View {
3667            released: Arc<Mutex<bool>>,
3668        }
3669
3670        impl Entity for Model {
3671            type Event = ();
3672
3673            fn release(&mut self, _: &mut MutableAppContext) {
3674                *self.released.lock() = true;
3675            }
3676        }
3677
3678        impl Entity for View {
3679            type Event = ();
3680
3681            fn release(&mut self, _: &mut MutableAppContext) {
3682                *self.released.lock() = true;
3683            }
3684        }
3685
3686        impl super::View for View {
3687            fn ui_name() -> &'static str {
3688                "View"
3689            }
3690
3691            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3692                Empty::new().boxed()
3693            }
3694        }
3695
3696        let model_released = Arc::new(Mutex::new(false));
3697        let view_released = Arc::new(Mutex::new(false));
3698
3699        let model = cx.add_model(|_| Model {
3700            released: model_released.clone(),
3701        });
3702
3703        let (window_id, _) = cx.add_window(Default::default(), |_| View {
3704            released: view_released.clone(),
3705        });
3706
3707        assert!(!*model_released.lock());
3708        assert!(!*view_released.lock());
3709
3710        cx.update(move || {
3711            drop(model);
3712        });
3713        assert!(*model_released.lock());
3714
3715        drop(cx.remove_window(window_id));
3716        assert!(*view_released.lock());
3717    }
3718
3719    #[crate::test(self)]
3720    fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
3721        #[derive(Default)]
3722        struct View {
3723            events: Vec<usize>,
3724        }
3725
3726        impl Entity for View {
3727            type Event = usize;
3728        }
3729
3730        impl super::View for View {
3731            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3732                Empty::new().boxed()
3733            }
3734
3735            fn ui_name() -> &'static str {
3736                "View"
3737            }
3738        }
3739
3740        struct Model;
3741
3742        impl Entity for Model {
3743            type Event = usize;
3744        }
3745
3746        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
3747        let handle_2 = cx.add_view(window_id, |_| View::default());
3748        let handle_2b = handle_2.clone();
3749        let handle_3 = cx.add_model(|_| Model);
3750
3751        handle_1.update(cx, |_, c| {
3752            c.subscribe(&handle_2, move |me, _, event, c| {
3753                me.events.push(*event);
3754
3755                c.subscribe(&handle_2b, |me, _, event, _| {
3756                    me.events.push(*event * 2);
3757                })
3758                .detach();
3759            })
3760            .detach();
3761
3762            c.subscribe(&handle_3, |me, _, event, _| {
3763                me.events.push(*event);
3764            })
3765            .detach();
3766        });
3767
3768        handle_2.update(cx, |_, c| c.emit(7));
3769        assert_eq!(handle_1.read(cx).events, vec![7]);
3770
3771        handle_2.update(cx, |_, c| c.emit(5));
3772        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
3773
3774        handle_3.update(cx, |_, c| c.emit(9));
3775        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10, 9]);
3776    }
3777
3778    #[crate::test(self)]
3779    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
3780        struct View;
3781
3782        impl Entity for View {
3783            type Event = ();
3784        }
3785
3786        impl super::View for View {
3787            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3788                Empty::new().boxed()
3789            }
3790
3791            fn ui_name() -> &'static str {
3792                "View"
3793            }
3794        }
3795
3796        struct Model;
3797
3798        impl Entity for Model {
3799            type Event = ();
3800        }
3801
3802        let (window_id, _) = cx.add_window(Default::default(), |_| View);
3803        let observing_view = cx.add_view(window_id, |_| View);
3804        let emitting_view = cx.add_view(window_id, |_| View);
3805        let observing_model = cx.add_model(|_| Model);
3806        let observed_model = cx.add_model(|_| Model);
3807
3808        observing_view.update(cx, |_, cx| {
3809            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
3810            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
3811        });
3812        observing_model.update(cx, |_, cx| {
3813            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
3814        });
3815
3816        cx.update(|| {
3817            drop(observing_view);
3818            drop(observing_model);
3819        });
3820
3821        emitting_view.update(cx, |_, cx| cx.emit(()));
3822        observed_model.update(cx, |_, cx| cx.emit(()));
3823    }
3824
3825    #[crate::test(self)]
3826    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
3827        #[derive(Default)]
3828        struct View {
3829            events: Vec<usize>,
3830        }
3831
3832        impl Entity for View {
3833            type Event = usize;
3834        }
3835
3836        impl super::View for View {
3837            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3838                Empty::new().boxed()
3839            }
3840
3841            fn ui_name() -> &'static str {
3842                "View"
3843            }
3844        }
3845
3846        #[derive(Default)]
3847        struct Model {
3848            count: usize,
3849        }
3850
3851        impl Entity for Model {
3852            type Event = ();
3853        }
3854
3855        let (_, view) = cx.add_window(Default::default(), |_| View::default());
3856        let model = cx.add_model(|_| Model::default());
3857
3858        view.update(cx, |_, c| {
3859            c.observe(&model, |me, observed, c| {
3860                me.events.push(observed.read(c).count)
3861            })
3862            .detach();
3863        });
3864
3865        model.update(cx, |model, c| {
3866            model.count = 11;
3867            c.notify();
3868        });
3869        assert_eq!(view.read(cx).events, vec![11]);
3870    }
3871
3872    #[crate::test(self)]
3873    fn test_dropping_observers(cx: &mut MutableAppContext) {
3874        struct View;
3875
3876        impl Entity for View {
3877            type Event = ();
3878        }
3879
3880        impl super::View for View {
3881            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3882                Empty::new().boxed()
3883            }
3884
3885            fn ui_name() -> &'static str {
3886                "View"
3887            }
3888        }
3889
3890        struct Model;
3891
3892        impl Entity for Model {
3893            type Event = ();
3894        }
3895
3896        let (window_id, _) = cx.add_window(Default::default(), |_| View);
3897        let observing_view = cx.add_view(window_id, |_| View);
3898        let observing_model = cx.add_model(|_| Model);
3899        let observed_model = cx.add_model(|_| Model);
3900
3901        observing_view.update(cx, |_, cx| {
3902            cx.observe(&observed_model, |_, _, _| {}).detach();
3903        });
3904        observing_model.update(cx, |_, cx| {
3905            cx.observe(&observed_model, |_, _, _| {}).detach();
3906        });
3907
3908        cx.update(|| {
3909            drop(observing_view);
3910            drop(observing_model);
3911        });
3912
3913        observed_model.update(cx, |_, cx| cx.notify());
3914    }
3915
3916    #[crate::test(self)]
3917    fn test_focus(cx: &mut MutableAppContext) {
3918        struct View {
3919            name: String,
3920            events: Arc<Mutex<Vec<String>>>,
3921        }
3922
3923        impl Entity for View {
3924            type Event = ();
3925        }
3926
3927        impl super::View for View {
3928            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3929                Empty::new().boxed()
3930            }
3931
3932            fn ui_name() -> &'static str {
3933                "View"
3934            }
3935
3936            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
3937                self.events.lock().push(format!("{} focused", &self.name));
3938            }
3939
3940            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
3941                self.events.lock().push(format!("{} blurred", &self.name));
3942            }
3943        }
3944
3945        let events: Arc<Mutex<Vec<String>>> = Default::default();
3946        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
3947            events: events.clone(),
3948            name: "view 1".to_string(),
3949        });
3950        let view_2 = cx.add_view(window_id, |_| View {
3951            events: events.clone(),
3952            name: "view 2".to_string(),
3953        });
3954
3955        view_1.update(cx, |_, cx| cx.focus(&view_2));
3956        view_1.update(cx, |_, cx| cx.focus(&view_1));
3957        view_1.update(cx, |_, cx| cx.focus(&view_2));
3958        view_1.update(cx, |_, _| drop(view_2));
3959
3960        assert_eq!(
3961            *events.lock(),
3962            [
3963                "view 1 focused".to_string(),
3964                "view 1 blurred".to_string(),
3965                "view 2 focused".to_string(),
3966                "view 2 blurred".to_string(),
3967                "view 1 focused".to_string(),
3968                "view 1 blurred".to_string(),
3969                "view 2 focused".to_string(),
3970                "view 1 focused".to_string(),
3971            ],
3972        );
3973    }
3974
3975    #[crate::test(self)]
3976    fn test_dispatch_action(cx: &mut MutableAppContext) {
3977        struct ViewA {
3978            id: usize,
3979        }
3980
3981        impl Entity for ViewA {
3982            type Event = ();
3983        }
3984
3985        impl View for ViewA {
3986            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3987                Empty::new().boxed()
3988            }
3989
3990            fn ui_name() -> &'static str {
3991                "View"
3992            }
3993        }
3994
3995        struct ViewB {
3996            id: usize,
3997        }
3998
3999        impl Entity for ViewB {
4000            type Event = ();
4001        }
4002
4003        impl View for ViewB {
4004            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4005                Empty::new().boxed()
4006            }
4007
4008            fn ui_name() -> &'static str {
4009                "View"
4010            }
4011        }
4012
4013        action!(Action, &'static str);
4014
4015        let actions = Rc::new(RefCell::new(Vec::new()));
4016
4017        let actions_clone = actions.clone();
4018        cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
4019            actions_clone.borrow_mut().push("global a".to_string());
4020        });
4021
4022        let actions_clone = actions.clone();
4023        cx.add_global_action(move |_: &Action, _: &mut MutableAppContext| {
4024            actions_clone.borrow_mut().push("global b".to_string());
4025        });
4026
4027        let actions_clone = actions.clone();
4028        cx.add_action(move |view: &mut ViewA, action: &Action, cx| {
4029            assert_eq!(action.0, "bar");
4030            cx.propagate_action();
4031            actions_clone.borrow_mut().push(format!("{} a", view.id));
4032        });
4033
4034        let actions_clone = actions.clone();
4035        cx.add_action(move |view: &mut ViewA, _: &Action, cx| {
4036            if view.id != 1 {
4037                cx.propagate_action();
4038            }
4039            actions_clone.borrow_mut().push(format!("{} b", view.id));
4040        });
4041
4042        let actions_clone = actions.clone();
4043        cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4044            cx.propagate_action();
4045            actions_clone.borrow_mut().push(format!("{} c", view.id));
4046        });
4047
4048        let actions_clone = actions.clone();
4049        cx.add_action(move |view: &mut ViewB, _: &Action, cx| {
4050            cx.propagate_action();
4051            actions_clone.borrow_mut().push(format!("{} d", view.id));
4052        });
4053
4054        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
4055        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
4056        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
4057        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
4058
4059        cx.dispatch_action(
4060            window_id,
4061            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
4062            &Action("bar"),
4063        );
4064
4065        assert_eq!(
4066            *actions.borrow(),
4067            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "1 b"]
4068        );
4069
4070        // Remove view_1, which doesn't propagate the action
4071        actions.borrow_mut().clear();
4072        cx.dispatch_action(
4073            window_id,
4074            vec![view_2.id(), view_3.id(), view_4.id()],
4075            &Action("bar"),
4076        );
4077
4078        assert_eq!(
4079            *actions.borrow(),
4080            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "global b", "global a"]
4081        );
4082    }
4083
4084    #[crate::test(self)]
4085    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
4086        use std::cell::Cell;
4087
4088        action!(Action, &'static str);
4089
4090        struct View {
4091            id: usize,
4092            keymap_context: keymap::Context,
4093        }
4094
4095        impl Entity for View {
4096            type Event = ();
4097        }
4098
4099        impl super::View for View {
4100            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4101                Empty::new().boxed()
4102            }
4103
4104            fn ui_name() -> &'static str {
4105                "View"
4106            }
4107
4108            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
4109                self.keymap_context.clone()
4110            }
4111        }
4112
4113        impl View {
4114            fn new(id: usize) -> Self {
4115                View {
4116                    id,
4117                    keymap_context: keymap::Context::default(),
4118                }
4119            }
4120        }
4121
4122        let mut view_1 = View::new(1);
4123        let mut view_2 = View::new(2);
4124        let mut view_3 = View::new(3);
4125        view_1.keymap_context.set.insert("a".into());
4126        view_2.keymap_context.set.insert("b".into());
4127        view_3.keymap_context.set.insert("c".into());
4128
4129        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
4130        let view_2 = cx.add_view(window_id, |_| view_2);
4131        let view_3 = cx.add_view(window_id, |_| view_3);
4132
4133        // This keymap's only binding dispatches an action on view 2 because that view will have
4134        // "a" and "b" in its context, but not "c".
4135        cx.add_bindings(vec![keymap::Binding::new(
4136            "a",
4137            Action("a"),
4138            Some("a && b && !c"),
4139        )]);
4140
4141        let handled_action = Rc::new(Cell::new(false));
4142        let handled_action_clone = handled_action.clone();
4143        cx.add_action(move |view: &mut View, action: &Action, _| {
4144            handled_action_clone.set(true);
4145            assert_eq!(view.id, 2);
4146            assert_eq!(action.0, "a");
4147        });
4148
4149        cx.dispatch_keystroke(
4150            window_id,
4151            vec![view_1.id(), view_2.id(), view_3.id()],
4152            &Keystroke::parse("a").unwrap(),
4153        )
4154        .unwrap();
4155
4156        assert!(handled_action.get());
4157    }
4158
4159    #[crate::test(self)]
4160    async fn test_model_condition(mut cx: TestAppContext) {
4161        struct Counter(usize);
4162
4163        impl super::Entity for Counter {
4164            type Event = ();
4165        }
4166
4167        impl Counter {
4168            fn inc(&mut self, cx: &mut ModelContext<Self>) {
4169                self.0 += 1;
4170                cx.notify();
4171            }
4172        }
4173
4174        let model = cx.add_model(|_| Counter(0));
4175
4176        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
4177        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
4178        smol::pin!(condition1, condition2);
4179
4180        model.update(&mut cx, |model, cx| model.inc(cx));
4181        assert_eq!(poll_once(&mut condition1).await, None);
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 condition1).await, Some(()));
4186        assert_eq!(poll_once(&mut condition2).await, None);
4187
4188        model.update(&mut cx, |model, cx| model.inc(cx));
4189        assert_eq!(poll_once(&mut condition2).await, Some(()));
4190
4191        model.update(&mut cx, |_, cx| cx.notify());
4192    }
4193
4194    #[crate::test(self)]
4195    #[should_panic]
4196    async fn test_model_condition_timeout(mut cx: TestAppContext) {
4197        struct Model;
4198
4199        impl super::Entity for Model {
4200            type Event = ();
4201        }
4202
4203        let model = cx.add_model(|_| Model);
4204        model.condition(&cx, |_, _| false).await;
4205    }
4206
4207    #[crate::test(self)]
4208    #[should_panic(expected = "model dropped with pending condition")]
4209    async fn test_model_condition_panic_on_drop(mut cx: TestAppContext) {
4210        struct Model;
4211
4212        impl super::Entity for Model {
4213            type Event = ();
4214        }
4215
4216        let model = cx.add_model(|_| Model);
4217        let condition = model.condition(&cx, |_, _| false);
4218        cx.update(|_| drop(model));
4219        condition.await;
4220    }
4221
4222    #[crate::test(self)]
4223    async fn test_view_condition(mut cx: TestAppContext) {
4224        struct Counter(usize);
4225
4226        impl super::Entity for Counter {
4227            type Event = ();
4228        }
4229
4230        impl super::View for Counter {
4231            fn ui_name() -> &'static str {
4232                "test view"
4233            }
4234
4235            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4236                Empty::new().boxed()
4237            }
4238        }
4239
4240        impl Counter {
4241            fn inc(&mut self, cx: &mut ViewContext<Self>) {
4242                self.0 += 1;
4243                cx.notify();
4244            }
4245        }
4246
4247        let (_, view) = cx.add_window(|_| Counter(0));
4248
4249        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
4250        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
4251        smol::pin!(condition1, condition2);
4252
4253        view.update(&mut cx, |view, cx| view.inc(cx));
4254        assert_eq!(poll_once(&mut condition1).await, None);
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 condition1).await, Some(()));
4259        assert_eq!(poll_once(&mut condition2).await, None);
4260
4261        view.update(&mut cx, |view, cx| view.inc(cx));
4262        assert_eq!(poll_once(&mut condition2).await, Some(()));
4263        view.update(&mut cx, |_, cx| cx.notify());
4264    }
4265
4266    #[crate::test(self)]
4267    #[should_panic]
4268    async fn test_view_condition_timeout(mut cx: TestAppContext) {
4269        struct View;
4270
4271        impl super::Entity for View {
4272            type Event = ();
4273        }
4274
4275        impl super::View for View {
4276            fn ui_name() -> &'static str {
4277                "test view"
4278            }
4279
4280            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4281                Empty::new().boxed()
4282            }
4283        }
4284
4285        let (_, view) = cx.add_window(|_| View);
4286        view.condition(&cx, |_, _| false).await;
4287    }
4288
4289    #[crate::test(self)]
4290    #[should_panic(expected = "view dropped with pending condition")]
4291    async fn test_view_condition_panic_on_drop(mut cx: TestAppContext) {
4292        struct View;
4293
4294        impl super::Entity for View {
4295            type Event = ();
4296        }
4297
4298        impl super::View for View {
4299            fn ui_name() -> &'static str {
4300                "test view"
4301            }
4302
4303            fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
4304                Empty::new().boxed()
4305            }
4306        }
4307
4308        let window_id = cx.add_window(|_| View).0;
4309        let view = cx.add_view(window_id, |_| View);
4310
4311        let condition = view.condition(&cx, |_, _| false);
4312        cx.update(|_| drop(view));
4313        condition.await;
4314    }
4315}