app.rs

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