app.rs

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