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