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_view(&self, window_id: usize, view_id: usize) -> Result<ElementBox> {
 751        self.cx.render_view(window_id, view_id)
 752    }
 753
 754    pub fn render_views(&self, window_id: usize) -> HashMap<usize, ElementBox> {
 755        self.cx.render_views(window_id)
 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            self.cx.font_cache.clone(),
1023            text_layout_cache,
1024            self.assets.clone(),
1025            self,
1026        )));
1027
1028        {
1029            let mut app = self.upgrade();
1030            let presenter = presenter.clone();
1031            window.on_event(Box::new(move |event| {
1032                app.update(|cx| {
1033                    if let Event::KeyDown { keystroke, .. } = &event {
1034                        if cx
1035                            .dispatch_keystroke(
1036                                window_id,
1037                                presenter.borrow().dispatch_path(cx.as_ref()),
1038                                keystroke,
1039                            )
1040                            .unwrap()
1041                        {
1042                            return;
1043                        }
1044                    }
1045
1046                    presenter.borrow_mut().dispatch_event(event, cx);
1047                })
1048            }));
1049        }
1050
1051        {
1052            let mut app = self.upgrade();
1053            let presenter = presenter.clone();
1054            window.on_resize(Box::new(move |window| {
1055                app.update(|cx| {
1056                    let scene = presenter.borrow_mut().build_scene(
1057                        window.size(),
1058                        window.titlebar_height(),
1059                        window.scale_factor(),
1060                        cx,
1061                    );
1062                    window.present_scene(scene);
1063                })
1064            }));
1065        }
1066
1067        {
1068            let mut app = self.upgrade();
1069            window.on_close(Box::new(move || {
1070                app.update(|cx| cx.remove_window(window_id));
1071            }));
1072        }
1073
1074        self.presenters_and_platform_windows
1075            .insert(window_id, (presenter.clone(), window));
1076
1077        self.on_debug_elements(window_id, move |cx| {
1078            presenter.borrow().debug_elements(cx).unwrap()
1079        });
1080    }
1081
1082    pub fn add_view<T, F>(&mut self, window_id: usize, build_view: F) -> ViewHandle<T>
1083    where
1084        T: View,
1085        F: FnOnce(&mut ViewContext<T>) -> T,
1086    {
1087        self.add_option_view(window_id, |cx| Some(build_view(cx)))
1088            .unwrap()
1089    }
1090
1091    pub fn add_option_view<T, F>(
1092        &mut self,
1093        window_id: usize,
1094        build_view: F,
1095    ) -> Option<ViewHandle<T>>
1096    where
1097        T: View,
1098        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1099    {
1100        let view_id = post_inc(&mut self.next_entity_id);
1101        self.pending_flushes += 1;
1102        let handle = ViewHandle::new(window_id, view_id, &self.cx.ref_counts);
1103        let mut cx = ViewContext::new(self, window_id, view_id);
1104        let handle = if let Some(view) = build_view(&mut cx) {
1105            self.cx.views.insert((window_id, view_id), Box::new(view));
1106            if let Some(window) = self.cx.windows.get_mut(&window_id) {
1107                window
1108                    .invalidation
1109                    .get_or_insert_with(Default::default)
1110                    .updated
1111                    .insert(view_id);
1112            }
1113            Some(handle)
1114        } else {
1115            None
1116        };
1117        self.flush_effects();
1118        handle
1119    }
1120
1121    fn remove_dropped_entities(&mut self) {
1122        loop {
1123            let (dropped_models, dropped_views, dropped_values) =
1124                self.cx.ref_counts.lock().take_dropped();
1125            if dropped_models.is_empty() && dropped_views.is_empty() && dropped_values.is_empty() {
1126                break;
1127            }
1128
1129            for model_id in dropped_models {
1130                self.subscriptions.remove(&model_id);
1131                self.model_observations.remove(&model_id);
1132                let mut model = self.cx.models.remove(&model_id).unwrap();
1133                model.release(self);
1134            }
1135
1136            for (window_id, view_id) in dropped_views {
1137                self.subscriptions.remove(&view_id);
1138                self.model_observations.remove(&view_id);
1139                let mut view = self.cx.views.remove(&(window_id, view_id)).unwrap();
1140                view.release(self);
1141                let change_focus_to = self.cx.windows.get_mut(&window_id).and_then(|window| {
1142                    window
1143                        .invalidation
1144                        .get_or_insert_with(Default::default)
1145                        .removed
1146                        .push(view_id);
1147                    if window.focused_view_id == view_id {
1148                        Some(window.root_view.id())
1149                    } else {
1150                        None
1151                    }
1152                });
1153
1154                if let Some(view_id) = change_focus_to {
1155                    self.focus(window_id, view_id);
1156                }
1157            }
1158
1159            let mut values = self.cx.values.write();
1160            for key in dropped_values {
1161                values.remove(&key);
1162            }
1163        }
1164    }
1165
1166    fn flush_effects(&mut self) {
1167        self.pending_flushes = self.pending_flushes.saturating_sub(1);
1168
1169        if !self.flushing_effects && self.pending_flushes == 0 {
1170            self.flushing_effects = true;
1171
1172            loop {
1173                if let Some(effect) = self.pending_effects.pop_front() {
1174                    match effect {
1175                        Effect::Event { entity_id, payload } => self.emit_event(entity_id, payload),
1176                        Effect::ModelNotification { model_id } => {
1177                            self.notify_model_observers(model_id)
1178                        }
1179                        Effect::ViewNotification { window_id, view_id } => {
1180                            self.notify_view_observers(window_id, view_id)
1181                        }
1182                        Effect::Focus { window_id, view_id } => {
1183                            self.focus(window_id, view_id);
1184                        }
1185                    }
1186                    self.remove_dropped_entities();
1187                } else {
1188                    self.remove_dropped_entities();
1189                    self.update_windows();
1190
1191                    if self.pending_effects.is_empty() {
1192                        self.flushing_effects = false;
1193                        break;
1194                    }
1195                }
1196            }
1197        }
1198    }
1199
1200    fn update_windows(&mut self) {
1201        let mut invalidations = HashMap::new();
1202        for (window_id, window) in &mut self.cx.windows {
1203            if let Some(invalidation) = window.invalidation.take() {
1204                invalidations.insert(*window_id, invalidation);
1205            }
1206        }
1207
1208        for (window_id, invalidation) in invalidations {
1209            if let Some((presenter, mut window)) =
1210                self.presenters_and_platform_windows.remove(&window_id)
1211            {
1212                {
1213                    let mut presenter = presenter.borrow_mut();
1214                    presenter.invalidate(invalidation, self.as_ref());
1215                    let scene = presenter.build_scene(
1216                        window.size(),
1217                        window.titlebar_height(),
1218                        window.scale_factor(),
1219                        self,
1220                    );
1221                    window.present_scene(scene);
1222                }
1223                self.presenters_and_platform_windows
1224                    .insert(window_id, (presenter, window));
1225            }
1226        }
1227    }
1228
1229    fn emit_event(&mut self, entity_id: usize, payload: Box<dyn Any>) {
1230        if let Some(subscriptions) = self.subscriptions.remove(&entity_id) {
1231            for mut subscription in subscriptions {
1232                let alive = match &mut subscription {
1233                    Subscription::FromModel { model_id, callback } => {
1234                        if let Some(mut model) = self.cx.models.remove(model_id) {
1235                            callback(model.as_any_mut(), payload.as_ref(), self, *model_id);
1236                            self.cx.models.insert(*model_id, model);
1237                            true
1238                        } else {
1239                            false
1240                        }
1241                    }
1242                    Subscription::FromView {
1243                        window_id,
1244                        view_id,
1245                        callback,
1246                    } => {
1247                        if let Some(mut view) = self.cx.views.remove(&(*window_id, *view_id)) {
1248                            callback(
1249                                view.as_any_mut(),
1250                                payload.as_ref(),
1251                                self,
1252                                *window_id,
1253                                *view_id,
1254                            );
1255                            self.cx.views.insert((*window_id, *view_id), view);
1256                            true
1257                        } else {
1258                            false
1259                        }
1260                    }
1261                };
1262
1263                if alive {
1264                    self.subscriptions
1265                        .entry(entity_id)
1266                        .or_default()
1267                        .push(subscription);
1268                }
1269            }
1270        }
1271    }
1272
1273    fn notify_model_observers(&mut self, observed_id: usize) {
1274        if let Some(observations) = self.model_observations.remove(&observed_id) {
1275            if self.cx.models.contains_key(&observed_id) {
1276                for mut observation in observations {
1277                    let alive = match &mut observation {
1278                        ModelObservation::FromModel { model_id, callback } => {
1279                            if let Some(mut model) = self.cx.models.remove(model_id) {
1280                                callback(model.as_any_mut(), observed_id, self, *model_id);
1281                                self.cx.models.insert(*model_id, model);
1282                                true
1283                            } else {
1284                                false
1285                            }
1286                        }
1287                        ModelObservation::FromView {
1288                            window_id,
1289                            view_id,
1290                            callback,
1291                        } => {
1292                            if let Some(mut view) = self.cx.views.remove(&(*window_id, *view_id)) {
1293                                callback(
1294                                    view.as_any_mut(),
1295                                    observed_id,
1296                                    self,
1297                                    *window_id,
1298                                    *view_id,
1299                                );
1300                                self.cx.views.insert((*window_id, *view_id), view);
1301                                true
1302                            } else {
1303                                false
1304                            }
1305                        }
1306                    };
1307
1308                    if alive {
1309                        self.model_observations
1310                            .entry(observed_id)
1311                            .or_default()
1312                            .push(observation);
1313                    }
1314                }
1315            }
1316        }
1317    }
1318
1319    fn notify_view_observers(&mut self, window_id: usize, view_id: usize) {
1320        if let Some(window) = self.cx.windows.get_mut(&window_id) {
1321            window
1322                .invalidation
1323                .get_or_insert_with(Default::default)
1324                .updated
1325                .insert(view_id);
1326        }
1327
1328        if let Some(observations) = self.view_observations.remove(&view_id) {
1329            if self.cx.views.contains_key(&(window_id, view_id)) {
1330                for mut observation in observations {
1331                    let alive = if let Some(mut view) = self
1332                        .cx
1333                        .views
1334                        .remove(&(observation.window_id, observation.view_id))
1335                    {
1336                        (observation.callback)(
1337                            view.as_any_mut(),
1338                            view_id,
1339                            window_id,
1340                            self,
1341                            observation.window_id,
1342                            observation.view_id,
1343                        );
1344                        self.cx
1345                            .views
1346                            .insert((observation.window_id, observation.view_id), view);
1347                        true
1348                    } else {
1349                        false
1350                    };
1351
1352                    if alive {
1353                        self.view_observations
1354                            .entry(view_id)
1355                            .or_default()
1356                            .push(observation);
1357                    }
1358                }
1359            }
1360        }
1361    }
1362
1363    fn focus(&mut self, window_id: usize, focused_id: usize) {
1364        if self
1365            .cx
1366            .windows
1367            .get(&window_id)
1368            .map(|w| w.focused_view_id)
1369            .map_or(false, |cur_focused| cur_focused == focused_id)
1370        {
1371            return;
1372        }
1373
1374        self.pending_flushes += 1;
1375
1376        let blurred_id = self.cx.windows.get_mut(&window_id).map(|window| {
1377            let blurred_id = window.focused_view_id;
1378            window.focused_view_id = focused_id;
1379            blurred_id
1380        });
1381
1382        if let Some(blurred_id) = blurred_id {
1383            if let Some(mut blurred_view) = self.cx.views.remove(&(window_id, blurred_id)) {
1384                blurred_view.on_blur(self, window_id, blurred_id);
1385                self.cx.views.insert((window_id, blurred_id), blurred_view);
1386            }
1387        }
1388
1389        if let Some(mut focused_view) = self.cx.views.remove(&(window_id, focused_id)) {
1390            focused_view.on_focus(self, window_id, focused_id);
1391            self.cx.views.insert((window_id, focused_id), focused_view);
1392        }
1393
1394        self.flush_effects();
1395    }
1396
1397    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
1398    where
1399        F: FnOnce(AsyncAppContext) -> Fut,
1400        Fut: 'static + Future<Output = T>,
1401        T: 'static,
1402    {
1403        let cx = self.to_async();
1404        self.foreground.spawn(f(cx))
1405    }
1406
1407    pub fn to_async(&self) -> AsyncAppContext {
1408        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
1409    }
1410
1411    pub fn write_to_clipboard(&self, item: ClipboardItem) {
1412        self.cx.platform.write_to_clipboard(item);
1413    }
1414
1415    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1416        self.cx.platform.read_from_clipboard()
1417    }
1418}
1419
1420impl ReadModel for MutableAppContext {
1421    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1422        if let Some(model) = self.cx.models.get(&handle.model_id) {
1423            model
1424                .as_any()
1425                .downcast_ref()
1426                .expect("downcast is type safe")
1427        } else {
1428            panic!("circular model reference");
1429        }
1430    }
1431}
1432
1433impl UpdateModel for MutableAppContext {
1434    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
1435    where
1436        T: Entity,
1437        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
1438    {
1439        if let Some(mut model) = self.cx.models.remove(&handle.model_id) {
1440            self.pending_flushes += 1;
1441            let mut cx = ModelContext::new(self, handle.model_id);
1442            let result = update(
1443                model
1444                    .as_any_mut()
1445                    .downcast_mut()
1446                    .expect("downcast is type safe"),
1447                &mut cx,
1448            );
1449            self.cx.models.insert(handle.model_id, model);
1450            self.flush_effects();
1451            result
1452        } else {
1453            panic!("circular model update");
1454        }
1455    }
1456}
1457
1458impl UpgradeModelHandle for MutableAppContext {
1459    fn upgrade_model_handle<T: Entity>(
1460        &self,
1461        handle: WeakModelHandle<T>,
1462    ) -> Option<ModelHandle<T>> {
1463        self.cx.upgrade_model_handle(handle)
1464    }
1465}
1466
1467impl ReadView for MutableAppContext {
1468    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1469        if let Some(view) = self.cx.views.get(&(handle.window_id, handle.view_id)) {
1470            view.as_any().downcast_ref().expect("downcast is type safe")
1471        } else {
1472            panic!("circular view reference");
1473        }
1474    }
1475}
1476
1477impl UpdateView for MutableAppContext {
1478    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
1479    where
1480        T: View,
1481        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
1482    {
1483        self.pending_flushes += 1;
1484        let mut view = self
1485            .cx
1486            .views
1487            .remove(&(handle.window_id, handle.view_id))
1488            .expect("circular view update");
1489
1490        let mut cx = ViewContext::new(self, handle.window_id, handle.view_id);
1491        let result = update(
1492            view.as_any_mut()
1493                .downcast_mut()
1494                .expect("downcast is type safe"),
1495            &mut cx,
1496        );
1497        self.cx
1498            .views
1499            .insert((handle.window_id, handle.view_id), view);
1500        self.flush_effects();
1501        result
1502    }
1503}
1504
1505impl AsRef<AppContext> for MutableAppContext {
1506    fn as_ref(&self) -> &AppContext {
1507        &self.cx
1508    }
1509}
1510
1511impl Deref for MutableAppContext {
1512    type Target = AppContext;
1513
1514    fn deref(&self) -> &Self::Target {
1515        &self.cx
1516    }
1517}
1518
1519pub struct AppContext {
1520    models: HashMap<usize, Box<dyn AnyModel>>,
1521    views: HashMap<(usize, usize), Box<dyn AnyView>>,
1522    windows: HashMap<usize, Window>,
1523    values: RwLock<HashMap<(TypeId, usize), Box<dyn Any>>>,
1524    background: Arc<executor::Background>,
1525    ref_counts: Arc<Mutex<RefCounts>>,
1526    font_cache: Arc<FontCache>,
1527    platform: Arc<dyn Platform>,
1528}
1529
1530impl AppContext {
1531    pub fn root_view_id(&self, window_id: usize) -> Option<usize> {
1532        self.windows
1533            .get(&window_id)
1534            .map(|window| window.root_view.id())
1535    }
1536
1537    pub fn focused_view_id(&self, window_id: usize) -> Option<usize> {
1538        self.windows
1539            .get(&window_id)
1540            .map(|window| window.focused_view_id)
1541    }
1542
1543    pub fn render_view(&self, window_id: usize, view_id: usize) -> Result<ElementBox> {
1544        self.views
1545            .get(&(window_id, view_id))
1546            .map(|v| v.render(window_id, view_id, self))
1547            .ok_or(anyhow!("view not found"))
1548    }
1549
1550    pub fn render_views(&self, window_id: usize) -> HashMap<usize, ElementBox> {
1551        self.views
1552            .iter()
1553            .filter_map(|((win_id, view_id), view)| {
1554                if *win_id == window_id {
1555                    Some((*view_id, view.render(*win_id, *view_id, self)))
1556                } else {
1557                    None
1558                }
1559            })
1560            .collect::<HashMap<_, ElementBox>>()
1561    }
1562
1563    pub fn background(&self) -> &Arc<executor::Background> {
1564        &self.background
1565    }
1566
1567    pub fn font_cache(&self) -> &Arc<FontCache> {
1568        &self.font_cache
1569    }
1570
1571    pub fn platform(&self) -> &Arc<dyn Platform> {
1572        &self.platform
1573    }
1574
1575    pub fn value<Tag: 'static, T: 'static + Default>(&self, id: usize) -> ValueHandle<T> {
1576        let key = (TypeId::of::<Tag>(), id);
1577        self.values
1578            .write()
1579            .entry(key)
1580            .or_insert_with(|| Box::new(T::default()));
1581        ValueHandle::new(TypeId::of::<Tag>(), id, &self.ref_counts)
1582    }
1583}
1584
1585impl ReadModel for AppContext {
1586    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1587        if let Some(model) = self.models.get(&handle.model_id) {
1588            model
1589                .as_any()
1590                .downcast_ref()
1591                .expect("downcast should be type safe")
1592        } else {
1593            panic!("circular model reference");
1594        }
1595    }
1596}
1597
1598impl UpgradeModelHandle for AppContext {
1599    fn upgrade_model_handle<T: Entity>(
1600        &self,
1601        handle: WeakModelHandle<T>,
1602    ) -> Option<ModelHandle<T>> {
1603        if self.models.contains_key(&handle.model_id) {
1604            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
1605        } else {
1606            None
1607        }
1608    }
1609}
1610
1611impl ReadView for AppContext {
1612    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1613        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
1614            view.as_any()
1615                .downcast_ref()
1616                .expect("downcast should be type safe")
1617        } else {
1618            panic!("circular view reference");
1619        }
1620    }
1621}
1622
1623struct Window {
1624    root_view: AnyViewHandle,
1625    focused_view_id: usize,
1626    invalidation: Option<WindowInvalidation>,
1627}
1628
1629#[derive(Default, Clone)]
1630pub struct WindowInvalidation {
1631    pub updated: HashSet<usize>,
1632    pub removed: Vec<usize>,
1633}
1634
1635pub enum Effect {
1636    Event {
1637        entity_id: usize,
1638        payload: Box<dyn Any>,
1639    },
1640    ModelNotification {
1641        model_id: usize,
1642    },
1643    ViewNotification {
1644        window_id: usize,
1645        view_id: usize,
1646    },
1647    Focus {
1648        window_id: usize,
1649        view_id: usize,
1650    },
1651}
1652
1653impl Debug for Effect {
1654    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1655        match self {
1656            Effect::Event { entity_id, .. } => f
1657                .debug_struct("Effect::Event")
1658                .field("entity_id", entity_id)
1659                .finish(),
1660            Effect::ModelNotification { model_id } => f
1661                .debug_struct("Effect::ModelNotification")
1662                .field("model_id", model_id)
1663                .finish(),
1664            Effect::ViewNotification { window_id, view_id } => f
1665                .debug_struct("Effect::ViewNotification")
1666                .field("window_id", window_id)
1667                .field("view_id", view_id)
1668                .finish(),
1669            Effect::Focus { window_id, view_id } => f
1670                .debug_struct("Effect::Focus")
1671                .field("window_id", window_id)
1672                .field("view_id", view_id)
1673                .finish(),
1674        }
1675    }
1676}
1677
1678pub trait AnyModel: Send + Sync {
1679    fn as_any(&self) -> &dyn Any;
1680    fn as_any_mut(&mut self) -> &mut dyn Any;
1681    fn release(&mut self, cx: &mut MutableAppContext);
1682}
1683
1684impl<T> AnyModel for T
1685where
1686    T: Entity,
1687{
1688    fn as_any(&self) -> &dyn Any {
1689        self
1690    }
1691
1692    fn as_any_mut(&mut self) -> &mut dyn Any {
1693        self
1694    }
1695
1696    fn release(&mut self, cx: &mut MutableAppContext) {
1697        self.release(cx);
1698    }
1699}
1700
1701pub trait AnyView: Send + Sync {
1702    fn as_any(&self) -> &dyn Any;
1703    fn as_any_mut(&mut self) -> &mut dyn Any;
1704    fn release(&mut self, cx: &mut MutableAppContext);
1705    fn ui_name(&self) -> &'static str;
1706    fn render<'a>(&self, window_id: usize, view_id: usize, cx: &AppContext) -> ElementBox;
1707    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
1708    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize);
1709    fn keymap_context(&self, cx: &AppContext) -> keymap::Context;
1710}
1711
1712impl<T> AnyView for T
1713where
1714    T: View,
1715{
1716    fn as_any(&self) -> &dyn Any {
1717        self
1718    }
1719
1720    fn as_any_mut(&mut self) -> &mut dyn Any {
1721        self
1722    }
1723
1724    fn release(&mut self, cx: &mut MutableAppContext) {
1725        self.release(cx);
1726    }
1727
1728    fn ui_name(&self) -> &'static str {
1729        T::ui_name()
1730    }
1731
1732    fn render<'a>(&self, window_id: usize, view_id: usize, cx: &AppContext) -> ElementBox {
1733        View::render(
1734            self,
1735            &RenderContext {
1736                window_id,
1737                view_id,
1738                app: cx,
1739                view_type: PhantomData::<T>,
1740            },
1741        )
1742    }
1743
1744    fn on_focus(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
1745        let mut cx = ViewContext::new(cx, window_id, view_id);
1746        View::on_focus(self, &mut cx);
1747    }
1748
1749    fn on_blur(&mut self, cx: &mut MutableAppContext, window_id: usize, view_id: usize) {
1750        let mut cx = ViewContext::new(cx, window_id, view_id);
1751        View::on_blur(self, &mut cx);
1752    }
1753
1754    fn keymap_context(&self, cx: &AppContext) -> keymap::Context {
1755        View::keymap_context(self, cx)
1756    }
1757}
1758
1759pub struct ModelContext<'a, T: ?Sized> {
1760    app: &'a mut MutableAppContext,
1761    model_id: usize,
1762    model_type: PhantomData<T>,
1763    halt_stream: bool,
1764}
1765
1766impl<'a, T: Entity> ModelContext<'a, T> {
1767    fn new(app: &'a mut MutableAppContext, model_id: usize) -> Self {
1768        Self {
1769            app,
1770            model_id,
1771            model_type: PhantomData,
1772            halt_stream: false,
1773        }
1774    }
1775
1776    pub fn background(&self) -> &Arc<executor::Background> {
1777        &self.app.cx.background
1778    }
1779
1780    pub fn halt_stream(&mut self) {
1781        self.halt_stream = true;
1782    }
1783
1784    pub fn model_id(&self) -> usize {
1785        self.model_id
1786    }
1787
1788    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
1789    where
1790        S: Entity,
1791        F: FnOnce(&mut ModelContext<S>) -> S,
1792    {
1793        self.app.add_model(build_model)
1794    }
1795
1796    pub fn subscribe<S: Entity, F>(&mut self, handle: &ModelHandle<S>, mut callback: F)
1797    where
1798        S::Event: 'static,
1799        F: 'static + FnMut(&mut T, &S::Event, &mut ModelContext<T>),
1800    {
1801        self.app
1802            .subscriptions
1803            .entry(handle.model_id)
1804            .or_default()
1805            .push(Subscription::FromModel {
1806                model_id: self.model_id,
1807                callback: Box::new(move |model, payload, app, model_id| {
1808                    let model = model.downcast_mut().expect("downcast is type safe");
1809                    let payload = payload.downcast_ref().expect("downcast is type safe");
1810                    let mut cx = ModelContext::new(app, model_id);
1811                    callback(model, payload, &mut cx);
1812                }),
1813            });
1814    }
1815
1816    pub fn emit(&mut self, payload: T::Event) {
1817        self.app.pending_effects.push_back(Effect::Event {
1818            entity_id: self.model_id,
1819            payload: Box::new(payload),
1820        });
1821    }
1822
1823    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F)
1824    where
1825        S: Entity,
1826        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
1827    {
1828        self.app
1829            .model_observations
1830            .entry(handle.model_id)
1831            .or_default()
1832            .push(ModelObservation::FromModel {
1833                model_id: self.model_id,
1834                callback: Box::new(move |model, observed_id, app, model_id| {
1835                    let model = model.downcast_mut().expect("downcast is type safe");
1836                    let observed = ModelHandle::new(observed_id, &app.cx.ref_counts);
1837                    let mut cx = ModelContext::new(app, model_id);
1838                    callback(model, observed, &mut cx);
1839                }),
1840            });
1841    }
1842
1843    pub fn notify(&mut self) {
1844        self.app
1845            .pending_effects
1846            .push_back(Effect::ModelNotification {
1847                model_id: self.model_id,
1848            });
1849    }
1850
1851    pub fn handle(&self) -> ModelHandle<T> {
1852        ModelHandle::new(self.model_id, &self.app.cx.ref_counts)
1853    }
1854
1855    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
1856    where
1857        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
1858        Fut: 'static + Future<Output = S>,
1859        S: 'static,
1860    {
1861        let handle = self.handle();
1862        self.app.spawn(|cx| f(handle, cx))
1863    }
1864
1865    pub fn spawn_weak<F, Fut, S>(&self, f: F) -> Task<S>
1866    where
1867        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
1868        Fut: 'static + Future<Output = S>,
1869        S: 'static,
1870    {
1871        let handle = self.handle().downgrade();
1872        self.app.spawn(|cx| f(handle, cx))
1873    }
1874}
1875
1876impl<M> AsRef<AppContext> for ModelContext<'_, M> {
1877    fn as_ref(&self) -> &AppContext {
1878        &self.app.cx
1879    }
1880}
1881
1882impl<M> AsMut<MutableAppContext> for ModelContext<'_, M> {
1883    fn as_mut(&mut self) -> &mut MutableAppContext {
1884        self.app
1885    }
1886}
1887
1888impl<M> ReadModel for ModelContext<'_, M> {
1889    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1890        self.app.read_model(handle)
1891    }
1892}
1893
1894impl<M> UpdateModel for ModelContext<'_, M> {
1895    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
1896    where
1897        T: Entity,
1898        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
1899    {
1900        self.app.update_model(handle, update)
1901    }
1902}
1903
1904impl<M> UpgradeModelHandle for ModelContext<'_, M> {
1905    fn upgrade_model_handle<T: Entity>(
1906        &self,
1907        handle: WeakModelHandle<T>,
1908    ) -> Option<ModelHandle<T>> {
1909        self.cx.upgrade_model_handle(handle)
1910    }
1911}
1912
1913impl<M> Deref for ModelContext<'_, M> {
1914    type Target = MutableAppContext;
1915
1916    fn deref(&self) -> &Self::Target {
1917        &self.app
1918    }
1919}
1920
1921impl<M> DerefMut for ModelContext<'_, M> {
1922    fn deref_mut(&mut self) -> &mut Self::Target {
1923        &mut self.app
1924    }
1925}
1926
1927pub struct ViewContext<'a, T: ?Sized> {
1928    app: &'a mut MutableAppContext,
1929    window_id: usize,
1930    view_id: usize,
1931    view_type: PhantomData<T>,
1932    halt_action_dispatch: bool,
1933}
1934
1935impl<'a, T: View> ViewContext<'a, T> {
1936    fn new(app: &'a mut MutableAppContext, window_id: usize, view_id: usize) -> Self {
1937        Self {
1938            app,
1939            window_id,
1940            view_id,
1941            view_type: PhantomData,
1942            halt_action_dispatch: true,
1943        }
1944    }
1945
1946    pub fn handle(&self) -> ViewHandle<T> {
1947        ViewHandle::new(self.window_id, self.view_id, &self.app.cx.ref_counts)
1948    }
1949
1950    pub fn window_id(&self) -> usize {
1951        self.window_id
1952    }
1953
1954    pub fn view_id(&self) -> usize {
1955        self.view_id
1956    }
1957
1958    pub fn foreground(&self) -> &Rc<executor::Foreground> {
1959        self.app.foreground()
1960    }
1961
1962    pub fn background_executor(&self) -> &Arc<executor::Background> {
1963        &self.app.cx.background
1964    }
1965
1966    pub fn platform(&self) -> Arc<dyn Platform> {
1967        self.app.platform()
1968    }
1969
1970    pub fn prompt<F>(&self, level: PromptLevel, msg: &str, answers: &[&str], done_fn: F)
1971    where
1972        F: 'static + FnOnce(usize, &mut MutableAppContext),
1973    {
1974        self.app
1975            .prompt(self.window_id, level, msg, answers, done_fn)
1976    }
1977
1978    pub fn prompt_for_paths<F>(&self, options: PathPromptOptions, done_fn: F)
1979    where
1980        F: 'static + FnOnce(Option<Vec<PathBuf>>, &mut MutableAppContext),
1981    {
1982        self.app.prompt_for_paths(options, done_fn)
1983    }
1984
1985    pub fn prompt_for_new_path<F>(&self, directory: &Path, done_fn: F)
1986    where
1987        F: 'static + FnOnce(Option<PathBuf>, &mut MutableAppContext),
1988    {
1989        self.app.prompt_for_new_path(directory, done_fn)
1990    }
1991
1992    pub fn debug_elements(&self) -> crate::json::Value {
1993        self.app.debug_elements(self.window_id).unwrap()
1994    }
1995
1996    pub fn focus<S>(&mut self, handle: S)
1997    where
1998        S: Into<AnyViewHandle>,
1999    {
2000        let handle = handle.into();
2001        self.app.pending_effects.push_back(Effect::Focus {
2002            window_id: handle.window_id,
2003            view_id: handle.view_id,
2004        });
2005    }
2006
2007    pub fn focus_self(&mut self) {
2008        self.app.pending_effects.push_back(Effect::Focus {
2009            window_id: self.window_id,
2010            view_id: self.view_id,
2011        });
2012    }
2013
2014    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2015    where
2016        S: Entity,
2017        F: FnOnce(&mut ModelContext<S>) -> S,
2018    {
2019        self.app.add_model(build_model)
2020    }
2021
2022    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
2023    where
2024        S: View,
2025        F: FnOnce(&mut ViewContext<S>) -> S,
2026    {
2027        self.app.add_view(self.window_id, build_view)
2028    }
2029
2030    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
2031    where
2032        S: View,
2033        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
2034    {
2035        self.app.add_option_view(self.window_id, build_view)
2036    }
2037
2038    pub fn subscribe_to_model<E, F>(&mut self, handle: &ModelHandle<E>, mut callback: F)
2039    where
2040        E: Entity,
2041        E::Event: 'static,
2042        F: 'static + FnMut(&mut T, ModelHandle<E>, &E::Event, &mut ViewContext<T>),
2043    {
2044        let emitter_handle = handle.downgrade();
2045        self.subscribe(handle, move |model, payload, cx| {
2046            if let Some(emitter_handle) = emitter_handle.upgrade(cx.as_ref()) {
2047                callback(model, emitter_handle, payload, cx);
2048            }
2049        });
2050    }
2051
2052    pub fn subscribe_to_view<V, F>(&mut self, handle: &ViewHandle<V>, mut callback: F)
2053    where
2054        V: View,
2055        V::Event: 'static,
2056        F: 'static + FnMut(&mut T, ViewHandle<V>, &V::Event, &mut ViewContext<T>),
2057    {
2058        let emitter_handle = handle.downgrade();
2059        self.subscribe(handle, move |view, payload, cx| {
2060            if let Some(emitter_handle) = emitter_handle.upgrade(cx.as_ref()) {
2061                callback(view, emitter_handle, payload, cx);
2062            }
2063        });
2064    }
2065
2066    pub fn subscribe<E, F>(&mut self, handle: &impl Handle<E>, mut callback: F)
2067    where
2068        E: Entity,
2069        E::Event: 'static,
2070        F: 'static + FnMut(&mut T, &E::Event, &mut ViewContext<T>),
2071    {
2072        self.app
2073            .subscriptions
2074            .entry(handle.id())
2075            .or_default()
2076            .push(Subscription::FromView {
2077                window_id: self.window_id,
2078                view_id: self.view_id,
2079                callback: Box::new(move |entity, payload, app, window_id, view_id| {
2080                    let entity = entity.downcast_mut().expect("downcast is type safe");
2081                    let payload = payload.downcast_ref().expect("downcast is type safe");
2082                    let mut cx = ViewContext::new(app, window_id, view_id);
2083                    callback(entity, payload, &mut cx);
2084                }),
2085            });
2086    }
2087
2088    pub fn emit(&mut self, payload: T::Event) {
2089        self.app.pending_effects.push_back(Effect::Event {
2090            entity_id: self.view_id,
2091            payload: Box::new(payload),
2092        });
2093    }
2094
2095    pub fn observe_model<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F)
2096    where
2097        S: Entity,
2098        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ViewContext<T>),
2099    {
2100        self.app
2101            .model_observations
2102            .entry(handle.id())
2103            .or_default()
2104            .push(ModelObservation::FromView {
2105                window_id: self.window_id,
2106                view_id: self.view_id,
2107                callback: Box::new(move |view, observed_id, app, window_id, view_id| {
2108                    let view = view.downcast_mut().expect("downcast is type safe");
2109                    let observed = ModelHandle::new(observed_id, &app.cx.ref_counts);
2110                    let mut cx = ViewContext::new(app, window_id, view_id);
2111                    callback(view, observed, &mut cx);
2112                }),
2113            });
2114    }
2115
2116    pub fn observe_view<S, F>(&mut self, handle: &ViewHandle<S>, mut callback: F)
2117    where
2118        S: View,
2119        F: 'static + FnMut(&mut T, ViewHandle<S>, &mut ViewContext<T>),
2120    {
2121        self.app
2122            .view_observations
2123            .entry(handle.id())
2124            .or_default()
2125            .push(ViewObservation {
2126                window_id: self.window_id,
2127                view_id: self.view_id,
2128                callback: Box::new(
2129                    move |view,
2130                          observed_view_id,
2131                          observed_window_id,
2132                          app,
2133                          observing_window_id,
2134                          observing_view_id| {
2135                        let view = view.downcast_mut().expect("downcast is type safe");
2136                        let observed_handle = ViewHandle::new(
2137                            observed_view_id,
2138                            observed_window_id,
2139                            &app.cx.ref_counts,
2140                        );
2141                        let mut cx = ViewContext::new(app, observing_window_id, observing_view_id);
2142                        callback(view, observed_handle, &mut cx);
2143                    },
2144                ),
2145            });
2146    }
2147
2148    pub fn notify(&mut self) {
2149        self.app.notify_view(self.window_id, self.view_id);
2150    }
2151
2152    pub fn notify_all(&mut self) {
2153        self.app.notify_all_views();
2154    }
2155
2156    pub fn propagate_action(&mut self) {
2157        self.halt_action_dispatch = false;
2158    }
2159
2160    pub fn spawn<F, Fut, S>(&self, f: F) -> Task<S>
2161    where
2162        F: FnOnce(ViewHandle<T>, AsyncAppContext) -> Fut,
2163        Fut: 'static + Future<Output = S>,
2164        S: 'static,
2165    {
2166        let handle = self.handle();
2167        self.app.spawn(|cx| f(handle, cx))
2168    }
2169}
2170
2171pub struct RenderContext<'a, T: View> {
2172    pub app: &'a AppContext,
2173    window_id: usize,
2174    view_id: usize,
2175    view_type: PhantomData<T>,
2176}
2177
2178impl<'a, T: View> RenderContext<'a, T> {
2179    pub fn handle(&self) -> WeakViewHandle<T> {
2180        WeakViewHandle::new(self.window_id, self.view_id)
2181    }
2182}
2183
2184impl AsRef<AppContext> for &AppContext {
2185    fn as_ref(&self) -> &AppContext {
2186        self
2187    }
2188}
2189
2190impl<V: View> Deref for RenderContext<'_, V> {
2191    type Target = AppContext;
2192
2193    fn deref(&self) -> &Self::Target {
2194        &self.app
2195    }
2196}
2197
2198impl<M> AsRef<AppContext> for ViewContext<'_, M> {
2199    fn as_ref(&self) -> &AppContext {
2200        &self.app.cx
2201    }
2202}
2203
2204impl<M> Deref for ViewContext<'_, M> {
2205    type Target = MutableAppContext;
2206
2207    fn deref(&self) -> &Self::Target {
2208        &self.app
2209    }
2210}
2211
2212impl<M> DerefMut for ViewContext<'_, M> {
2213    fn deref_mut(&mut self) -> &mut Self::Target {
2214        &mut self.app
2215    }
2216}
2217
2218impl<M> AsMut<MutableAppContext> for ViewContext<'_, M> {
2219    fn as_mut(&mut self) -> &mut MutableAppContext {
2220        self.app
2221    }
2222}
2223
2224impl<V> ReadModel for ViewContext<'_, V> {
2225    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
2226        self.app.read_model(handle)
2227    }
2228}
2229
2230impl<V> UpgradeModelHandle for ViewContext<'_, V> {
2231    fn upgrade_model_handle<T: Entity>(
2232        &self,
2233        handle: WeakModelHandle<T>,
2234    ) -> Option<ModelHandle<T>> {
2235        self.cx.upgrade_model_handle(handle)
2236    }
2237}
2238
2239impl<V: View> UpdateModel for ViewContext<'_, V> {
2240    fn update_model<T, F, S>(&mut self, handle: &ModelHandle<T>, update: F) -> S
2241    where
2242        T: Entity,
2243        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2244    {
2245        self.app.update_model(handle, update)
2246    }
2247}
2248
2249impl<V: View> ReadView for ViewContext<'_, V> {
2250    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
2251        self.app.read_view(handle)
2252    }
2253}
2254
2255impl<V: View> UpdateView for ViewContext<'_, V> {
2256    fn update_view<T, F, S>(&mut self, handle: &ViewHandle<T>, update: F) -> S
2257    where
2258        T: View,
2259        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2260    {
2261        self.app.update_view(handle, update)
2262    }
2263}
2264
2265pub trait Handle<T> {
2266    fn id(&self) -> usize;
2267    fn location(&self) -> EntityLocation;
2268}
2269
2270#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
2271pub enum EntityLocation {
2272    Model(usize),
2273    View(usize, usize),
2274}
2275
2276pub struct ModelHandle<T> {
2277    model_id: usize,
2278    model_type: PhantomData<T>,
2279    ref_counts: Arc<Mutex<RefCounts>>,
2280}
2281
2282impl<T: Entity> ModelHandle<T> {
2283    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2284        ref_counts.lock().inc_model(model_id);
2285        Self {
2286            model_id,
2287            model_type: PhantomData,
2288            ref_counts: ref_counts.clone(),
2289        }
2290    }
2291
2292    pub fn downgrade(&self) -> WeakModelHandle<T> {
2293        WeakModelHandle::new(self.model_id)
2294    }
2295
2296    pub fn id(&self) -> usize {
2297        self.model_id
2298    }
2299
2300    pub fn read<'a, C: ReadModel>(&self, cx: &'a C) -> &'a T {
2301        cx.read_model(self)
2302    }
2303
2304    pub fn read_with<'a, C, F, S>(&self, cx: &C, read: F) -> S
2305    where
2306        C: ReadModelWith,
2307        F: FnOnce(&T, &AppContext) -> S,
2308    {
2309        cx.read_model_with(self, read)
2310    }
2311
2312    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2313    where
2314        C: UpdateModel,
2315        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
2316    {
2317        cx.update_model(self, update)
2318    }
2319
2320    pub fn condition(
2321        &self,
2322        cx: &TestAppContext,
2323        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2324    ) -> impl Future<Output = ()> {
2325        let (tx, mut rx) = mpsc::channel(1024);
2326
2327        let mut cx = cx.cx.borrow_mut();
2328        self.update(&mut *cx, |_, cx| {
2329            cx.observe(self, {
2330                let mut tx = tx.clone();
2331                move |_, _, _| {
2332                    tx.blocking_send(()).ok();
2333                }
2334            });
2335            cx.subscribe(self, {
2336                let mut tx = tx.clone();
2337                move |_, _, _| {
2338                    tx.blocking_send(()).ok();
2339                }
2340            })
2341        });
2342
2343        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2344        let handle = self.downgrade();
2345        let duration = if std::env::var("CI").is_ok() {
2346            Duration::from_secs(5)
2347        } else {
2348            Duration::from_secs(1)
2349        };
2350
2351        async move {
2352            timeout(duration, async move {
2353                loop {
2354                    {
2355                        let cx = cx.borrow();
2356                        let cx = cx.as_ref();
2357                        if predicate(
2358                            handle
2359                                .upgrade(cx)
2360                                .expect("model dropped with pending condition")
2361                                .read(cx),
2362                            cx,
2363                        ) {
2364                            break;
2365                        }
2366                    }
2367
2368                    rx.recv()
2369                        .await
2370                        .expect("model dropped with pending condition");
2371                }
2372            })
2373            .await
2374            .expect("condition timed out");
2375        }
2376    }
2377}
2378
2379impl<T> Clone for ModelHandle<T> {
2380    fn clone(&self) -> Self {
2381        self.ref_counts.lock().inc_model(self.model_id);
2382        Self {
2383            model_id: self.model_id,
2384            model_type: PhantomData,
2385            ref_counts: self.ref_counts.clone(),
2386        }
2387    }
2388}
2389
2390impl<T> PartialEq for ModelHandle<T> {
2391    fn eq(&self, other: &Self) -> bool {
2392        self.model_id == other.model_id
2393    }
2394}
2395
2396impl<T> Eq for ModelHandle<T> {}
2397
2398impl<T> Hash for ModelHandle<T> {
2399    fn hash<H: Hasher>(&self, state: &mut H) {
2400        self.model_id.hash(state);
2401    }
2402}
2403
2404impl<T> std::borrow::Borrow<usize> for ModelHandle<T> {
2405    fn borrow(&self) -> &usize {
2406        &self.model_id
2407    }
2408}
2409
2410impl<T> Debug for ModelHandle<T> {
2411    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2412        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
2413            .field(&self.model_id)
2414            .finish()
2415    }
2416}
2417
2418unsafe impl<T> Send for ModelHandle<T> {}
2419unsafe impl<T> Sync for ModelHandle<T> {}
2420
2421impl<T> Drop for ModelHandle<T> {
2422    fn drop(&mut self) {
2423        self.ref_counts.lock().dec_model(self.model_id);
2424    }
2425}
2426
2427impl<T> Handle<T> for ModelHandle<T> {
2428    fn id(&self) -> usize {
2429        self.model_id
2430    }
2431
2432    fn location(&self) -> EntityLocation {
2433        EntityLocation::Model(self.model_id)
2434    }
2435}
2436pub struct WeakModelHandle<T> {
2437    model_id: usize,
2438    model_type: PhantomData<T>,
2439}
2440
2441impl<T: Entity> WeakModelHandle<T> {
2442    fn new(model_id: usize) -> Self {
2443        Self {
2444            model_id,
2445            model_type: PhantomData,
2446        }
2447    }
2448
2449    pub fn upgrade(self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<T>> {
2450        cx.upgrade_model_handle(self)
2451    }
2452}
2453
2454impl<T> Hash for WeakModelHandle<T> {
2455    fn hash<H: Hasher>(&self, state: &mut H) {
2456        self.model_id.hash(state)
2457    }
2458}
2459
2460impl<T> PartialEq for WeakModelHandle<T> {
2461    fn eq(&self, other: &Self) -> bool {
2462        self.model_id == other.model_id
2463    }
2464}
2465
2466impl<T> Eq for WeakModelHandle<T> {}
2467
2468impl<T> Clone for WeakModelHandle<T> {
2469    fn clone(&self) -> Self {
2470        Self {
2471            model_id: self.model_id,
2472            model_type: PhantomData,
2473        }
2474    }
2475}
2476
2477impl<T> Copy for WeakModelHandle<T> {}
2478
2479pub struct ViewHandle<T> {
2480    window_id: usize,
2481    view_id: usize,
2482    view_type: PhantomData<T>,
2483    ref_counts: Arc<Mutex<RefCounts>>,
2484}
2485
2486impl<T: View> ViewHandle<T> {
2487    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2488        ref_counts.lock().inc_view(window_id, view_id);
2489        Self {
2490            window_id,
2491            view_id,
2492            view_type: PhantomData,
2493            ref_counts: ref_counts.clone(),
2494        }
2495    }
2496
2497    pub fn downgrade(&self) -> WeakViewHandle<T> {
2498        WeakViewHandle::new(self.window_id, self.view_id)
2499    }
2500
2501    pub fn window_id(&self) -> usize {
2502        self.window_id
2503    }
2504
2505    pub fn id(&self) -> usize {
2506        self.view_id
2507    }
2508
2509    pub fn read<'a, C: ReadView>(&self, cx: &'a C) -> &'a T {
2510        cx.read_view(self)
2511    }
2512
2513    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
2514    where
2515        C: ReadViewWith,
2516        F: FnOnce(&T, &AppContext) -> S,
2517    {
2518        cx.read_view_with(self, read)
2519    }
2520
2521    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
2522    where
2523        C: UpdateView,
2524        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
2525    {
2526        cx.update_view(self, update)
2527    }
2528
2529    pub fn is_focused(&self, cx: &AppContext) -> bool {
2530        cx.focused_view_id(self.window_id)
2531            .map_or(false, |focused_id| focused_id == self.view_id)
2532    }
2533
2534    pub fn condition(
2535        &self,
2536        cx: &TestAppContext,
2537        mut predicate: impl FnMut(&T, &AppContext) -> bool,
2538    ) -> impl Future<Output = ()> {
2539        let (tx, mut rx) = mpsc::channel(1024);
2540
2541        let mut cx = cx.cx.borrow_mut();
2542        self.update(&mut *cx, |_, cx| {
2543            cx.observe_view(self, {
2544                let mut tx = tx.clone();
2545                move |_, _, _| {
2546                    tx.blocking_send(()).ok();
2547                }
2548            });
2549
2550            cx.subscribe(self, {
2551                let mut tx = tx.clone();
2552                move |_, _, _| {
2553                    tx.blocking_send(()).ok();
2554                }
2555            })
2556        });
2557
2558        let cx = cx.weak_self.as_ref().unwrap().upgrade().unwrap();
2559        let handle = self.downgrade();
2560        let duration = if std::env::var("CI").is_ok() {
2561            Duration::from_secs(2)
2562        } else {
2563            Duration::from_millis(500)
2564        };
2565
2566        async move {
2567            timeout(duration, async move {
2568                loop {
2569                    {
2570                        let cx = cx.borrow();
2571                        let cx = cx.as_ref();
2572                        if predicate(
2573                            handle
2574                                .upgrade(cx)
2575                                .expect("view dropped with pending condition")
2576                                .read(cx),
2577                            cx,
2578                        ) {
2579                            break;
2580                        }
2581                    }
2582
2583                    rx.recv()
2584                        .await
2585                        .expect("view dropped with pending condition");
2586                }
2587            })
2588            .await
2589            .expect("condition timed out");
2590        }
2591    }
2592}
2593
2594impl<T> Clone for ViewHandle<T> {
2595    fn clone(&self) -> Self {
2596        self.ref_counts
2597            .lock()
2598            .inc_view(self.window_id, self.view_id);
2599        Self {
2600            window_id: self.window_id,
2601            view_id: self.view_id,
2602            view_type: PhantomData,
2603            ref_counts: self.ref_counts.clone(),
2604        }
2605    }
2606}
2607
2608impl<T> PartialEq for ViewHandle<T> {
2609    fn eq(&self, other: &Self) -> bool {
2610        self.window_id == other.window_id && self.view_id == other.view_id
2611    }
2612}
2613
2614impl<T> Eq for ViewHandle<T> {}
2615
2616impl<T> Debug for ViewHandle<T> {
2617    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2618        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
2619            .field("window_id", &self.window_id)
2620            .field("view_id", &self.view_id)
2621            .finish()
2622    }
2623}
2624
2625impl<T> Drop for ViewHandle<T> {
2626    fn drop(&mut self) {
2627        self.ref_counts
2628            .lock()
2629            .dec_view(self.window_id, self.view_id);
2630    }
2631}
2632
2633impl<T> Handle<T> for ViewHandle<T> {
2634    fn id(&self) -> usize {
2635        self.view_id
2636    }
2637
2638    fn location(&self) -> EntityLocation {
2639        EntityLocation::View(self.window_id, self.view_id)
2640    }
2641}
2642
2643pub struct AnyViewHandle {
2644    window_id: usize,
2645    view_id: usize,
2646    view_type: TypeId,
2647    ref_counts: Arc<Mutex<RefCounts>>,
2648}
2649
2650impl AnyViewHandle {
2651    pub fn id(&self) -> usize {
2652        self.view_id
2653    }
2654
2655    pub fn is<T: 'static>(&self) -> bool {
2656        TypeId::of::<T>() == self.view_type
2657    }
2658
2659    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
2660        if self.is::<T>() {
2661            let result = Some(ViewHandle {
2662                window_id: self.window_id,
2663                view_id: self.view_id,
2664                ref_counts: self.ref_counts.clone(),
2665                view_type: PhantomData,
2666            });
2667            unsafe {
2668                Arc::decrement_strong_count(&self.ref_counts);
2669            }
2670            std::mem::forget(self);
2671            result
2672        } else {
2673            None
2674        }
2675    }
2676}
2677
2678impl Clone for AnyViewHandle {
2679    fn clone(&self) -> Self {
2680        self.ref_counts
2681            .lock()
2682            .inc_view(self.window_id, self.view_id);
2683        Self {
2684            window_id: self.window_id,
2685            view_id: self.view_id,
2686            view_type: self.view_type,
2687            ref_counts: self.ref_counts.clone(),
2688        }
2689    }
2690}
2691
2692impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
2693    fn from(handle: &ViewHandle<T>) -> Self {
2694        handle
2695            .ref_counts
2696            .lock()
2697            .inc_view(handle.window_id, handle.view_id);
2698        AnyViewHandle {
2699            window_id: handle.window_id,
2700            view_id: handle.view_id,
2701            view_type: TypeId::of::<T>(),
2702            ref_counts: handle.ref_counts.clone(),
2703        }
2704    }
2705}
2706
2707impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
2708    fn from(handle: ViewHandle<T>) -> Self {
2709        let any_handle = AnyViewHandle {
2710            window_id: handle.window_id,
2711            view_id: handle.view_id,
2712            view_type: TypeId::of::<T>(),
2713            ref_counts: handle.ref_counts.clone(),
2714        };
2715        unsafe {
2716            Arc::decrement_strong_count(&handle.ref_counts);
2717        }
2718        std::mem::forget(handle);
2719        any_handle
2720    }
2721}
2722
2723impl Drop for AnyViewHandle {
2724    fn drop(&mut self) {
2725        self.ref_counts
2726            .lock()
2727            .dec_view(self.window_id, self.view_id);
2728    }
2729}
2730
2731pub struct AnyModelHandle {
2732    model_id: usize,
2733    ref_counts: Arc<Mutex<RefCounts>>,
2734}
2735
2736impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
2737    fn from(handle: ModelHandle<T>) -> Self {
2738        handle.ref_counts.lock().inc_model(handle.model_id);
2739        Self {
2740            model_id: handle.model_id,
2741            ref_counts: handle.ref_counts.clone(),
2742        }
2743    }
2744}
2745
2746impl Drop for AnyModelHandle {
2747    fn drop(&mut self) {
2748        self.ref_counts.lock().dec_model(self.model_id);
2749    }
2750}
2751pub struct WeakViewHandle<T> {
2752    window_id: usize,
2753    view_id: usize,
2754    view_type: PhantomData<T>,
2755}
2756
2757impl<T: View> WeakViewHandle<T> {
2758    fn new(window_id: usize, view_id: usize) -> Self {
2759        Self {
2760            window_id,
2761            view_id,
2762            view_type: PhantomData,
2763        }
2764    }
2765
2766    pub fn upgrade(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
2767        if cx.ref_counts.lock().is_entity_alive(self.view_id) {
2768            Some(ViewHandle::new(
2769                self.window_id,
2770                self.view_id,
2771                &cx.ref_counts,
2772            ))
2773        } else {
2774            None
2775        }
2776    }
2777}
2778
2779impl<T> Clone for WeakViewHandle<T> {
2780    fn clone(&self) -> Self {
2781        Self {
2782            window_id: self.window_id,
2783            view_id: self.view_id,
2784            view_type: PhantomData,
2785        }
2786    }
2787}
2788
2789pub struct ValueHandle<T> {
2790    value_type: PhantomData<T>,
2791    tag_type_id: TypeId,
2792    id: usize,
2793    ref_counts: Weak<Mutex<RefCounts>>,
2794}
2795
2796impl<T: 'static> ValueHandle<T> {
2797    fn new(tag_type_id: TypeId, id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
2798        ref_counts.lock().inc_value(tag_type_id, id);
2799        Self {
2800            value_type: PhantomData,
2801            tag_type_id,
2802            id,
2803            ref_counts: Arc::downgrade(ref_counts),
2804        }
2805    }
2806
2807    pub fn read<R>(&self, cx: &AppContext, f: impl FnOnce(&T) -> R) -> R {
2808        f(cx.values
2809            .read()
2810            .get(&(self.tag_type_id, self.id))
2811            .unwrap()
2812            .downcast_ref()
2813            .unwrap())
2814    }
2815
2816    pub fn update<R>(
2817        &self,
2818        cx: &mut EventContext,
2819        f: impl FnOnce(&mut T, &mut EventContext) -> R,
2820    ) -> R {
2821        let mut value = cx
2822            .app
2823            .cx
2824            .values
2825            .write()
2826            .remove(&(self.tag_type_id, self.id))
2827            .unwrap();
2828        let result = f(value.downcast_mut().unwrap(), cx);
2829        cx.app
2830            .cx
2831            .values
2832            .write()
2833            .insert((self.tag_type_id, self.id), value);
2834        result
2835    }
2836}
2837
2838impl<T> Drop for ValueHandle<T> {
2839    fn drop(&mut self) {
2840        if let Some(ref_counts) = self.ref_counts.upgrade() {
2841            ref_counts.lock().dec_value(self.tag_type_id, self.id);
2842        }
2843    }
2844}
2845
2846#[derive(Default)]
2847struct RefCounts {
2848    entity_counts: HashMap<usize, usize>,
2849    value_counts: HashMap<(TypeId, usize), usize>,
2850    dropped_models: HashSet<usize>,
2851    dropped_views: HashSet<(usize, usize)>,
2852    dropped_values: HashSet<(TypeId, usize)>,
2853}
2854
2855impl RefCounts {
2856    fn inc_model(&mut self, model_id: usize) {
2857        match self.entity_counts.entry(model_id) {
2858            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
2859            Entry::Vacant(entry) => {
2860                entry.insert(1);
2861                self.dropped_models.remove(&model_id);
2862            }
2863        }
2864    }
2865
2866    fn inc_view(&mut self, window_id: usize, view_id: usize) {
2867        match self.entity_counts.entry(view_id) {
2868            Entry::Occupied(mut entry) => *entry.get_mut() += 1,
2869            Entry::Vacant(entry) => {
2870                entry.insert(1);
2871                self.dropped_views.remove(&(window_id, view_id));
2872            }
2873        }
2874    }
2875
2876    fn inc_value(&mut self, tag_type_id: TypeId, id: usize) {
2877        *self.value_counts.entry((tag_type_id, id)).or_insert(0) += 1;
2878    }
2879
2880    fn dec_model(&mut self, model_id: usize) {
2881        let count = self.entity_counts.get_mut(&model_id).unwrap();
2882        *count -= 1;
2883        if *count == 0 {
2884            self.entity_counts.remove(&model_id);
2885            self.dropped_models.insert(model_id);
2886        }
2887    }
2888
2889    fn dec_view(&mut self, window_id: usize, view_id: usize) {
2890        let count = self.entity_counts.get_mut(&view_id).unwrap();
2891        *count -= 1;
2892        if *count == 0 {
2893            self.entity_counts.remove(&view_id);
2894            self.dropped_views.insert((window_id, view_id));
2895        }
2896    }
2897
2898    fn dec_value(&mut self, tag_type_id: TypeId, id: usize) {
2899        let key = (tag_type_id, id);
2900        let count = self.value_counts.get_mut(&key).unwrap();
2901        *count -= 1;
2902        if *count == 0 {
2903            self.value_counts.remove(&key);
2904            self.dropped_values.insert(key);
2905        }
2906    }
2907
2908    fn is_entity_alive(&self, entity_id: usize) -> bool {
2909        self.entity_counts.contains_key(&entity_id)
2910    }
2911
2912    fn take_dropped(
2913        &mut self,
2914    ) -> (
2915        HashSet<usize>,
2916        HashSet<(usize, usize)>,
2917        HashSet<(TypeId, usize)>,
2918    ) {
2919        let mut dropped_models = HashSet::new();
2920        let mut dropped_views = HashSet::new();
2921        let mut dropped_values = HashSet::new();
2922        std::mem::swap(&mut self.dropped_models, &mut dropped_models);
2923        std::mem::swap(&mut self.dropped_views, &mut dropped_views);
2924        std::mem::swap(&mut self.dropped_values, &mut dropped_values);
2925        (dropped_models, dropped_views, dropped_values)
2926    }
2927}
2928
2929enum Subscription {
2930    FromModel {
2931        model_id: usize,
2932        callback: Box<dyn FnMut(&mut dyn Any, &dyn Any, &mut MutableAppContext, usize)>,
2933    },
2934    FromView {
2935        window_id: usize,
2936        view_id: usize,
2937        callback: Box<dyn FnMut(&mut dyn Any, &dyn Any, &mut MutableAppContext, usize, usize)>,
2938    },
2939}
2940
2941enum ModelObservation {
2942    FromModel {
2943        model_id: usize,
2944        callback: Box<dyn FnMut(&mut dyn Any, usize, &mut MutableAppContext, usize)>,
2945    },
2946    FromView {
2947        window_id: usize,
2948        view_id: usize,
2949        callback: Box<dyn FnMut(&mut dyn Any, usize, &mut MutableAppContext, usize, usize)>,
2950    },
2951}
2952
2953struct ViewObservation {
2954    window_id: usize,
2955    view_id: usize,
2956    callback: Box<dyn FnMut(&mut dyn Any, usize, usize, &mut MutableAppContext, usize, usize)>,
2957}
2958
2959#[cfg(test)]
2960mod tests {
2961    use super::*;
2962    use crate::elements::*;
2963    use smol::future::poll_once;
2964    use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
2965
2966    #[crate::test(self)]
2967    fn test_model_handles(cx: &mut MutableAppContext) {
2968        struct Model {
2969            other: Option<ModelHandle<Model>>,
2970            events: Vec<String>,
2971        }
2972
2973        impl Entity for Model {
2974            type Event = usize;
2975        }
2976
2977        impl Model {
2978            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
2979                if let Some(other) = other.as_ref() {
2980                    cx.observe(other, |me, _, _| {
2981                        me.events.push("notified".into());
2982                    });
2983                    cx.subscribe(other, |me, event, _| {
2984                        me.events.push(format!("observed event {}", event));
2985                    });
2986                }
2987
2988                Self {
2989                    other,
2990                    events: Vec::new(),
2991                }
2992            }
2993        }
2994
2995        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
2996        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
2997        assert_eq!(cx.cx.models.len(), 2);
2998
2999        handle_1.update(cx, |model, cx| {
3000            model.events.push("updated".into());
3001            cx.emit(1);
3002            cx.notify();
3003            cx.emit(2);
3004        });
3005        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3006        assert_eq!(
3007            handle_2.read(cx).events,
3008            vec![
3009                "observed event 1".to_string(),
3010                "notified".to_string(),
3011                "observed event 2".to_string(),
3012            ]
3013        );
3014
3015        handle_2.update(cx, |model, _| {
3016            drop(handle_1);
3017            model.other.take();
3018        });
3019
3020        assert_eq!(cx.cx.models.len(), 1);
3021        assert!(cx.subscriptions.is_empty());
3022        assert!(cx.model_observations.is_empty());
3023    }
3024
3025    #[crate::test(self)]
3026    fn test_subscribe_and_emit_from_model(cx: &mut MutableAppContext) {
3027        #[derive(Default)]
3028        struct Model {
3029            events: Vec<usize>,
3030        }
3031
3032        impl Entity for Model {
3033            type Event = usize;
3034        }
3035
3036        let handle_1 = cx.add_model(|_| Model::default());
3037        let handle_2 = cx.add_model(|_| Model::default());
3038        let handle_2b = handle_2.clone();
3039
3040        handle_1.update(cx, |_, c| {
3041            c.subscribe(&handle_2, move |model: &mut Model, event, c| {
3042                model.events.push(*event);
3043
3044                c.subscribe(&handle_2b, |model, event, _| {
3045                    model.events.push(*event * 2);
3046                });
3047            });
3048        });
3049
3050        handle_2.update(cx, |_, c| c.emit(7));
3051        assert_eq!(handle_1.read(cx).events, vec![7]);
3052
3053        handle_2.update(cx, |_, c| c.emit(5));
3054        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5]);
3055    }
3056
3057    #[crate::test(self)]
3058    fn test_observe_and_notify_from_model(cx: &mut MutableAppContext) {
3059        #[derive(Default)]
3060        struct Model {
3061            count: usize,
3062            events: Vec<usize>,
3063        }
3064
3065        impl Entity for Model {
3066            type Event = ();
3067        }
3068
3069        let handle_1 = cx.add_model(|_| Model::default());
3070        let handle_2 = cx.add_model(|_| Model::default());
3071        let handle_2b = handle_2.clone();
3072
3073        handle_1.update(cx, |_, c| {
3074            c.observe(&handle_2, move |model, observed, c| {
3075                model.events.push(observed.read(c).count);
3076                c.observe(&handle_2b, |model, observed, c| {
3077                    model.events.push(observed.read(c).count * 2);
3078                });
3079            });
3080        });
3081
3082        handle_2.update(cx, |model, c| {
3083            model.count = 7;
3084            c.notify()
3085        });
3086        assert_eq!(handle_1.read(cx).events, vec![7]);
3087
3088        handle_2.update(cx, |model, c| {
3089            model.count = 5;
3090            c.notify()
3091        });
3092        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5])
3093    }
3094
3095    #[crate::test(self)]
3096    fn test_view_handles(cx: &mut MutableAppContext) {
3097        struct View {
3098            other: Option<ViewHandle<View>>,
3099            events: Vec<String>,
3100        }
3101
3102        impl Entity for View {
3103            type Event = usize;
3104        }
3105
3106        impl super::View for View {
3107            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3108                Empty::new().boxed()
3109            }
3110
3111            fn ui_name() -> &'static str {
3112                "View"
3113            }
3114        }
3115
3116        impl View {
3117            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
3118                if let Some(other) = other.as_ref() {
3119                    cx.subscribe_to_view(other, |me, _, event, _| {
3120                        me.events.push(format!("observed event {}", event));
3121                    });
3122                }
3123                Self {
3124                    other,
3125                    events: Vec::new(),
3126                }
3127            }
3128        }
3129
3130        let (window_id, _) = cx.add_window(Default::default(), |cx| View::new(None, cx));
3131        let handle_1 = cx.add_view(window_id, |cx| View::new(None, cx));
3132        let handle_2 = cx.add_view(window_id, |cx| View::new(Some(handle_1.clone()), cx));
3133        assert_eq!(cx.cx.views.len(), 3);
3134
3135        handle_1.update(cx, |view, cx| {
3136            view.events.push("updated".into());
3137            cx.emit(1);
3138            cx.emit(2);
3139        });
3140        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
3141        assert_eq!(
3142            handle_2.read(cx).events,
3143            vec![
3144                "observed event 1".to_string(),
3145                "observed event 2".to_string(),
3146            ]
3147        );
3148
3149        handle_2.update(cx, |view, _| {
3150            drop(handle_1);
3151            view.other.take();
3152        });
3153
3154        assert_eq!(cx.cx.views.len(), 2);
3155        assert!(cx.subscriptions.is_empty());
3156        assert!(cx.model_observations.is_empty());
3157    }
3158
3159    #[crate::test(self)]
3160    fn test_add_window(cx: &mut MutableAppContext) {
3161        struct View {
3162            mouse_down_count: Arc<AtomicUsize>,
3163        }
3164
3165        impl Entity for View {
3166            type Event = ();
3167        }
3168
3169        impl super::View for View {
3170            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3171                let mouse_down_count = self.mouse_down_count.clone();
3172                EventHandler::new(Empty::new().boxed())
3173                    .on_mouse_down(move |_| {
3174                        mouse_down_count.fetch_add(1, SeqCst);
3175                        true
3176                    })
3177                    .boxed()
3178            }
3179
3180            fn ui_name() -> &'static str {
3181                "View"
3182            }
3183        }
3184
3185        let mouse_down_count = Arc::new(AtomicUsize::new(0));
3186        let (window_id, _) = cx.add_window(Default::default(), |_| View {
3187            mouse_down_count: mouse_down_count.clone(),
3188        });
3189        let presenter = cx.presenters_and_platform_windows[&window_id].0.clone();
3190        // Ensure window's root element is in a valid lifecycle state.
3191        presenter.borrow_mut().dispatch_event(
3192            Event::LeftMouseDown {
3193                position: Default::default(),
3194                cmd: false,
3195            },
3196            cx,
3197        );
3198        assert_eq!(mouse_down_count.load(SeqCst), 1);
3199    }
3200
3201    #[crate::test(self)]
3202    fn test_entity_release_hooks(cx: &mut MutableAppContext) {
3203        struct Model {
3204            released: Arc<Mutex<bool>>,
3205        }
3206
3207        struct View {
3208            released: Arc<Mutex<bool>>,
3209        }
3210
3211        impl Entity for Model {
3212            type Event = ();
3213
3214            fn release(&mut self, _: &mut MutableAppContext) {
3215                *self.released.lock() = true;
3216            }
3217        }
3218
3219        impl Entity for View {
3220            type Event = ();
3221
3222            fn release(&mut self, _: &mut MutableAppContext) {
3223                *self.released.lock() = true;
3224            }
3225        }
3226
3227        impl super::View for View {
3228            fn ui_name() -> &'static str {
3229                "View"
3230            }
3231
3232            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3233                Empty::new().boxed()
3234            }
3235        }
3236
3237        let model_released = Arc::new(Mutex::new(false));
3238        let view_released = Arc::new(Mutex::new(false));
3239
3240        let model = cx.add_model(|_| Model {
3241            released: model_released.clone(),
3242        });
3243
3244        let (window_id, _) = cx.add_window(Default::default(), |_| View {
3245            released: view_released.clone(),
3246        });
3247
3248        assert!(!*model_released.lock());
3249        assert!(!*view_released.lock());
3250
3251        cx.update(move || {
3252            drop(model);
3253        });
3254        assert!(*model_released.lock());
3255
3256        drop(cx.remove_window(window_id));
3257        assert!(*view_released.lock());
3258    }
3259
3260    #[crate::test(self)]
3261    fn test_subscribe_and_emit_from_view(cx: &mut MutableAppContext) {
3262        #[derive(Default)]
3263        struct View {
3264            events: Vec<usize>,
3265        }
3266
3267        impl Entity for View {
3268            type Event = usize;
3269        }
3270
3271        impl super::View for View {
3272            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3273                Empty::new().boxed()
3274            }
3275
3276            fn ui_name() -> &'static str {
3277                "View"
3278            }
3279        }
3280
3281        struct Model;
3282
3283        impl Entity for Model {
3284            type Event = usize;
3285        }
3286
3287        let (window_id, handle_1) = cx.add_window(Default::default(), |_| View::default());
3288        let handle_2 = cx.add_view(window_id, |_| View::default());
3289        let handle_2b = handle_2.clone();
3290        let handle_3 = cx.add_model(|_| Model);
3291
3292        handle_1.update(cx, |_, c| {
3293            c.subscribe_to_view(&handle_2, move |me, _, event, c| {
3294                me.events.push(*event);
3295
3296                c.subscribe_to_view(&handle_2b, |me, _, event, _| {
3297                    me.events.push(*event * 2);
3298                });
3299            });
3300
3301            c.subscribe_to_model(&handle_3, |me, _, event, _| {
3302                me.events.push(*event);
3303            })
3304        });
3305
3306        handle_2.update(cx, |_, c| c.emit(7));
3307        assert_eq!(handle_1.read(cx).events, vec![7]);
3308
3309        handle_2.update(cx, |_, c| c.emit(5));
3310        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5]);
3311
3312        handle_3.update(cx, |_, c| c.emit(9));
3313        assert_eq!(handle_1.read(cx).events, vec![7, 10, 5, 9]);
3314    }
3315
3316    #[crate::test(self)]
3317    fn test_dropping_subscribers(cx: &mut MutableAppContext) {
3318        struct View;
3319
3320        impl Entity for View {
3321            type Event = ();
3322        }
3323
3324        impl super::View for View {
3325            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3326                Empty::new().boxed()
3327            }
3328
3329            fn ui_name() -> &'static str {
3330                "View"
3331            }
3332        }
3333
3334        struct Model;
3335
3336        impl Entity for Model {
3337            type Event = ();
3338        }
3339
3340        let (window_id, _) = cx.add_window(Default::default(), |_| View);
3341        let observing_view = cx.add_view(window_id, |_| View);
3342        let emitting_view = cx.add_view(window_id, |_| View);
3343        let observing_model = cx.add_model(|_| Model);
3344        let observed_model = cx.add_model(|_| Model);
3345
3346        observing_view.update(cx, |_, cx| {
3347            cx.subscribe_to_view(&emitting_view, |_, _, _, _| {});
3348            cx.subscribe_to_model(&observed_model, |_, _, _, _| {});
3349        });
3350        observing_model.update(cx, |_, cx| {
3351            cx.subscribe(&observed_model, |_, _, _| {});
3352        });
3353
3354        cx.update(|| {
3355            drop(observing_view);
3356            drop(observing_model);
3357        });
3358
3359        emitting_view.update(cx, |_, cx| cx.emit(()));
3360        observed_model.update(cx, |_, cx| cx.emit(()));
3361    }
3362
3363    #[crate::test(self)]
3364    fn test_observe_and_notify_from_view(cx: &mut MutableAppContext) {
3365        #[derive(Default)]
3366        struct View {
3367            events: Vec<usize>,
3368        }
3369
3370        impl Entity for View {
3371            type Event = usize;
3372        }
3373
3374        impl super::View for View {
3375            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3376                Empty::new().boxed()
3377            }
3378
3379            fn ui_name() -> &'static str {
3380                "View"
3381            }
3382        }
3383
3384        #[derive(Default)]
3385        struct Model {
3386            count: usize,
3387        }
3388
3389        impl Entity for Model {
3390            type Event = ();
3391        }
3392
3393        let (_, view) = cx.add_window(Default::default(), |_| View::default());
3394        let model = cx.add_model(|_| Model::default());
3395
3396        view.update(cx, |_, c| {
3397            c.observe_model(&model, |me, observed, c| {
3398                me.events.push(observed.read(c).count)
3399            });
3400        });
3401
3402        model.update(cx, |model, c| {
3403            model.count = 11;
3404            c.notify();
3405        });
3406        assert_eq!(view.read(cx).events, vec![11]);
3407    }
3408
3409    #[crate::test(self)]
3410    fn test_dropping_observers(cx: &mut MutableAppContext) {
3411        struct View;
3412
3413        impl Entity for View {
3414            type Event = ();
3415        }
3416
3417        impl super::View for View {
3418            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3419                Empty::new().boxed()
3420            }
3421
3422            fn ui_name() -> &'static str {
3423                "View"
3424            }
3425        }
3426
3427        struct Model;
3428
3429        impl Entity for Model {
3430            type Event = ();
3431        }
3432
3433        let (window_id, _) = cx.add_window(Default::default(), |_| View);
3434        let observing_view = cx.add_view(window_id, |_| View);
3435        let observing_model = cx.add_model(|_| Model);
3436        let observed_model = cx.add_model(|_| Model);
3437
3438        observing_view.update(cx, |_, cx| {
3439            cx.observe_model(&observed_model, |_, _, _| {});
3440        });
3441        observing_model.update(cx, |_, cx| {
3442            cx.observe(&observed_model, |_, _, _| {});
3443        });
3444
3445        cx.update(|| {
3446            drop(observing_view);
3447            drop(observing_model);
3448        });
3449
3450        observed_model.update(cx, |_, cx| cx.notify());
3451    }
3452
3453    #[crate::test(self)]
3454    fn test_focus(cx: &mut MutableAppContext) {
3455        struct View {
3456            name: String,
3457            events: Arc<Mutex<Vec<String>>>,
3458        }
3459
3460        impl Entity for View {
3461            type Event = ();
3462        }
3463
3464        impl super::View for View {
3465            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3466                Empty::new().boxed()
3467            }
3468
3469            fn ui_name() -> &'static str {
3470                "View"
3471            }
3472
3473            fn on_focus(&mut self, _: &mut ViewContext<Self>) {
3474                self.events.lock().push(format!("{} focused", &self.name));
3475            }
3476
3477            fn on_blur(&mut self, _: &mut ViewContext<Self>) {
3478                self.events.lock().push(format!("{} blurred", &self.name));
3479            }
3480        }
3481
3482        let events: Arc<Mutex<Vec<String>>> = Default::default();
3483        let (window_id, view_1) = cx.add_window(Default::default(), |_| View {
3484            events: events.clone(),
3485            name: "view 1".to_string(),
3486        });
3487        let view_2 = cx.add_view(window_id, |_| View {
3488            events: events.clone(),
3489            name: "view 2".to_string(),
3490        });
3491
3492        view_1.update(cx, |_, cx| cx.focus(&view_2));
3493        view_1.update(cx, |_, cx| cx.focus(&view_1));
3494        view_1.update(cx, |_, cx| cx.focus(&view_2));
3495        view_1.update(cx, |_, _| drop(view_2));
3496
3497        assert_eq!(
3498            *events.lock(),
3499            [
3500                "view 1 focused".to_string(),
3501                "view 1 blurred".to_string(),
3502                "view 2 focused".to_string(),
3503                "view 2 blurred".to_string(),
3504                "view 1 focused".to_string(),
3505                "view 1 blurred".to_string(),
3506                "view 2 focused".to_string(),
3507                "view 1 focused".to_string(),
3508            ],
3509        );
3510    }
3511
3512    #[crate::test(self)]
3513    fn test_dispatch_action(cx: &mut MutableAppContext) {
3514        struct ViewA {
3515            id: usize,
3516        }
3517
3518        impl Entity for ViewA {
3519            type Event = ();
3520        }
3521
3522        impl View for ViewA {
3523            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3524                Empty::new().boxed()
3525            }
3526
3527            fn ui_name() -> &'static str {
3528                "View"
3529            }
3530        }
3531
3532        struct ViewB {
3533            id: usize,
3534        }
3535
3536        impl Entity for ViewB {
3537            type Event = ();
3538        }
3539
3540        impl View for ViewB {
3541            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3542                Empty::new().boxed()
3543            }
3544
3545            fn ui_name() -> &'static str {
3546                "View"
3547            }
3548        }
3549
3550        struct ActionArg {
3551            foo: String,
3552        }
3553
3554        let actions = Rc::new(RefCell::new(Vec::new()));
3555
3556        let actions_clone = actions.clone();
3557        cx.add_global_action("action", move |_: &ActionArg, _: &mut MutableAppContext| {
3558            actions_clone.borrow_mut().push("global a".to_string());
3559        });
3560
3561        let actions_clone = actions.clone();
3562        cx.add_global_action("action", move |_: &ActionArg, _: &mut MutableAppContext| {
3563            actions_clone.borrow_mut().push("global b".to_string());
3564        });
3565
3566        let actions_clone = actions.clone();
3567        cx.add_action("action", move |view: &mut ViewA, arg: &ActionArg, cx| {
3568            assert_eq!(arg.foo, "bar");
3569            cx.propagate_action();
3570            actions_clone.borrow_mut().push(format!("{} a", view.id));
3571        });
3572
3573        let actions_clone = actions.clone();
3574        cx.add_action("action", move |view: &mut ViewA, _: &ActionArg, cx| {
3575            if view.id != 1 {
3576                cx.propagate_action();
3577            }
3578            actions_clone.borrow_mut().push(format!("{} b", view.id));
3579        });
3580
3581        let actions_clone = actions.clone();
3582        cx.add_action("action", move |view: &mut ViewB, _: &ActionArg, cx| {
3583            cx.propagate_action();
3584            actions_clone.borrow_mut().push(format!("{} c", view.id));
3585        });
3586
3587        let actions_clone = actions.clone();
3588        cx.add_action("action", move |view: &mut ViewB, _: &ActionArg, cx| {
3589            cx.propagate_action();
3590            actions_clone.borrow_mut().push(format!("{} d", view.id));
3591        });
3592
3593        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
3594        let view_2 = cx.add_view(window_id, |_| ViewB { id: 2 });
3595        let view_3 = cx.add_view(window_id, |_| ViewA { id: 3 });
3596        let view_4 = cx.add_view(window_id, |_| ViewB { id: 4 });
3597
3598        cx.dispatch_action(
3599            window_id,
3600            vec![view_1.id(), view_2.id(), view_3.id(), view_4.id()],
3601            "action",
3602            ActionArg { foo: "bar".into() },
3603        );
3604
3605        assert_eq!(
3606            *actions.borrow(),
3607            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "1 b"]
3608        );
3609
3610        // Remove view_1, which doesn't propagate the action
3611        actions.borrow_mut().clear();
3612        cx.dispatch_action(
3613            window_id,
3614            vec![view_2.id(), view_3.id(), view_4.id()],
3615            "action",
3616            ActionArg { foo: "bar".into() },
3617        );
3618
3619        assert_eq!(
3620            *actions.borrow(),
3621            vec!["4 d", "4 c", "3 b", "3 a", "2 d", "2 c", "global b", "global a"]
3622        );
3623    }
3624
3625    #[crate::test(self)]
3626    fn test_dispatch_keystroke(cx: &mut MutableAppContext) {
3627        use std::cell::Cell;
3628
3629        #[derive(Clone)]
3630        struct ActionArg {
3631            key: String,
3632        }
3633
3634        struct View {
3635            id: usize,
3636            keymap_context: keymap::Context,
3637        }
3638
3639        impl Entity for View {
3640            type Event = ();
3641        }
3642
3643        impl super::View for View {
3644            fn render<'a>(&self, _: &RenderContext<Self>) -> ElementBox {
3645                Empty::new().boxed()
3646            }
3647
3648            fn ui_name() -> &'static str {
3649                "View"
3650            }
3651
3652            fn keymap_context(&self, _: &AppContext) -> keymap::Context {
3653                self.keymap_context.clone()
3654            }
3655        }
3656
3657        impl View {
3658            fn new(id: usize) -> Self {
3659                View {
3660                    id,
3661                    keymap_context: keymap::Context::default(),
3662                }
3663            }
3664        }
3665
3666        let mut view_1 = View::new(1);
3667        let mut view_2 = View::new(2);
3668        let mut view_3 = View::new(3);
3669        view_1.keymap_context.set.insert("a".into());
3670        view_2.keymap_context.set.insert("b".into());
3671        view_3.keymap_context.set.insert("c".into());
3672
3673        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
3674        let view_2 = cx.add_view(window_id, |_| view_2);
3675        let view_3 = cx.add_view(window_id, |_| view_3);
3676
3677        // This keymap's only binding dispatches an action on view 2 because that view will have
3678        // "a" and "b" in its context, but not "c".
3679        let binding = keymap::Binding::new("a", "action", Some("a && b && !c"))
3680            .with_arg(ActionArg { key: "a".into() });
3681        cx.add_bindings(vec![binding]);
3682
3683        let handled_action = Rc::new(Cell::new(false));
3684        let handled_action_clone = handled_action.clone();
3685        cx.add_action("action", move |view: &mut View, arg: &ActionArg, _| {
3686            handled_action_clone.set(true);
3687            assert_eq!(view.id, 2);
3688            assert_eq!(arg.key, "a");
3689        });
3690
3691        cx.dispatch_keystroke(
3692            window_id,
3693            vec![view_1.id(), view_2.id(), view_3.id()],
3694            &Keystroke::parse("a").unwrap(),
3695        )
3696        .unwrap();
3697
3698        assert!(handled_action.get());
3699    }
3700
3701    #[crate::test(self)]
3702    async fn test_model_condition(mut cx: TestAppContext) {
3703        struct Counter(usize);
3704
3705        impl super::Entity for Counter {
3706            type Event = ();
3707        }
3708
3709        impl Counter {
3710            fn inc(&mut self, cx: &mut ModelContext<Self>) {
3711                self.0 += 1;
3712                cx.notify();
3713            }
3714        }
3715
3716        let model = cx.add_model(|_| Counter(0));
3717
3718        let condition1 = model.condition(&cx, |model, _| model.0 == 2);
3719        let condition2 = model.condition(&cx, |model, _| model.0 == 3);
3720        smol::pin!(condition1, condition2);
3721
3722        model.update(&mut cx, |model, cx| model.inc(cx));
3723        assert_eq!(poll_once(&mut condition1).await, None);
3724        assert_eq!(poll_once(&mut condition2).await, None);
3725
3726        model.update(&mut cx, |model, cx| model.inc(cx));
3727        assert_eq!(poll_once(&mut condition1).await, Some(()));
3728        assert_eq!(poll_once(&mut condition2).await, None);
3729
3730        model.update(&mut cx, |model, cx| model.inc(cx));
3731        assert_eq!(poll_once(&mut condition2).await, Some(()));
3732
3733        model.update(&mut cx, |_, cx| cx.notify());
3734    }
3735
3736    #[crate::test(self)]
3737    #[should_panic]
3738    async fn test_model_condition_timeout(mut cx: TestAppContext) {
3739        struct Model;
3740
3741        impl super::Entity for Model {
3742            type Event = ();
3743        }
3744
3745        let model = cx.add_model(|_| Model);
3746        model.condition(&cx, |_, _| false).await;
3747    }
3748
3749    #[crate::test(self)]
3750    #[should_panic(expected = "model dropped with pending condition")]
3751    async fn test_model_condition_panic_on_drop(mut cx: TestAppContext) {
3752        struct Model;
3753
3754        impl super::Entity for Model {
3755            type Event = ();
3756        }
3757
3758        let model = cx.add_model(|_| Model);
3759        let condition = model.condition(&cx, |_, _| false);
3760        cx.update(|_| drop(model));
3761        condition.await;
3762    }
3763
3764    #[crate::test(self)]
3765    async fn test_view_condition(mut cx: TestAppContext) {
3766        struct Counter(usize);
3767
3768        impl super::Entity for Counter {
3769            type Event = ();
3770        }
3771
3772        impl super::View for Counter {
3773            fn ui_name() -> &'static str {
3774                "test view"
3775            }
3776
3777            fn render(&self, _: &RenderContext<Self>) -> ElementBox {
3778                Empty::new().boxed()
3779            }
3780        }
3781
3782        impl Counter {
3783            fn inc(&mut self, cx: &mut ViewContext<Self>) {
3784                self.0 += 1;
3785                cx.notify();
3786            }
3787        }
3788
3789        let (_, view) = cx.add_window(|_| Counter(0));
3790
3791        let condition1 = view.condition(&cx, |view, _| view.0 == 2);
3792        let condition2 = view.condition(&cx, |view, _| view.0 == 3);
3793        smol::pin!(condition1, condition2);
3794
3795        view.update(&mut cx, |view, cx| view.inc(cx));
3796        assert_eq!(poll_once(&mut condition1).await, None);
3797        assert_eq!(poll_once(&mut condition2).await, None);
3798
3799        view.update(&mut cx, |view, cx| view.inc(cx));
3800        assert_eq!(poll_once(&mut condition1).await, Some(()));
3801        assert_eq!(poll_once(&mut condition2).await, None);
3802
3803        view.update(&mut cx, |view, cx| view.inc(cx));
3804        assert_eq!(poll_once(&mut condition2).await, Some(()));
3805        view.update(&mut cx, |_, cx| cx.notify());
3806    }
3807
3808    #[crate::test(self)]
3809    #[should_panic]
3810    async fn test_view_condition_timeout(mut cx: TestAppContext) {
3811        struct View;
3812
3813        impl super::Entity for View {
3814            type Event = ();
3815        }
3816
3817        impl super::View for View {
3818            fn ui_name() -> &'static str {
3819                "test view"
3820            }
3821
3822            fn render(&self, _: &RenderContext<Self>) -> ElementBox {
3823                Empty::new().boxed()
3824            }
3825        }
3826
3827        let (_, view) = cx.add_window(|_| View);
3828        view.condition(&cx, |_, _| false).await;
3829    }
3830
3831    #[crate::test(self)]
3832    #[should_panic(expected = "view dropped with pending condition")]
3833    async fn test_view_condition_panic_on_drop(mut cx: TestAppContext) {
3834        struct View;
3835
3836        impl super::Entity for View {
3837            type Event = ();
3838        }
3839
3840        impl super::View for View {
3841            fn ui_name() -> &'static str {
3842                "test view"
3843            }
3844
3845            fn render(&self, _: &RenderContext<Self>) -> ElementBox {
3846                Empty::new().boxed()
3847            }
3848        }
3849
3850        let window_id = cx.add_window(|_| View).0;
3851        let view = cx.add_view(window_id, |_| View);
3852
3853        let condition = view.condition(&cx, |_, _| false);
3854        cx.update(|_| drop(view));
3855        condition.await;
3856    }
3857}