app.rs

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