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