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