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