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