app.rs

   1pub mod action;
   2mod callback_collection;
   3mod menu;
   4pub(crate) mod ref_counts;
   5#[cfg(any(test, feature = "test-support"))]
   6pub mod test_app_context;
   7pub(crate) mod window;
   8mod window_input_handler;
   9
  10use std::{
  11    any::{type_name, Any, TypeId},
  12    cell::RefCell,
  13    fmt::{self, Debug},
  14    hash::{Hash, Hasher},
  15    marker::PhantomData,
  16    mem,
  17    ops::{Deref, DerefMut, Range},
  18    path::{Path, PathBuf},
  19    pin::Pin,
  20    rc::{self, Rc},
  21    sync::{Arc, Weak},
  22    time::Duration,
  23};
  24
  25use anyhow::{anyhow, Context, Result};
  26use parking_lot::Mutex;
  27use postage::oneshot;
  28use smol::prelude::*;
  29use util::ResultExt;
  30use uuid::Uuid;
  31
  32pub use action::*;
  33use callback_collection::CallbackCollection;
  34use collections::{hash_map::Entry, BTreeMap, HashMap, HashSet, VecDeque};
  35pub use menu::*;
  36use platform::Event;
  37#[cfg(any(test, feature = "test-support"))]
  38use ref_counts::LeakDetector;
  39#[cfg(any(test, feature = "test-support"))]
  40pub use test_app_context::{ContextHandle, TestAppContext};
  41use window_input_handler::WindowInputHandler;
  42
  43use crate::{
  44    elements::{AnyElement, AnyRootElement, RootElement},
  45    executor::{self, Task},
  46    keymap_matcher::{self, Binding, KeymapContext, KeymapMatcher, Keystroke, MatchResult},
  47    platform::{
  48        self, FontSystem, KeyDownEvent, KeyUpEvent, ModifiersChangedEvent, MouseButton,
  49        PathPromptOptions, Platform, PromptLevel, WindowBounds, WindowOptions,
  50    },
  51    util::post_inc,
  52    window::{Window, WindowContext},
  53    AssetCache, AssetSource, ClipboardItem, FontCache, MouseRegionId,
  54};
  55
  56use self::ref_counts::RefCounts;
  57
  58pub trait Entity: 'static {
  59    type Event;
  60
  61    fn release(&mut self, _: &mut AppContext) {}
  62    fn app_will_quit(
  63        &mut self,
  64        _: &mut AppContext,
  65    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
  66        None
  67    }
  68}
  69
  70pub trait View: Entity + Sized {
  71    fn ui_name() -> &'static str;
  72    fn render(&mut self, cx: &mut ViewContext<'_, '_, Self>) -> AnyElement<Self>;
  73    fn focus_in(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {}
  74    fn focus_out(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {}
  75    fn key_down(&mut self, _: &KeyDownEvent, _: &mut ViewContext<Self>) -> bool {
  76        false
  77    }
  78    fn key_up(&mut self, _: &KeyUpEvent, _: &mut ViewContext<Self>) -> bool {
  79        false
  80    }
  81    fn modifiers_changed(&mut self, _: &ModifiersChangedEvent, _: &mut ViewContext<Self>) -> bool {
  82        false
  83    }
  84
  85    fn keymap_context(&self, _: &AppContext) -> keymap_matcher::KeymapContext {
  86        Self::default_keymap_context()
  87    }
  88    fn default_keymap_context() -> keymap_matcher::KeymapContext {
  89        let mut cx = keymap_matcher::KeymapContext::default();
  90        cx.add_identifier(Self::ui_name());
  91        cx
  92    }
  93    fn debug_json(&self, _: &AppContext) -> serde_json::Value {
  94        serde_json::Value::Null
  95    }
  96
  97    fn text_for_range(&self, _: Range<usize>, _: &AppContext) -> Option<String> {
  98        None
  99    }
 100    fn selected_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
 101        None
 102    }
 103    fn marked_text_range(&self, _: &AppContext) -> Option<Range<usize>> {
 104        None
 105    }
 106    fn unmark_text(&mut self, _: &mut ViewContext<Self>) {}
 107    fn replace_text_in_range(
 108        &mut self,
 109        _: Option<Range<usize>>,
 110        _: &str,
 111        _: &mut ViewContext<Self>,
 112    ) {
 113    }
 114    fn replace_and_mark_text_in_range(
 115        &mut self,
 116        _: Option<Range<usize>>,
 117        _: &str,
 118        _: Option<Range<usize>>,
 119        _: &mut ViewContext<Self>,
 120    ) {
 121    }
 122}
 123
 124pub trait BorrowAppContext {
 125    fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T;
 126    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T;
 127}
 128
 129pub trait BorrowWindowContext {
 130    type ReturnValue<T>;
 131
 132    fn read_with<T, F: FnOnce(&WindowContext) -> T>(
 133        &self,
 134        window_id: usize,
 135        f: F,
 136    ) -> Self::ReturnValue<T>;
 137    fn update<T, F: FnOnce(&mut WindowContext) -> T>(
 138        &mut self,
 139        window_id: usize,
 140        f: F,
 141    ) -> Self::ReturnValue<T>;
 142}
 143
 144#[derive(Clone)]
 145pub struct App(Rc<RefCell<AppContext>>);
 146
 147impl App {
 148    pub fn new(asset_source: impl AssetSource) -> Result<Self> {
 149        let platform = platform::current::platform();
 150        let foreground = Rc::new(executor::Foreground::platform(platform.dispatcher())?);
 151        let foreground_platform = platform::current::foreground_platform(foreground.clone());
 152        let app = Self(Rc::new(RefCell::new(AppContext::new(
 153            foreground,
 154            Arc::new(executor::Background::new()),
 155            platform.clone(),
 156            foreground_platform.clone(),
 157            Arc::new(FontCache::new(platform.fonts())),
 158            Default::default(),
 159            asset_source,
 160        ))));
 161
 162        foreground_platform.on_quit(Box::new({
 163            let cx = app.0.clone();
 164            move || {
 165                cx.borrow_mut().quit();
 166            }
 167        }));
 168        setup_menu_handlers(foreground_platform.as_ref(), &app);
 169
 170        app.0.borrow_mut().weak_self = Some(Rc::downgrade(&app.0));
 171        Ok(app)
 172    }
 173
 174    pub fn background(&self) -> Arc<executor::Background> {
 175        self.0.borrow().background().clone()
 176    }
 177
 178    pub fn on_become_active<F>(self, mut callback: F) -> Self
 179    where
 180        F: 'static + FnMut(&mut AppContext),
 181    {
 182        let cx = self.0.clone();
 183        self.0
 184            .borrow_mut()
 185            .foreground_platform
 186            .on_become_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 187        self
 188    }
 189
 190    pub fn on_resign_active<F>(self, mut callback: F) -> Self
 191    where
 192        F: 'static + FnMut(&mut AppContext),
 193    {
 194        let cx = self.0.clone();
 195        self.0
 196            .borrow_mut()
 197            .foreground_platform
 198            .on_resign_active(Box::new(move || callback(&mut *cx.borrow_mut())));
 199        self
 200    }
 201
 202    pub fn on_quit<F>(&mut self, mut callback: F) -> &mut Self
 203    where
 204        F: 'static + FnMut(&mut AppContext),
 205    {
 206        let cx = self.0.clone();
 207        self.0
 208            .borrow_mut()
 209            .foreground_platform
 210            .on_quit(Box::new(move || callback(&mut *cx.borrow_mut())));
 211        self
 212    }
 213
 214    /// Handle the application being re-activated when no windows are open.
 215    pub fn on_reopen<F>(&mut self, mut callback: F) -> &mut Self
 216    where
 217        F: 'static + FnMut(&mut AppContext),
 218    {
 219        let cx = self.0.clone();
 220        self.0
 221            .borrow_mut()
 222            .foreground_platform
 223            .on_reopen(Box::new(move || callback(&mut *cx.borrow_mut())));
 224        self
 225    }
 226
 227    pub fn on_event<F>(&mut self, mut callback: F) -> &mut Self
 228    where
 229        F: 'static + FnMut(Event, &mut AppContext) -> bool,
 230    {
 231        let cx = self.0.clone();
 232        self.0
 233            .borrow_mut()
 234            .foreground_platform
 235            .on_event(Box::new(move |event| {
 236                callback(event, &mut *cx.borrow_mut())
 237            }));
 238        self
 239    }
 240
 241    pub fn on_open_urls<F>(&mut self, mut callback: F) -> &mut Self
 242    where
 243        F: 'static + FnMut(Vec<String>, &mut AppContext),
 244    {
 245        let cx = self.0.clone();
 246        self.0
 247            .borrow_mut()
 248            .foreground_platform
 249            .on_open_urls(Box::new(move |urls| callback(urls, &mut *cx.borrow_mut())));
 250        self
 251    }
 252
 253    pub fn run<F>(self, on_finish_launching: F)
 254    where
 255        F: 'static + FnOnce(&mut AppContext),
 256    {
 257        let platform = self.0.borrow().foreground_platform.clone();
 258        platform.run(Box::new(move || {
 259            let mut cx = self.0.borrow_mut();
 260            let cx = &mut *cx;
 261            crate::views::init(cx);
 262            on_finish_launching(cx);
 263        }))
 264    }
 265
 266    pub fn platform(&self) -> Arc<dyn Platform> {
 267        self.0.borrow().platform.clone()
 268    }
 269
 270    pub fn font_cache(&self) -> Arc<FontCache> {
 271        self.0.borrow().font_cache.clone()
 272    }
 273
 274    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, callback: F) -> T {
 275        let mut state = self.0.borrow_mut();
 276        let result = state.update(callback);
 277        state.pending_notifications.clear();
 278        result
 279    }
 280
 281    fn update_window<T, F: FnOnce(&mut WindowContext) -> T>(
 282        &mut self,
 283        window_id: usize,
 284        callback: F,
 285    ) -> Option<T> {
 286        let mut state = self.0.borrow_mut();
 287        let result = state.update_window(window_id, callback);
 288        state.pending_notifications.clear();
 289        result
 290    }
 291}
 292
 293#[derive(Clone)]
 294pub struct AsyncAppContext(Rc<RefCell<AppContext>>);
 295
 296impl AsyncAppContext {
 297    pub fn spawn<F, Fut, T>(&self, f: F) -> Task<T>
 298    where
 299        F: FnOnce(AsyncAppContext) -> Fut,
 300        Fut: 'static + Future<Output = T>,
 301        T: 'static,
 302    {
 303        self.0.borrow().foreground.spawn(f(self.clone()))
 304    }
 305
 306    pub fn read<T, F: FnOnce(&AppContext) -> T>(&self, callback: F) -> T {
 307        callback(&*self.0.borrow())
 308    }
 309
 310    pub fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, callback: F) -> T {
 311        self.0.borrow_mut().update(callback)
 312    }
 313
 314    pub fn update_window<T, F: FnOnce(&mut WindowContext) -> T>(
 315        &mut self,
 316        window_id: usize,
 317        callback: F,
 318    ) -> Option<T> {
 319        self.0.borrow_mut().update_window(window_id, callback)
 320    }
 321
 322    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
 323    where
 324        T: Entity,
 325        F: FnOnce(&mut ModelContext<T>) -> T,
 326    {
 327        self.update(|cx| cx.add_model(build_model))
 328    }
 329
 330    pub fn add_window<T, F>(
 331        &mut self,
 332        window_options: WindowOptions,
 333        build_root_view: F,
 334    ) -> (usize, ViewHandle<T>)
 335    where
 336        T: View,
 337        F: FnOnce(&mut ViewContext<T>) -> T,
 338    {
 339        self.update(|cx| cx.add_window(window_options, build_root_view))
 340    }
 341
 342    pub fn remove_window(&mut self, window_id: usize) {
 343        self.update(|cx| cx.remove_window(window_id))
 344    }
 345
 346    pub fn activate_window(&mut self, window_id: usize) {
 347        self.update_window(window_id, |cx| cx.activate_window());
 348    }
 349
 350    // TODO: Can we eliminate this method and move it to WindowContext then call it with update_window?s
 351    pub fn prompt(
 352        &mut self,
 353        window_id: usize,
 354        level: PromptLevel,
 355        msg: &str,
 356        answers: &[&str],
 357    ) -> Option<oneshot::Receiver<usize>> {
 358        self.update_window(window_id, |cx| cx.prompt(level, msg, answers))
 359    }
 360
 361    pub fn platform(&self) -> Arc<dyn Platform> {
 362        self.0.borrow().platform().clone()
 363    }
 364
 365    pub fn foreground(&self) -> Rc<executor::Foreground> {
 366        self.0.borrow().foreground.clone()
 367    }
 368
 369    pub fn background(&self) -> Arc<executor::Background> {
 370        self.0.borrow().background.clone()
 371    }
 372}
 373
 374impl BorrowAppContext for AsyncAppContext {
 375    fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
 376        self.0.borrow().read_with(f)
 377    }
 378
 379    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
 380        self.0.borrow_mut().update(f)
 381    }
 382}
 383
 384impl BorrowWindowContext for AsyncAppContext {
 385    type ReturnValue<T> = Result<T>;
 386
 387    fn read_with<T, F: FnOnce(&WindowContext) -> T>(&self, window_id: usize, f: F) -> Result<T> {
 388        self.0
 389            .borrow()
 390            .read_window(window_id, f)
 391            .ok_or_else(|| anyhow!("window was closed"))
 392    }
 393
 394    fn update<T, F: FnOnce(&mut WindowContext) -> T>(
 395        &mut self,
 396        window_id: usize,
 397        f: F,
 398    ) -> Result<T> {
 399        self.0
 400            .borrow_mut()
 401            .update_window(window_id, f)
 402            .ok_or_else(|| anyhow!("window was closed"))
 403    }
 404}
 405
 406type ActionCallback = dyn FnMut(&mut dyn AnyView, &dyn Action, &mut WindowContext, usize);
 407type GlobalActionCallback = dyn FnMut(&dyn Action, &mut AppContext);
 408
 409type SubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool>;
 410type GlobalSubscriptionCallback = Box<dyn FnMut(&dyn Any, &mut AppContext)>;
 411type ObservationCallback = Box<dyn FnMut(&mut AppContext) -> bool>;
 412type GlobalObservationCallback = Box<dyn FnMut(&mut AppContext)>;
 413type FocusObservationCallback = Box<dyn FnMut(bool, &mut WindowContext) -> bool>;
 414type ReleaseObservationCallback = Box<dyn FnMut(&dyn Any, &mut AppContext)>;
 415type ActionObservationCallback = Box<dyn FnMut(TypeId, &mut AppContext)>;
 416type WindowActivationCallback = Box<dyn FnMut(bool, &mut WindowContext) -> bool>;
 417type WindowFullscreenCallback = Box<dyn FnMut(bool, &mut WindowContext) -> bool>;
 418type WindowBoundsCallback = Box<dyn FnMut(WindowBounds, Uuid, &mut WindowContext) -> bool>;
 419type KeystrokeCallback =
 420    Box<dyn FnMut(&Keystroke, &MatchResult, Option<&Box<dyn Action>>, &mut WindowContext) -> bool>;
 421type ActiveLabeledTasksCallback = Box<dyn FnMut(&mut AppContext) -> bool>;
 422type DeserializeActionCallback = fn(json: &str) -> anyhow::Result<Box<dyn Action>>;
 423type WindowShouldCloseSubscriptionCallback = Box<dyn FnMut(&mut AppContext) -> bool>;
 424
 425pub struct AppContext {
 426    models: HashMap<usize, Box<dyn AnyModel>>,
 427    views: HashMap<(usize, usize), Box<dyn AnyView>>,
 428    pub(crate) parents: HashMap<(usize, usize), ParentId>,
 429    windows: HashMap<usize, Window>,
 430    globals: HashMap<TypeId, Box<dyn Any>>,
 431    element_states: HashMap<ElementStateId, Box<dyn Any>>,
 432    background: Arc<executor::Background>,
 433    ref_counts: Arc<Mutex<RefCounts>>,
 434
 435    weak_self: Option<rc::Weak<RefCell<Self>>>,
 436    platform: Arc<dyn Platform>,
 437    foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 438    pub asset_cache: Arc<AssetCache>,
 439    font_system: Arc<dyn FontSystem>,
 440    pub font_cache: Arc<FontCache>,
 441    action_deserializers: HashMap<&'static str, (TypeId, DeserializeActionCallback)>,
 442    capture_actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 443    // Entity Types -> { Action Types -> Action Handlers }
 444    actions: HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>>,
 445    // Action Types -> Action Handlers
 446    global_actions: HashMap<TypeId, Box<GlobalActionCallback>>,
 447    keystroke_matcher: KeymapMatcher,
 448    next_entity_id: usize,
 449    next_window_id: usize,
 450    next_subscription_id: usize,
 451    frame_count: usize,
 452
 453    subscriptions: CallbackCollection<usize, SubscriptionCallback>,
 454    global_subscriptions: CallbackCollection<TypeId, GlobalSubscriptionCallback>,
 455    observations: CallbackCollection<usize, ObservationCallback>,
 456    global_observations: CallbackCollection<TypeId, GlobalObservationCallback>,
 457    focus_observations: CallbackCollection<usize, FocusObservationCallback>,
 458    release_observations: CallbackCollection<usize, ReleaseObservationCallback>,
 459    action_dispatch_observations: CallbackCollection<(), ActionObservationCallback>,
 460    window_activation_observations: CallbackCollection<usize, WindowActivationCallback>,
 461    window_fullscreen_observations: CallbackCollection<usize, WindowFullscreenCallback>,
 462    window_bounds_observations: CallbackCollection<usize, WindowBoundsCallback>,
 463    keystroke_observations: CallbackCollection<usize, KeystrokeCallback>,
 464    active_labeled_task_observations: CallbackCollection<(), ActiveLabeledTasksCallback>,
 465
 466    foreground: Rc<executor::Foreground>,
 467    pending_effects: VecDeque<Effect>,
 468    pending_notifications: HashSet<usize>,
 469    pending_global_notifications: HashSet<TypeId>,
 470    pending_flushes: usize,
 471    flushing_effects: bool,
 472    halt_action_dispatch: bool,
 473    next_labeled_task_id: usize,
 474    active_labeled_tasks: BTreeMap<usize, &'static str>,
 475}
 476
 477impl AppContext {
 478    fn new(
 479        foreground: Rc<executor::Foreground>,
 480        background: Arc<executor::Background>,
 481        platform: Arc<dyn platform::Platform>,
 482        foreground_platform: Rc<dyn platform::ForegroundPlatform>,
 483        font_cache: Arc<FontCache>,
 484        ref_counts: RefCounts,
 485        asset_source: impl AssetSource,
 486    ) -> Self {
 487        Self {
 488            models: Default::default(),
 489            views: Default::default(),
 490            parents: Default::default(),
 491            windows: Default::default(),
 492            globals: Default::default(),
 493            element_states: Default::default(),
 494            ref_counts: Arc::new(Mutex::new(ref_counts)),
 495            background,
 496
 497            weak_self: None,
 498            font_system: platform.fonts(),
 499            platform,
 500            foreground_platform,
 501            font_cache,
 502            asset_cache: Arc::new(AssetCache::new(asset_source)),
 503            action_deserializers: Default::default(),
 504            capture_actions: Default::default(),
 505            actions: Default::default(),
 506            global_actions: Default::default(),
 507            keystroke_matcher: KeymapMatcher::default(),
 508            next_entity_id: 0,
 509            next_window_id: 0,
 510            next_subscription_id: 0,
 511            frame_count: 0,
 512            subscriptions: Default::default(),
 513            global_subscriptions: Default::default(),
 514            observations: Default::default(),
 515            focus_observations: Default::default(),
 516            release_observations: Default::default(),
 517            global_observations: Default::default(),
 518            window_activation_observations: Default::default(),
 519            window_fullscreen_observations: Default::default(),
 520            window_bounds_observations: Default::default(),
 521            keystroke_observations: Default::default(),
 522            action_dispatch_observations: Default::default(),
 523            active_labeled_task_observations: Default::default(),
 524            foreground,
 525            pending_effects: VecDeque::new(),
 526            pending_notifications: Default::default(),
 527            pending_global_notifications: Default::default(),
 528            pending_flushes: 0,
 529            flushing_effects: false,
 530            halt_action_dispatch: false,
 531            next_labeled_task_id: 0,
 532            active_labeled_tasks: Default::default(),
 533        }
 534    }
 535
 536    pub fn background(&self) -> &Arc<executor::Background> {
 537        &self.background
 538    }
 539
 540    pub fn font_cache(&self) -> &Arc<FontCache> {
 541        &self.font_cache
 542    }
 543
 544    pub fn platform(&self) -> &Arc<dyn Platform> {
 545        &self.platform
 546    }
 547
 548    pub fn has_global<T: 'static>(&self) -> bool {
 549        self.globals.contains_key(&TypeId::of::<T>())
 550    }
 551
 552    pub fn global<T: 'static>(&self) -> &T {
 553        if let Some(global) = self.globals.get(&TypeId::of::<T>()) {
 554            global.downcast_ref().unwrap()
 555        } else {
 556            panic!("no global has been added for {}", type_name::<T>());
 557        }
 558    }
 559
 560    pub fn upgrade(&self) -> App {
 561        App(self.weak_self.as_ref().unwrap().upgrade().unwrap())
 562    }
 563
 564    pub fn quit(&mut self) {
 565        let mut futures = Vec::new();
 566
 567        self.update(|cx| {
 568            for model_id in cx.models.keys().copied().collect::<Vec<_>>() {
 569                let mut model = cx.models.remove(&model_id).unwrap();
 570                futures.extend(model.app_will_quit(cx));
 571                cx.models.insert(model_id, model);
 572            }
 573
 574            for view_id in cx.views.keys().copied().collect::<Vec<_>>() {
 575                let mut view = cx.views.remove(&view_id).unwrap();
 576                futures.extend(view.app_will_quit(cx));
 577                cx.views.insert(view_id, view);
 578            }
 579        });
 580
 581        self.remove_all_windows();
 582
 583        let futures = futures::future::join_all(futures);
 584        if self
 585            .background
 586            .block_with_timeout(Duration::from_millis(100), futures)
 587            .is_err()
 588        {
 589            log::error!("timed out waiting on app_will_quit");
 590        }
 591    }
 592
 593    pub fn remove_all_windows(&mut self) {
 594        self.windows.clear();
 595        self.flush_effects();
 596    }
 597
 598    pub fn foreground(&self) -> &Rc<executor::Foreground> {
 599        &self.foreground
 600    }
 601
 602    pub fn deserialize_action(
 603        &self,
 604        name: &str,
 605        argument: Option<&str>,
 606    ) -> Result<Box<dyn Action>> {
 607        let callback = self
 608            .action_deserializers
 609            .get(name)
 610            .ok_or_else(|| anyhow!("unknown action {}", name))?
 611            .1;
 612        callback(argument.unwrap_or("{}"))
 613            .with_context(|| format!("invalid data for action {}", name))
 614    }
 615
 616    pub fn add_action<A, V, F, R>(&mut self, handler: F)
 617    where
 618        A: Action,
 619        V: View,
 620        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> R,
 621    {
 622        self.add_action_internal(handler, false)
 623    }
 624
 625    pub fn capture_action<A, V, F>(&mut self, handler: F)
 626    where
 627        A: Action,
 628        V: View,
 629        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>),
 630    {
 631        self.add_action_internal(handler, true)
 632    }
 633
 634    fn add_action_internal<A, V, F, R>(&mut self, mut handler: F, capture: bool)
 635    where
 636        A: Action,
 637        V: View,
 638        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> R,
 639    {
 640        let handler = Box::new(
 641            move |view: &mut dyn AnyView,
 642                  action: &dyn Action,
 643                  cx: &mut WindowContext,
 644                  view_id: usize| {
 645                let action = action.as_any().downcast_ref().unwrap();
 646                let mut cx = ViewContext::mutable(cx, view_id);
 647                handler(
 648                    view.as_any_mut()
 649                        .downcast_mut()
 650                        .expect("downcast is type safe"),
 651                    action,
 652                    &mut cx,
 653                );
 654            },
 655        );
 656
 657        self.action_deserializers
 658            .entry(A::qualified_name())
 659            .or_insert((TypeId::of::<A>(), A::from_json_str));
 660
 661        let actions = if capture {
 662            &mut self.capture_actions
 663        } else {
 664            &mut self.actions
 665        };
 666
 667        actions
 668            .entry(TypeId::of::<V>())
 669            .or_default()
 670            .entry(TypeId::of::<A>())
 671            .or_default()
 672            .push(handler);
 673    }
 674
 675    pub fn add_async_action<A, V, F>(&mut self, mut handler: F)
 676    where
 677        A: Action,
 678        V: View,
 679        F: 'static + FnMut(&mut V, &A, &mut ViewContext<V>) -> Option<Task<Result<()>>>,
 680    {
 681        self.add_action(move |view, action, cx| {
 682            if let Some(task) = handler(view, action, cx) {
 683                task.detach_and_log_err(cx);
 684            }
 685        })
 686    }
 687
 688    pub fn add_global_action<A, F>(&mut self, mut handler: F)
 689    where
 690        A: Action,
 691        F: 'static + FnMut(&A, &mut AppContext),
 692    {
 693        let handler = Box::new(move |action: &dyn Action, cx: &mut AppContext| {
 694            let action = action.as_any().downcast_ref().unwrap();
 695            handler(action, cx);
 696        });
 697
 698        self.action_deserializers
 699            .entry(A::qualified_name())
 700            .or_insert((TypeId::of::<A>(), A::from_json_str));
 701
 702        if self
 703            .global_actions
 704            .insert(TypeId::of::<A>(), handler)
 705            .is_some()
 706        {
 707            panic!(
 708                "registered multiple global handlers for {}",
 709                type_name::<A>()
 710            );
 711        }
 712    }
 713
 714    pub fn has_window(&self, window_id: usize) -> bool {
 715        self.window_ids()
 716            .find(|window| window == &window_id)
 717            .is_some()
 718    }
 719
 720    pub fn window_is_active(&self, window_id: usize) -> bool {
 721        self.windows.get(&window_id).map_or(false, |w| w.is_active)
 722    }
 723
 724    pub fn root_view(&self, window_id: usize) -> Option<&AnyViewHandle> {
 725        self.windows.get(&window_id).map(|w| w.root_view())
 726    }
 727
 728    pub fn window_ids(&self) -> impl Iterator<Item = usize> + '_ {
 729        self.windows.keys().copied()
 730    }
 731
 732    pub fn view_ui_name(&self, window_id: usize, view_id: usize) -> Option<&'static str> {
 733        Some(self.views.get(&(window_id, view_id))?.ui_name())
 734    }
 735
 736    pub fn view_type_id(&self, window_id: usize, view_id: usize) -> Option<TypeId> {
 737        self.views
 738            .get(&(window_id, view_id))
 739            .map(|view| view.as_any().type_id())
 740    }
 741
 742    pub fn active_labeled_tasks<'a>(
 743        &'a self,
 744    ) -> impl DoubleEndedIterator<Item = &'static str> + 'a {
 745        self.active_labeled_tasks.values().cloned()
 746    }
 747
 748    pub(crate) fn start_frame(&mut self) {
 749        self.frame_count += 1;
 750    }
 751
 752    pub fn update<T, F: FnOnce(&mut Self) -> T>(&mut self, callback: F) -> T {
 753        self.pending_flushes += 1;
 754        let result = callback(self);
 755        self.flush_effects();
 756        result
 757    }
 758
 759    pub fn read_window<T, F: FnOnce(&WindowContext) -> T>(
 760        &self,
 761        window_id: usize,
 762        callback: F,
 763    ) -> Option<T> {
 764        let window = self.windows.get(&window_id)?;
 765        let window_context = WindowContext::immutable(self, &window, window_id);
 766        Some(callback(&window_context))
 767    }
 768
 769    pub fn update_window<T, F: FnOnce(&mut WindowContext) -> T>(
 770        &mut self,
 771        window_id: usize,
 772        callback: F,
 773    ) -> Option<T> {
 774        self.update(|app_context| {
 775            let mut window = app_context.windows.remove(&window_id)?;
 776            let mut window_context = WindowContext::mutable(app_context, &mut window, window_id);
 777            let result = callback(&mut window_context);
 778            if !window_context.removed {
 779                app_context.windows.insert(window_id, window);
 780            }
 781            Some(result)
 782        })
 783    }
 784
 785    pub fn update_active_window<T, F: FnOnce(&mut WindowContext) -> T>(
 786        &mut self,
 787        callback: F,
 788    ) -> Option<T> {
 789        self.platform
 790            .main_window_id()
 791            .and_then(|id| self.update_window(id, callback))
 792    }
 793
 794    pub fn prompt_for_paths(
 795        &self,
 796        options: PathPromptOptions,
 797    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 798        self.foreground_platform.prompt_for_paths(options)
 799    }
 800
 801    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
 802        self.foreground_platform.prompt_for_new_path(directory)
 803    }
 804
 805    pub fn reveal_path(&self, path: &Path) {
 806        self.foreground_platform.reveal_path(path)
 807    }
 808
 809    pub fn emit_global<E: Any>(&mut self, payload: E) {
 810        self.pending_effects.push_back(Effect::GlobalEvent {
 811            payload: Box::new(payload),
 812        });
 813    }
 814
 815    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 816    where
 817        E: Entity,
 818        E::Event: 'static,
 819        H: Handle<E>,
 820        F: 'static + FnMut(H, &E::Event, &mut Self),
 821    {
 822        self.subscribe_internal(handle, move |handle, event, cx| {
 823            callback(handle, event, cx);
 824            true
 825        })
 826    }
 827
 828    pub fn subscribe_global<E, F>(&mut self, mut callback: F) -> Subscription
 829    where
 830        E: Any,
 831        F: 'static + FnMut(&E, &mut Self),
 832    {
 833        let subscription_id = post_inc(&mut self.next_subscription_id);
 834        let type_id = TypeId::of::<E>();
 835        self.pending_effects.push_back(Effect::GlobalSubscription {
 836            type_id,
 837            subscription_id,
 838            callback: Box::new(move |payload, cx| {
 839                let payload = payload.downcast_ref().expect("downcast is type safe");
 840                callback(payload, cx)
 841            }),
 842        });
 843        Subscription::GlobalSubscription(
 844            self.global_subscriptions
 845                .subscribe(type_id, subscription_id),
 846        )
 847    }
 848
 849    pub fn observe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 850    where
 851        E: Entity,
 852        E::Event: 'static,
 853        H: Handle<E>,
 854        F: 'static + FnMut(H, &mut Self),
 855    {
 856        self.observe_internal(handle, move |handle, cx| {
 857            callback(handle, cx);
 858            true
 859        })
 860    }
 861
 862    fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 863    where
 864        E: Entity,
 865        E::Event: 'static,
 866        H: Handle<E>,
 867        F: 'static + FnMut(H, &E::Event, &mut Self) -> bool,
 868    {
 869        let subscription_id = post_inc(&mut self.next_subscription_id);
 870        let emitter = handle.downgrade();
 871        self.pending_effects.push_back(Effect::Subscription {
 872            entity_id: handle.id(),
 873            subscription_id,
 874            callback: Box::new(move |payload, cx| {
 875                if let Some(emitter) = H::upgrade_from(&emitter, cx) {
 876                    let payload = payload.downcast_ref().expect("downcast is type safe");
 877                    callback(emitter, payload, cx)
 878                } else {
 879                    false
 880                }
 881            }),
 882        });
 883        Subscription::Subscription(self.subscriptions.subscribe(handle.id(), subscription_id))
 884    }
 885
 886    fn observe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 887    where
 888        E: Entity,
 889        E::Event: 'static,
 890        H: Handle<E>,
 891        F: 'static + FnMut(H, &mut Self) -> bool,
 892    {
 893        let subscription_id = post_inc(&mut self.next_subscription_id);
 894        let observed = handle.downgrade();
 895        let entity_id = handle.id();
 896        self.pending_effects.push_back(Effect::Observation {
 897            entity_id,
 898            subscription_id,
 899            callback: Box::new(move |cx| {
 900                if let Some(observed) = H::upgrade_from(&observed, cx) {
 901                    callback(observed, cx)
 902                } else {
 903                    false
 904                }
 905            }),
 906        });
 907        Subscription::Observation(self.observations.subscribe(entity_id, subscription_id))
 908    }
 909
 910    fn observe_focus<F, V>(&mut self, handle: &ViewHandle<V>, mut callback: F) -> Subscription
 911    where
 912        F: 'static + FnMut(ViewHandle<V>, bool, &mut WindowContext) -> bool,
 913        V: View,
 914    {
 915        let subscription_id = post_inc(&mut self.next_subscription_id);
 916        let observed = handle.downgrade();
 917        let view_id = handle.id();
 918
 919        self.pending_effects.push_back(Effect::FocusObservation {
 920            view_id,
 921            subscription_id,
 922            callback: Box::new(move |focused, cx| {
 923                if let Some(observed) = observed.upgrade(cx) {
 924                    callback(observed, focused, cx)
 925                } else {
 926                    false
 927                }
 928            }),
 929        });
 930        Subscription::FocusObservation(self.focus_observations.subscribe(view_id, subscription_id))
 931    }
 932
 933    pub fn observe_global<G, F>(&mut self, mut observe: F) -> Subscription
 934    where
 935        G: Any,
 936        F: 'static + FnMut(&mut AppContext),
 937    {
 938        let type_id = TypeId::of::<G>();
 939        let id = post_inc(&mut self.next_subscription_id);
 940
 941        self.global_observations.add_callback(
 942            type_id,
 943            id,
 944            Box::new(move |cx: &mut AppContext| observe(cx)),
 945        );
 946        Subscription::GlobalObservation(self.global_observations.subscribe(type_id, id))
 947    }
 948
 949    pub fn observe_default_global<G, F>(&mut self, observe: F) -> Subscription
 950    where
 951        G: Any + Default,
 952        F: 'static + FnMut(&mut AppContext),
 953    {
 954        if !self.has_global::<G>() {
 955            self.set_global(G::default());
 956        }
 957        self.observe_global::<G, F>(observe)
 958    }
 959
 960    pub fn observe_release<E, H, F>(&mut self, handle: &H, callback: F) -> Subscription
 961    where
 962        E: Entity,
 963        E::Event: 'static,
 964        H: Handle<E>,
 965        F: 'static + FnOnce(&E, &mut Self),
 966    {
 967        let id = post_inc(&mut self.next_subscription_id);
 968        let mut callback = Some(callback);
 969        self.release_observations.add_callback(
 970            handle.id(),
 971            id,
 972            Box::new(move |released, cx| {
 973                let released = released.downcast_ref().unwrap();
 974                if let Some(callback) = callback.take() {
 975                    callback(released, cx)
 976                }
 977            }),
 978        );
 979        Subscription::ReleaseObservation(self.release_observations.subscribe(handle.id(), id))
 980    }
 981
 982    pub fn observe_actions<F>(&mut self, callback: F) -> Subscription
 983    where
 984        F: 'static + FnMut(TypeId, &mut AppContext),
 985    {
 986        let subscription_id = post_inc(&mut self.next_subscription_id);
 987        self.action_dispatch_observations
 988            .add_callback((), subscription_id, Box::new(callback));
 989        Subscription::ActionObservation(
 990            self.action_dispatch_observations
 991                .subscribe((), subscription_id),
 992        )
 993    }
 994
 995    fn observe_active_labeled_tasks<F>(&mut self, callback: F) -> Subscription
 996    where
 997        F: 'static + FnMut(&mut AppContext) -> bool,
 998    {
 999        let subscription_id = post_inc(&mut self.next_subscription_id);
1000        self.active_labeled_task_observations
1001            .add_callback((), subscription_id, Box::new(callback));
1002        Subscription::ActiveLabeledTasksObservation(
1003            self.active_labeled_task_observations
1004                .subscribe((), subscription_id),
1005        )
1006    }
1007
1008    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut AppContext)) {
1009        self.pending_effects.push_back(Effect::Deferred {
1010            callback: Box::new(callback),
1011            after_window_update: false,
1012        })
1013    }
1014
1015    pub fn after_window_update(&mut self, callback: impl 'static + FnOnce(&mut AppContext)) {
1016        self.pending_effects.push_back(Effect::Deferred {
1017            callback: Box::new(callback),
1018            after_window_update: true,
1019        })
1020    }
1021
1022    fn notify_model(&mut self, model_id: usize) {
1023        if self.pending_notifications.insert(model_id) {
1024            self.pending_effects
1025                .push_back(Effect::ModelNotification { model_id });
1026        }
1027    }
1028
1029    fn notify_view(&mut self, window_id: usize, view_id: usize) {
1030        if self.pending_notifications.insert(view_id) {
1031            self.pending_effects
1032                .push_back(Effect::ViewNotification { window_id, view_id });
1033        }
1034    }
1035
1036    fn notify_global(&mut self, type_id: TypeId) {
1037        if self.pending_global_notifications.insert(type_id) {
1038            self.pending_effects
1039                .push_back(Effect::GlobalNotification { type_id });
1040        }
1041    }
1042
1043    pub fn all_action_names<'a>(&'a self) -> impl Iterator<Item = &'static str> + 'a {
1044        self.action_deserializers.keys().copied()
1045    }
1046
1047    pub fn is_action_available(&self, action: &dyn Action) -> bool {
1048        let mut available_in_window = false;
1049        let action_type = action.as_any().type_id();
1050        if let Some(window_id) = self.platform.main_window_id() {
1051            available_in_window = self
1052                .read_window(window_id, |cx| {
1053                    if let Some(focused_view_id) = cx.focused_view_id() {
1054                        for view_id in cx.ancestors(focused_view_id) {
1055                            if let Some(view) = cx.views.get(&(window_id, view_id)) {
1056                                let view_type = view.as_any().type_id();
1057                                if let Some(actions) = cx.actions.get(&view_type) {
1058                                    if actions.contains_key(&action_type) {
1059                                        return true;
1060                                    }
1061                                }
1062                            }
1063                        }
1064                    }
1065                    false
1066                })
1067                .unwrap_or(false);
1068        }
1069        available_in_window || self.global_actions.contains_key(&action_type)
1070    }
1071
1072    fn actions_mut(
1073        &mut self,
1074        capture_phase: bool,
1075    ) -> &mut HashMap<TypeId, HashMap<TypeId, Vec<Box<ActionCallback>>>> {
1076        if capture_phase {
1077            &mut self.capture_actions
1078        } else {
1079            &mut self.actions
1080        }
1081    }
1082
1083    pub fn dispatch_global_action<A: Action>(&mut self, action: A) {
1084        self.dispatch_global_action_any(&action);
1085    }
1086
1087    fn dispatch_global_action_any(&mut self, action: &dyn Action) -> bool {
1088        self.update(|this| {
1089            if let Some((name, mut handler)) = this.global_actions.remove_entry(&action.id()) {
1090                handler(action, this);
1091                this.global_actions.insert(name, handler);
1092                true
1093            } else {
1094                false
1095            }
1096        })
1097    }
1098
1099    pub fn add_bindings<T: IntoIterator<Item = Binding>>(&mut self, bindings: T) {
1100        self.keystroke_matcher.add_bindings(bindings);
1101    }
1102
1103    pub fn clear_bindings(&mut self) {
1104        self.keystroke_matcher.clear_bindings();
1105    }
1106
1107    pub fn default_global<T: 'static + Default>(&mut self) -> &T {
1108        let type_id = TypeId::of::<T>();
1109        self.update(|this| {
1110            if let Entry::Vacant(entry) = this.globals.entry(type_id) {
1111                entry.insert(Box::new(T::default()));
1112                this.notify_global(type_id);
1113            }
1114        });
1115        self.globals.get(&type_id).unwrap().downcast_ref().unwrap()
1116    }
1117
1118    pub fn set_global<T: 'static>(&mut self, state: T) {
1119        self.update(|this| {
1120            let type_id = TypeId::of::<T>();
1121            this.globals.insert(type_id, Box::new(state));
1122            this.notify_global(type_id);
1123        });
1124    }
1125
1126    pub fn update_default_global<T, F, U>(&mut self, update: F) -> U
1127    where
1128        T: 'static + Default,
1129        F: FnOnce(&mut T, &mut AppContext) -> U,
1130    {
1131        self.update(|mut this| {
1132            Self::update_default_global_internal(&mut this, |global, cx| update(global, cx))
1133        })
1134    }
1135
1136    fn update_default_global_internal<C, T, F, U>(this: &mut C, update: F) -> U
1137    where
1138        C: DerefMut<Target = AppContext>,
1139        T: 'static + Default,
1140        F: FnOnce(&mut T, &mut C) -> U,
1141    {
1142        let type_id = TypeId::of::<T>();
1143        let mut state = this
1144            .globals
1145            .remove(&type_id)
1146            .unwrap_or_else(|| Box::new(T::default()));
1147        let result = update(state.downcast_mut().unwrap(), this);
1148        this.globals.insert(type_id, state);
1149        this.notify_global(type_id);
1150        result
1151    }
1152
1153    pub fn update_global<T, F, U>(&mut self, update: F) -> U
1154    where
1155        T: 'static,
1156        F: FnOnce(&mut T, &mut AppContext) -> U,
1157    {
1158        self.update(|mut this| {
1159            Self::update_global_internal(&mut this, |global, cx| update(global, cx))
1160        })
1161    }
1162
1163    fn update_global_internal<C, T, F, U>(this: &mut C, update: F) -> U
1164    where
1165        C: DerefMut<Target = AppContext>,
1166        T: 'static,
1167        F: FnOnce(&mut T, &mut C) -> U,
1168    {
1169        let type_id = TypeId::of::<T>();
1170        if let Some(mut state) = this.globals.remove(&type_id) {
1171            let result = update(state.downcast_mut().unwrap(), this);
1172            this.globals.insert(type_id, state);
1173            this.notify_global(type_id);
1174            result
1175        } else {
1176            panic!("No global added for {}", std::any::type_name::<T>());
1177        }
1178    }
1179
1180    pub fn clear_globals(&mut self) {
1181        self.globals.clear();
1182    }
1183
1184    pub fn add_model<T, F>(&mut self, build_model: F) -> ModelHandle<T>
1185    where
1186        T: Entity,
1187        F: FnOnce(&mut ModelContext<T>) -> T,
1188    {
1189        self.update(|this| {
1190            let model_id = post_inc(&mut this.next_entity_id);
1191            let handle = ModelHandle::new(model_id, &this.ref_counts);
1192            let mut cx = ModelContext::new(this, model_id);
1193            let model = build_model(&mut cx);
1194            this.models.insert(model_id, Box::new(model));
1195            handle
1196        })
1197    }
1198
1199    pub fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
1200        if let Some(model) = self.models.get(&handle.model_id) {
1201            model
1202                .as_any()
1203                .downcast_ref()
1204                .expect("downcast is type safe")
1205        } else {
1206            panic!("circular model reference");
1207        }
1208    }
1209
1210    fn update_model<T: Entity, V>(
1211        &mut self,
1212        handle: &ModelHandle<T>,
1213        update: &mut dyn FnMut(&mut T, &mut ModelContext<T>) -> V,
1214    ) -> V {
1215        if let Some(mut model) = self.models.remove(&handle.model_id) {
1216            self.update(|this| {
1217                let mut cx = ModelContext::new(this, handle.model_id);
1218                let result = update(
1219                    model
1220                        .as_any_mut()
1221                        .downcast_mut()
1222                        .expect("downcast is type safe"),
1223                    &mut cx,
1224                );
1225                this.models.insert(handle.model_id, model);
1226                result
1227            })
1228        } else {
1229            panic!("circular model update");
1230        }
1231    }
1232
1233    fn upgrade_model_handle<T: Entity>(
1234        &self,
1235        handle: &WeakModelHandle<T>,
1236    ) -> Option<ModelHandle<T>> {
1237        if self.ref_counts.lock().is_entity_alive(handle.model_id) {
1238            Some(ModelHandle::new(handle.model_id, &self.ref_counts))
1239        } else {
1240            None
1241        }
1242    }
1243
1244    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
1245        self.ref_counts.lock().is_entity_alive(handle.model_id)
1246    }
1247
1248    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
1249        if self.ref_counts.lock().is_entity_alive(handle.model_id) {
1250            Some(AnyModelHandle::new(
1251                handle.model_id,
1252                handle.model_type,
1253                self.ref_counts.clone(),
1254            ))
1255        } else {
1256            None
1257        }
1258    }
1259
1260    pub fn add_window<V, F>(
1261        &mut self,
1262        window_options: WindowOptions,
1263        build_root_view: F,
1264    ) -> (usize, ViewHandle<V>)
1265    where
1266        V: View,
1267        F: FnOnce(&mut ViewContext<V>) -> V,
1268    {
1269        self.update(|this| {
1270            let window_id = post_inc(&mut this.next_window_id);
1271            let platform_window =
1272                this.platform
1273                    .open_window(window_id, window_options, this.foreground.clone());
1274            let window = this.build_window(window_id, platform_window, build_root_view);
1275            let root_view = window.root_view().clone().downcast::<V>().unwrap();
1276            this.windows.insert(window_id, window);
1277            (window_id, root_view)
1278        })
1279    }
1280
1281    pub fn add_status_bar_item<V, F>(&mut self, build_root_view: F) -> (usize, ViewHandle<V>)
1282    where
1283        V: View,
1284        F: FnOnce(&mut ViewContext<V>) -> V,
1285    {
1286        self.update(|this| {
1287            let window_id = post_inc(&mut this.next_window_id);
1288            let platform_window = this.platform.add_status_item(window_id);
1289            let window = this.build_window(window_id, platform_window, build_root_view);
1290            let root_view = window.root_view().clone().downcast::<V>().unwrap();
1291
1292            this.windows.insert(window_id, window);
1293            this.update_window(window_id, |cx| {
1294                root_view.update(cx, |view, cx| view.focus_in(cx.handle().into_any(), cx))
1295            });
1296
1297            (window_id, root_view)
1298        })
1299    }
1300
1301    pub fn remove_status_bar_item(&mut self, id: usize) {
1302        self.remove_window(id);
1303    }
1304
1305    pub fn remove_window(&mut self, window_id: usize) {
1306        self.windows.remove(&window_id);
1307        self.flush_effects();
1308    }
1309
1310    pub fn build_window<V, F>(
1311        &mut self,
1312        window_id: usize,
1313        mut platform_window: Box<dyn platform::Window>,
1314        build_root_view: F,
1315    ) -> Window
1316    where
1317        V: View,
1318        F: FnOnce(&mut ViewContext<V>) -> V,
1319    {
1320        {
1321            let mut app = self.upgrade();
1322
1323            platform_window.on_event(Box::new(move |event| {
1324                app.update_window(window_id, |cx| {
1325                    if let Event::KeyDown(KeyDownEvent { keystroke, .. }) = &event {
1326                        if cx.dispatch_keystroke(keystroke) {
1327                            return true;
1328                        }
1329                    }
1330
1331                    cx.dispatch_event(event, false)
1332                })
1333                .unwrap_or(false)
1334            }));
1335        }
1336
1337        {
1338            let mut app = self.upgrade();
1339            platform_window.on_active_status_change(Box::new(move |is_active| {
1340                app.update(|cx| cx.window_changed_active_status(window_id, is_active))
1341            }));
1342        }
1343
1344        {
1345            let mut app = self.upgrade();
1346            platform_window.on_resize(Box::new(move || {
1347                app.update(|cx| cx.window_was_resized(window_id))
1348            }));
1349        }
1350
1351        {
1352            let mut app = self.upgrade();
1353            platform_window.on_moved(Box::new(move || {
1354                app.update(|cx| cx.window_was_moved(window_id))
1355            }));
1356        }
1357
1358        {
1359            let mut app = self.upgrade();
1360            platform_window.on_fullscreen(Box::new(move |is_fullscreen| {
1361                app.update(|cx| cx.window_was_fullscreen_changed(window_id, is_fullscreen))
1362            }));
1363        }
1364
1365        {
1366            let mut app = self.upgrade();
1367            platform_window.on_close(Box::new(move || {
1368                app.update(|cx| cx.remove_window(window_id));
1369            }));
1370        }
1371
1372        {
1373            let mut app = self.upgrade();
1374            platform_window
1375                .on_appearance_changed(Box::new(move || app.update(|cx| cx.refresh_windows())));
1376        }
1377
1378        platform_window.set_input_handler(Box::new(WindowInputHandler {
1379            app: self.upgrade().0,
1380            window_id,
1381        }));
1382
1383        let mut window = Window::new(window_id, platform_window, self, build_root_view);
1384        let scene = WindowContext::mutable(self, &mut window, window_id)
1385            .build_scene()
1386            .expect("initial scene should not error");
1387        window.platform_window.present_scene(scene);
1388        window
1389    }
1390
1391    pub fn replace_root_view<V, F>(
1392        &mut self,
1393        window_id: usize,
1394        build_root_view: F,
1395    ) -> Option<ViewHandle<V>>
1396    where
1397        V: View,
1398        F: FnOnce(&mut ViewContext<V>) -> V,
1399    {
1400        self.update_window(window_id, |cx| cx.replace_root_view(build_root_view))
1401    }
1402
1403    pub fn add_view<S, F>(&mut self, parent: &AnyViewHandle, build_view: F) -> ViewHandle<S>
1404    where
1405        S: View,
1406        F: FnOnce(&mut ViewContext<S>) -> S,
1407    {
1408        self.update_window(parent.window_id, |cx| {
1409            cx.build_and_insert_view(ParentId::View(parent.view_id), |cx| Some(build_view(cx)))
1410                .unwrap()
1411        })
1412        .unwrap()
1413    }
1414
1415    pub fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
1416        if let Some(view) = self.views.get(&(handle.window_id, handle.view_id)) {
1417            view.as_any().downcast_ref().expect("downcast is type safe")
1418        } else {
1419            panic!("circular view reference for type {}", type_name::<T>());
1420        }
1421    }
1422
1423    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
1424        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
1425            Some(ViewHandle::new(
1426                handle.window_id,
1427                handle.view_id,
1428                &self.ref_counts,
1429            ))
1430        } else {
1431            None
1432        }
1433    }
1434
1435    fn upgrade_any_view_handle(&self, handle: &AnyWeakViewHandle) -> Option<AnyViewHandle> {
1436        if self.ref_counts.lock().is_entity_alive(handle.view_id) {
1437            Some(AnyViewHandle::new(
1438                handle.window_id,
1439                handle.view_id,
1440                handle.view_type,
1441                self.ref_counts.clone(),
1442            ))
1443        } else {
1444            None
1445        }
1446    }
1447
1448    fn remove_dropped_entities(&mut self) {
1449        loop {
1450            let (dropped_models, dropped_views, dropped_element_states) =
1451                self.ref_counts.lock().take_dropped();
1452            if dropped_models.is_empty()
1453                && dropped_views.is_empty()
1454                && dropped_element_states.is_empty()
1455            {
1456                break;
1457            }
1458
1459            for model_id in dropped_models {
1460                self.subscriptions.remove(model_id);
1461                self.observations.remove(model_id);
1462                let mut model = self.models.remove(&model_id).unwrap();
1463                model.release(self);
1464                self.pending_effects
1465                    .push_back(Effect::ModelRelease { model_id, model });
1466            }
1467
1468            for (window_id, view_id) in dropped_views {
1469                self.subscriptions.remove(view_id);
1470                self.observations.remove(view_id);
1471                let mut view = self.views.remove(&(window_id, view_id)).unwrap();
1472                view.release(self);
1473                let change_focus_to = self.windows.get_mut(&window_id).and_then(|window| {
1474                    window
1475                        .invalidation
1476                        .get_or_insert_with(Default::default)
1477                        .removed
1478                        .push(view_id);
1479                    if window.focused_view_id == Some(view_id) {
1480                        Some(window.root_view().id())
1481                    } else {
1482                        None
1483                    }
1484                });
1485                self.parents.remove(&(window_id, view_id));
1486
1487                if let Some(view_id) = change_focus_to {
1488                    self.handle_focus_effect(window_id, Some(view_id));
1489                }
1490
1491                self.pending_effects
1492                    .push_back(Effect::ViewRelease { view_id, view });
1493            }
1494
1495            for key in dropped_element_states {
1496                self.element_states.remove(&key);
1497            }
1498        }
1499    }
1500
1501    fn flush_effects(&mut self) {
1502        self.pending_flushes = self.pending_flushes.saturating_sub(1);
1503        let mut after_window_update_callbacks = Vec::new();
1504
1505        if !self.flushing_effects && self.pending_flushes == 0 {
1506            self.flushing_effects = true;
1507
1508            let mut refreshing = false;
1509            loop {
1510                if let Some(effect) = self.pending_effects.pop_front() {
1511                    match effect {
1512                        Effect::Subscription {
1513                            entity_id,
1514                            subscription_id,
1515                            callback,
1516                        } => self
1517                            .subscriptions
1518                            .add_callback(entity_id, subscription_id, callback),
1519
1520                        Effect::Event { entity_id, payload } => {
1521                            let mut subscriptions = self.subscriptions.clone();
1522                            subscriptions
1523                                .emit(entity_id, |callback| callback(payload.as_ref(), self))
1524                        }
1525
1526                        Effect::GlobalSubscription {
1527                            type_id,
1528                            subscription_id,
1529                            callback,
1530                        } => self.global_subscriptions.add_callback(
1531                            type_id,
1532                            subscription_id,
1533                            callback,
1534                        ),
1535
1536                        Effect::GlobalEvent { payload } => self.emit_global_event(payload),
1537
1538                        Effect::Observation {
1539                            entity_id,
1540                            subscription_id,
1541                            callback,
1542                        } => self
1543                            .observations
1544                            .add_callback(entity_id, subscription_id, callback),
1545
1546                        Effect::ModelNotification { model_id } => {
1547                            let mut observations = self.observations.clone();
1548                            observations.emit(model_id, |callback| callback(self));
1549                        }
1550
1551                        Effect::ViewNotification { window_id, view_id } => {
1552                            self.handle_view_notification_effect(window_id, view_id)
1553                        }
1554
1555                        Effect::GlobalNotification { type_id } => {
1556                            let mut subscriptions = self.global_observations.clone();
1557                            subscriptions.emit(type_id, |callback| {
1558                                callback(self);
1559                                true
1560                            });
1561                        }
1562
1563                        Effect::Deferred {
1564                            callback,
1565                            after_window_update,
1566                        } => {
1567                            if after_window_update {
1568                                after_window_update_callbacks.push(callback);
1569                            } else {
1570                                callback(self)
1571                            }
1572                        }
1573
1574                        Effect::ModelRelease { model_id, model } => {
1575                            self.handle_entity_release_effect(model_id, model.as_any())
1576                        }
1577
1578                        Effect::ViewRelease { view_id, view } => {
1579                            self.handle_entity_release_effect(view_id, view.as_any())
1580                        }
1581
1582                        Effect::Focus { window_id, view_id } => {
1583                            self.handle_focus_effect(window_id, view_id);
1584                        }
1585
1586                        Effect::FocusObservation {
1587                            view_id,
1588                            subscription_id,
1589                            callback,
1590                        } => {
1591                            self.focus_observations.add_callback(
1592                                view_id,
1593                                subscription_id,
1594                                callback,
1595                            );
1596                        }
1597
1598                        Effect::ResizeWindow { window_id } => {
1599                            if let Some(window) = self.windows.get_mut(&window_id) {
1600                                window
1601                                    .invalidation
1602                                    .get_or_insert(WindowInvalidation::default());
1603                            }
1604                            self.handle_window_moved(window_id);
1605                        }
1606
1607                        Effect::MoveWindow { window_id } => {
1608                            self.handle_window_moved(window_id);
1609                        }
1610
1611                        Effect::WindowActivationObservation {
1612                            window_id,
1613                            subscription_id,
1614                            callback,
1615                        } => self.window_activation_observations.add_callback(
1616                            window_id,
1617                            subscription_id,
1618                            callback,
1619                        ),
1620
1621                        Effect::ActivateWindow {
1622                            window_id,
1623                            is_active,
1624                        } => self.handle_window_activation_effect(window_id, is_active),
1625
1626                        Effect::WindowFullscreenObservation {
1627                            window_id,
1628                            subscription_id,
1629                            callback,
1630                        } => self.window_fullscreen_observations.add_callback(
1631                            window_id,
1632                            subscription_id,
1633                            callback,
1634                        ),
1635
1636                        Effect::FullscreenWindow {
1637                            window_id,
1638                            is_fullscreen,
1639                        } => self.handle_fullscreen_effect(window_id, is_fullscreen),
1640
1641                        Effect::WindowBoundsObservation {
1642                            window_id,
1643                            subscription_id,
1644                            callback,
1645                        } => self.window_bounds_observations.add_callback(
1646                            window_id,
1647                            subscription_id,
1648                            callback,
1649                        ),
1650
1651                        Effect::RefreshWindows => {
1652                            refreshing = true;
1653                        }
1654                        Effect::DispatchActionFrom {
1655                            window_id,
1656                            view_id,
1657                            action,
1658                        } => {
1659                            self.handle_dispatch_action_from_effect(
1660                                window_id,
1661                                Some(view_id),
1662                                action.as_ref(),
1663                            );
1664                        }
1665                        Effect::ActionDispatchNotification { action_id } => {
1666                            self.handle_action_dispatch_notification_effect(action_id)
1667                        }
1668                        Effect::WindowShouldCloseSubscription {
1669                            window_id,
1670                            callback,
1671                        } => {
1672                            self.handle_window_should_close_subscription_effect(window_id, callback)
1673                        }
1674                        Effect::Keystroke {
1675                            window_id,
1676                            keystroke,
1677                            handled_by,
1678                            result,
1679                        } => self.handle_keystroke_effect(window_id, keystroke, handled_by, result),
1680                        Effect::ActiveLabeledTasksChanged => {
1681                            self.handle_active_labeled_tasks_changed_effect()
1682                        }
1683                        Effect::ActiveLabeledTasksObservation {
1684                            subscription_id,
1685                            callback,
1686                        } => self.active_labeled_task_observations.add_callback(
1687                            (),
1688                            subscription_id,
1689                            callback,
1690                        ),
1691                    }
1692                    self.pending_notifications.clear();
1693                    self.remove_dropped_entities();
1694                } else {
1695                    self.remove_dropped_entities();
1696
1697                    if refreshing {
1698                        self.perform_window_refresh();
1699                    } else {
1700                        self.update_windows();
1701                    }
1702
1703                    if self.pending_effects.is_empty() {
1704                        for callback in after_window_update_callbacks.drain(..) {
1705                            callback(self);
1706                        }
1707
1708                        if self.pending_effects.is_empty() {
1709                            self.flushing_effects = false;
1710                            self.pending_notifications.clear();
1711                            self.pending_global_notifications.clear();
1712                            break;
1713                        }
1714                    }
1715
1716                    refreshing = false;
1717                }
1718            }
1719        }
1720    }
1721
1722    fn update_windows(&mut self) {
1723        let window_ids = self.windows.keys().cloned().collect::<Vec<_>>();
1724        for window_id in window_ids {
1725            self.update_window(window_id, |cx| {
1726                if let Some(mut invalidation) = cx.window.invalidation.take() {
1727                    let appearance = cx.window.platform_window.appearance();
1728                    cx.invalidate(&mut invalidation, appearance);
1729                    if let Some(scene) = cx.build_scene().log_err() {
1730                        cx.window.platform_window.present_scene(scene);
1731                    }
1732                }
1733            });
1734        }
1735    }
1736
1737    fn window_was_resized(&mut self, window_id: usize) {
1738        self.pending_effects
1739            .push_back(Effect::ResizeWindow { window_id });
1740    }
1741
1742    fn window_was_moved(&mut self, window_id: usize) {
1743        self.pending_effects
1744            .push_back(Effect::MoveWindow { window_id });
1745    }
1746
1747    fn window_was_fullscreen_changed(&mut self, window_id: usize, is_fullscreen: bool) {
1748        self.pending_effects.push_back(Effect::FullscreenWindow {
1749            window_id,
1750            is_fullscreen,
1751        });
1752    }
1753
1754    fn window_changed_active_status(&mut self, window_id: usize, is_active: bool) {
1755        self.pending_effects.push_back(Effect::ActivateWindow {
1756            window_id,
1757            is_active,
1758        });
1759    }
1760
1761    fn keystroke(
1762        &mut self,
1763        window_id: usize,
1764        keystroke: Keystroke,
1765        handled_by: Option<Box<dyn Action>>,
1766        result: MatchResult,
1767    ) {
1768        self.pending_effects.push_back(Effect::Keystroke {
1769            window_id,
1770            keystroke,
1771            handled_by,
1772            result,
1773        });
1774    }
1775
1776    pub fn refresh_windows(&mut self) {
1777        self.pending_effects.push_back(Effect::RefreshWindows);
1778    }
1779
1780    pub fn dispatch_action_at(&mut self, window_id: usize, view_id: usize, action: impl Action) {
1781        self.dispatch_any_action_at(window_id, view_id, Box::new(action));
1782    }
1783
1784    pub fn dispatch_any_action_at(
1785        &mut self,
1786        window_id: usize,
1787        view_id: usize,
1788        action: Box<dyn Action>,
1789    ) {
1790        self.pending_effects.push_back(Effect::DispatchActionFrom {
1791            window_id,
1792            view_id,
1793            action,
1794        });
1795    }
1796
1797    fn perform_window_refresh(&mut self) {
1798        let window_ids = self.windows.keys().cloned().collect::<Vec<_>>();
1799        for window_id in window_ids {
1800            self.update_window(window_id, |cx| {
1801                let mut invalidation = cx.window.invalidation.take().unwrap_or_default();
1802                invalidation
1803                    .updated
1804                    .extend(cx.window.rendered_views.keys().copied());
1805                cx.invalidate(&mut invalidation, cx.window.platform_window.appearance());
1806                cx.refreshing = true;
1807                if let Some(scene) = cx.build_scene().log_err() {
1808                    cx.window.platform_window.present_scene(scene);
1809                }
1810            });
1811        }
1812    }
1813
1814    fn emit_global_event(&mut self, payload: Box<dyn Any>) {
1815        let type_id = (&*payload).type_id();
1816
1817        let mut subscriptions = self.global_subscriptions.clone();
1818        subscriptions.emit(type_id, |callback| {
1819            callback(payload.as_ref(), self);
1820            true //Always alive
1821        });
1822    }
1823
1824    fn handle_view_notification_effect(
1825        &mut self,
1826        observed_window_id: usize,
1827        observed_view_id: usize,
1828    ) {
1829        if self
1830            .views
1831            .contains_key(&(observed_window_id, observed_view_id))
1832        {
1833            if let Some(window) = self.windows.get_mut(&observed_window_id) {
1834                window
1835                    .invalidation
1836                    .get_or_insert_with(Default::default)
1837                    .updated
1838                    .insert(observed_view_id);
1839            }
1840
1841            let mut observations = self.observations.clone();
1842            observations.emit(observed_view_id, |callback| callback(self));
1843        }
1844    }
1845
1846    fn handle_entity_release_effect(&mut self, entity_id: usize, entity: &dyn Any) {
1847        self.release_observations
1848            .clone()
1849            .emit(entity_id, |callback| {
1850                callback(entity, self);
1851                // Release observations happen one time. So clear the callback by returning false
1852                false
1853            })
1854    }
1855
1856    fn handle_fullscreen_effect(&mut self, window_id: usize, is_fullscreen: bool) {
1857        self.update_window(window_id, |cx| {
1858            cx.window.is_fullscreen = is_fullscreen;
1859
1860            let mut fullscreen_observations = cx.window_fullscreen_observations.clone();
1861            fullscreen_observations.emit(window_id, |callback| callback(is_fullscreen, cx));
1862
1863            if let Some(uuid) = cx.window_display_uuid() {
1864                let bounds = cx.window_bounds();
1865                let mut bounds_observations = cx.window_bounds_observations.clone();
1866                bounds_observations.emit(window_id, |callback| callback(bounds, uuid, cx));
1867            }
1868
1869            Some(())
1870        });
1871    }
1872
1873    fn handle_keystroke_effect(
1874        &mut self,
1875        window_id: usize,
1876        keystroke: Keystroke,
1877        handled_by: Option<Box<dyn Action>>,
1878        result: MatchResult,
1879    ) {
1880        self.update_window(window_id, |cx| {
1881            let mut observations = cx.keystroke_observations.clone();
1882            observations.emit(window_id, move |callback| {
1883                callback(&keystroke, &result, handled_by.as_ref(), cx)
1884            });
1885        });
1886    }
1887
1888    fn handle_window_activation_effect(&mut self, window_id: usize, active: bool) {
1889        self.update_window(window_id, |cx| {
1890            if cx.window.is_active == active {
1891                return;
1892            }
1893            cx.window.is_active = active;
1894
1895            if let Some(focused_id) = cx.window.focused_view_id {
1896                for view_id in cx.ancestors(focused_id).collect::<Vec<_>>() {
1897                    cx.update_any_view(view_id, |view, cx| {
1898                        if active {
1899                            view.focus_in(focused_id, cx, view_id);
1900                        } else {
1901                            view.focus_out(focused_id, cx, view_id);
1902                        }
1903                    });
1904                }
1905            }
1906
1907            let mut observations = cx.window_activation_observations.clone();
1908            observations.emit(window_id, |callback| callback(active, cx));
1909        });
1910    }
1911
1912    fn handle_focus_effect(&mut self, window_id: usize, mut focused_id: Option<usize>) {
1913        let mut blurred_id = None;
1914        self.update_window(window_id, |cx| {
1915            if cx.window.focused_view_id == focused_id {
1916                focused_id = None;
1917                return;
1918            }
1919            blurred_id = cx.window.focused_view_id;
1920            cx.window.focused_view_id = focused_id;
1921
1922            let blurred_parents = blurred_id
1923                .map(|blurred_id| cx.ancestors(blurred_id).collect::<Vec<_>>())
1924                .unwrap_or_default();
1925            let focused_parents = focused_id
1926                .map(|focused_id| cx.ancestors(focused_id).collect::<Vec<_>>())
1927                .unwrap_or_default();
1928
1929            if let Some(blurred_id) = blurred_id {
1930                for view_id in blurred_parents.iter().copied() {
1931                    if let Some(mut view) = cx.views.remove(&(window_id, view_id)) {
1932                        view.focus_out(blurred_id, cx, view_id);
1933                        cx.views.insert((window_id, view_id), view);
1934                    }
1935                }
1936
1937                let mut subscriptions = cx.focus_observations.clone();
1938                subscriptions.emit(blurred_id, |callback| callback(false, cx));
1939            }
1940
1941            if let Some(focused_id) = focused_id {
1942                for view_id in focused_parents {
1943                    if let Some(mut view) = cx.views.remove(&(window_id, view_id)) {
1944                        view.focus_in(focused_id, cx, view_id);
1945                        cx.views.insert((window_id, view_id), view);
1946                    }
1947                }
1948
1949                let mut subscriptions = cx.focus_observations.clone();
1950                subscriptions.emit(focused_id, |callback| callback(true, cx));
1951            }
1952        });
1953    }
1954
1955    fn handle_dispatch_action_from_effect(
1956        &mut self,
1957        window_id: usize,
1958        view_id: Option<usize>,
1959        action: &dyn Action,
1960    ) {
1961        self.update_window(window_id, |cx| {
1962            cx.handle_dispatch_action_from_effect(view_id, action)
1963        });
1964    }
1965
1966    fn handle_action_dispatch_notification_effect(&mut self, action_id: TypeId) {
1967        self.action_dispatch_observations
1968            .clone()
1969            .emit((), |callback| {
1970                callback(action_id, self);
1971                true
1972            });
1973    }
1974
1975    fn handle_window_should_close_subscription_effect(
1976        &mut self,
1977        window_id: usize,
1978        mut callback: WindowShouldCloseSubscriptionCallback,
1979    ) {
1980        let mut app = self.upgrade();
1981        if let Some(window) = self.windows.get_mut(&window_id) {
1982            window
1983                .platform_window
1984                .on_should_close(Box::new(move || app.update(|cx| callback(cx))))
1985        }
1986    }
1987
1988    fn handle_window_moved(&mut self, window_id: usize) {
1989        self.update_window(window_id, |cx| {
1990            if let Some(display) = cx.window_display_uuid() {
1991                let bounds = cx.window_bounds();
1992                cx.window_bounds_observations
1993                    .clone()
1994                    .emit(window_id, move |callback| {
1995                        callback(bounds, display, cx);
1996                        true
1997                    });
1998            }
1999        });
2000    }
2001
2002    fn handle_active_labeled_tasks_changed_effect(&mut self) {
2003        self.active_labeled_task_observations
2004            .clone()
2005            .emit((), move |callback| {
2006                callback(self);
2007                true
2008            });
2009    }
2010
2011    pub fn focus(&mut self, window_id: usize, view_id: Option<usize>) {
2012        self.pending_effects
2013            .push_back(Effect::Focus { window_id, view_id });
2014    }
2015
2016    fn spawn_internal<F, Fut, T>(&mut self, task_name: Option<&'static str>, f: F) -> Task<T>
2017    where
2018        F: FnOnce(AsyncAppContext) -> Fut,
2019        Fut: 'static + Future<Output = T>,
2020        T: 'static,
2021    {
2022        let label_id = task_name.map(|task_name| {
2023            let id = post_inc(&mut self.next_labeled_task_id);
2024            self.active_labeled_tasks.insert(id, task_name);
2025            self.pending_effects
2026                .push_back(Effect::ActiveLabeledTasksChanged);
2027            id
2028        });
2029
2030        let future = f(self.to_async());
2031        let cx = self.to_async();
2032        self.foreground.spawn(async move {
2033            let result = future.await;
2034            let mut cx = cx.0.borrow_mut();
2035
2036            if let Some(completed_label_id) = label_id {
2037                cx.active_labeled_tasks.remove(&completed_label_id);
2038                cx.pending_effects
2039                    .push_back(Effect::ActiveLabeledTasksChanged);
2040            }
2041            cx.flush_effects();
2042            result
2043        })
2044    }
2045
2046    pub fn spawn_labeled<F, Fut, T>(&mut self, task_name: &'static str, f: F) -> Task<T>
2047    where
2048        F: FnOnce(AsyncAppContext) -> Fut,
2049        Fut: 'static + Future<Output = T>,
2050        T: 'static,
2051    {
2052        self.spawn_internal(Some(task_name), f)
2053    }
2054
2055    pub fn spawn<F, Fut, T>(&mut self, f: F) -> Task<T>
2056    where
2057        F: FnOnce(AsyncAppContext) -> Fut,
2058        Fut: 'static + Future<Output = T>,
2059        T: 'static,
2060    {
2061        self.spawn_internal(None, f)
2062    }
2063
2064    pub fn to_async(&self) -> AsyncAppContext {
2065        AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
2066    }
2067
2068    pub fn write_to_clipboard(&self, item: ClipboardItem) {
2069        self.platform.write_to_clipboard(item);
2070    }
2071
2072    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
2073        self.platform.read_from_clipboard()
2074    }
2075
2076    #[cfg(any(test, feature = "test-support"))]
2077    pub fn leak_detector(&self) -> Arc<Mutex<LeakDetector>> {
2078        self.ref_counts.lock().leak_detector.clone()
2079    }
2080}
2081
2082impl BorrowAppContext for AppContext {
2083    fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
2084        f(self)
2085    }
2086
2087    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
2088        f(self)
2089    }
2090}
2091
2092#[derive(Debug)]
2093pub enum ParentId {
2094    View(usize),
2095    Root,
2096}
2097
2098#[derive(Default, Clone)]
2099pub struct WindowInvalidation {
2100    pub updated: HashSet<usize>,
2101    pub removed: Vec<usize>,
2102}
2103
2104pub enum Effect {
2105    Subscription {
2106        entity_id: usize,
2107        subscription_id: usize,
2108        callback: SubscriptionCallback,
2109    },
2110    Event {
2111        entity_id: usize,
2112        payload: Box<dyn Any>,
2113    },
2114    GlobalSubscription {
2115        type_id: TypeId,
2116        subscription_id: usize,
2117        callback: GlobalSubscriptionCallback,
2118    },
2119    GlobalEvent {
2120        payload: Box<dyn Any>,
2121    },
2122    Observation {
2123        entity_id: usize,
2124        subscription_id: usize,
2125        callback: ObservationCallback,
2126    },
2127    ModelNotification {
2128        model_id: usize,
2129    },
2130    ViewNotification {
2131        window_id: usize,
2132        view_id: usize,
2133    },
2134    Deferred {
2135        callback: Box<dyn FnOnce(&mut AppContext)>,
2136        after_window_update: bool,
2137    },
2138    GlobalNotification {
2139        type_id: TypeId,
2140    },
2141    ModelRelease {
2142        model_id: usize,
2143        model: Box<dyn AnyModel>,
2144    },
2145    ViewRelease {
2146        view_id: usize,
2147        view: Box<dyn AnyView>,
2148    },
2149    Focus {
2150        window_id: usize,
2151        view_id: Option<usize>,
2152    },
2153    FocusObservation {
2154        view_id: usize,
2155        subscription_id: usize,
2156        callback: FocusObservationCallback,
2157    },
2158    ResizeWindow {
2159        window_id: usize,
2160    },
2161    MoveWindow {
2162        window_id: usize,
2163    },
2164    ActivateWindow {
2165        window_id: usize,
2166        is_active: bool,
2167    },
2168    WindowActivationObservation {
2169        window_id: usize,
2170        subscription_id: usize,
2171        callback: WindowActivationCallback,
2172    },
2173    FullscreenWindow {
2174        window_id: usize,
2175        is_fullscreen: bool,
2176    },
2177    WindowFullscreenObservation {
2178        window_id: usize,
2179        subscription_id: usize,
2180        callback: WindowFullscreenCallback,
2181    },
2182    WindowBoundsObservation {
2183        window_id: usize,
2184        subscription_id: usize,
2185        callback: WindowBoundsCallback,
2186    },
2187    Keystroke {
2188        window_id: usize,
2189        keystroke: Keystroke,
2190        handled_by: Option<Box<dyn Action>>,
2191        result: MatchResult,
2192    },
2193    RefreshWindows,
2194    DispatchActionFrom {
2195        window_id: usize,
2196        view_id: usize,
2197        action: Box<dyn Action>,
2198    },
2199    ActionDispatchNotification {
2200        action_id: TypeId,
2201    },
2202    WindowShouldCloseSubscription {
2203        window_id: usize,
2204        callback: WindowShouldCloseSubscriptionCallback,
2205    },
2206    ActiveLabeledTasksChanged,
2207    ActiveLabeledTasksObservation {
2208        subscription_id: usize,
2209        callback: ActiveLabeledTasksCallback,
2210    },
2211}
2212
2213impl Debug for Effect {
2214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2215        match self {
2216            Effect::Subscription {
2217                entity_id,
2218                subscription_id,
2219                ..
2220            } => f
2221                .debug_struct("Effect::Subscribe")
2222                .field("entity_id", entity_id)
2223                .field("subscription_id", subscription_id)
2224                .finish(),
2225            Effect::Event { entity_id, .. } => f
2226                .debug_struct("Effect::Event")
2227                .field("entity_id", entity_id)
2228                .finish(),
2229            Effect::GlobalSubscription {
2230                type_id,
2231                subscription_id,
2232                ..
2233            } => f
2234                .debug_struct("Effect::Subscribe")
2235                .field("type_id", type_id)
2236                .field("subscription_id", subscription_id)
2237                .finish(),
2238            Effect::GlobalEvent { payload, .. } => f
2239                .debug_struct("Effect::GlobalEvent")
2240                .field("type_id", &(&*payload).type_id())
2241                .finish(),
2242            Effect::Observation {
2243                entity_id,
2244                subscription_id,
2245                ..
2246            } => f
2247                .debug_struct("Effect::Observation")
2248                .field("entity_id", entity_id)
2249                .field("subscription_id", subscription_id)
2250                .finish(),
2251            Effect::ModelNotification { model_id } => f
2252                .debug_struct("Effect::ModelNotification")
2253                .field("model_id", model_id)
2254                .finish(),
2255            Effect::ViewNotification { window_id, view_id } => f
2256                .debug_struct("Effect::ViewNotification")
2257                .field("window_id", window_id)
2258                .field("view_id", view_id)
2259                .finish(),
2260            Effect::GlobalNotification { type_id } => f
2261                .debug_struct("Effect::GlobalNotification")
2262                .field("type_id", type_id)
2263                .finish(),
2264            Effect::Deferred { .. } => f.debug_struct("Effect::Deferred").finish(),
2265            Effect::ModelRelease { model_id, .. } => f
2266                .debug_struct("Effect::ModelRelease")
2267                .field("model_id", model_id)
2268                .finish(),
2269            Effect::ViewRelease { view_id, .. } => f
2270                .debug_struct("Effect::ViewRelease")
2271                .field("view_id", view_id)
2272                .finish(),
2273            Effect::Focus { window_id, view_id } => f
2274                .debug_struct("Effect::Focus")
2275                .field("window_id", window_id)
2276                .field("view_id", view_id)
2277                .finish(),
2278            Effect::FocusObservation {
2279                view_id,
2280                subscription_id,
2281                ..
2282            } => f
2283                .debug_struct("Effect::FocusObservation")
2284                .field("view_id", view_id)
2285                .field("subscription_id", subscription_id)
2286                .finish(),
2287            Effect::DispatchActionFrom {
2288                window_id, view_id, ..
2289            } => f
2290                .debug_struct("Effect::DispatchActionFrom")
2291                .field("window_id", window_id)
2292                .field("view_id", view_id)
2293                .finish(),
2294            Effect::ActionDispatchNotification { action_id, .. } => f
2295                .debug_struct("Effect::ActionDispatchNotification")
2296                .field("action_id", action_id)
2297                .finish(),
2298            Effect::ResizeWindow { window_id } => f
2299                .debug_struct("Effect::RefreshWindow")
2300                .field("window_id", window_id)
2301                .finish(),
2302            Effect::MoveWindow { window_id } => f
2303                .debug_struct("Effect::MoveWindow")
2304                .field("window_id", window_id)
2305                .finish(),
2306            Effect::WindowActivationObservation {
2307                window_id,
2308                subscription_id,
2309                ..
2310            } => f
2311                .debug_struct("Effect::WindowActivationObservation")
2312                .field("window_id", window_id)
2313                .field("subscription_id", subscription_id)
2314                .finish(),
2315            Effect::ActivateWindow {
2316                window_id,
2317                is_active,
2318            } => f
2319                .debug_struct("Effect::ActivateWindow")
2320                .field("window_id", window_id)
2321                .field("is_active", is_active)
2322                .finish(),
2323            Effect::FullscreenWindow {
2324                window_id,
2325                is_fullscreen,
2326            } => f
2327                .debug_struct("Effect::FullscreenWindow")
2328                .field("window_id", window_id)
2329                .field("is_fullscreen", is_fullscreen)
2330                .finish(),
2331            Effect::WindowFullscreenObservation {
2332                window_id,
2333                subscription_id,
2334                callback: _,
2335            } => f
2336                .debug_struct("Effect::WindowFullscreenObservation")
2337                .field("window_id", window_id)
2338                .field("subscription_id", subscription_id)
2339                .finish(),
2340
2341            Effect::WindowBoundsObservation {
2342                window_id,
2343                subscription_id,
2344                callback: _,
2345            } => f
2346                .debug_struct("Effect::WindowBoundsObservation")
2347                .field("window_id", window_id)
2348                .field("subscription_id", subscription_id)
2349                .finish(),
2350            Effect::RefreshWindows => f.debug_struct("Effect::FullViewRefresh").finish(),
2351            Effect::WindowShouldCloseSubscription { window_id, .. } => f
2352                .debug_struct("Effect::WindowShouldCloseSubscription")
2353                .field("window_id", window_id)
2354                .finish(),
2355            Effect::Keystroke {
2356                window_id,
2357                keystroke,
2358                handled_by,
2359                result,
2360            } => f
2361                .debug_struct("Effect::Keystroke")
2362                .field("window_id", window_id)
2363                .field("keystroke", keystroke)
2364                .field(
2365                    "keystroke",
2366                    &handled_by.as_ref().map(|handled_by| handled_by.name()),
2367                )
2368                .field("result", result)
2369                .finish(),
2370            Effect::ActiveLabeledTasksChanged => {
2371                f.debug_struct("Effect::ActiveLabeledTasksChanged").finish()
2372            }
2373            Effect::ActiveLabeledTasksObservation {
2374                subscription_id,
2375                callback: _,
2376            } => f
2377                .debug_struct("Effect::ActiveLabeledTasksObservation")
2378                .field("subscription_id", subscription_id)
2379                .finish(),
2380        }
2381    }
2382}
2383
2384pub trait AnyModel {
2385    fn as_any(&self) -> &dyn Any;
2386    fn as_any_mut(&mut self) -> &mut dyn Any;
2387    fn release(&mut self, cx: &mut AppContext);
2388    fn app_will_quit(
2389        &mut self,
2390        cx: &mut AppContext,
2391    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2392}
2393
2394impl<T> AnyModel for T
2395where
2396    T: Entity,
2397{
2398    fn as_any(&self) -> &dyn Any {
2399        self
2400    }
2401
2402    fn as_any_mut(&mut self) -> &mut dyn Any {
2403        self
2404    }
2405
2406    fn release(&mut self, cx: &mut AppContext) {
2407        self.release(cx);
2408    }
2409
2410    fn app_will_quit(
2411        &mut self,
2412        cx: &mut AppContext,
2413    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2414        self.app_will_quit(cx)
2415    }
2416}
2417
2418pub trait AnyView {
2419    fn as_any(&self) -> &dyn Any;
2420    fn as_any_mut(&mut self) -> &mut dyn Any;
2421    fn release(&mut self, cx: &mut AppContext);
2422    fn app_will_quit(
2423        &mut self,
2424        cx: &mut AppContext,
2425    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>>;
2426    fn ui_name(&self) -> &'static str;
2427    fn render(&mut self, cx: &mut WindowContext, view_id: usize) -> Box<dyn AnyRootElement>;
2428    fn focus_in<'a, 'b>(&mut self, focused_id: usize, cx: &mut WindowContext<'a>, view_id: usize);
2429    fn focus_out(&mut self, focused_id: usize, cx: &mut WindowContext, view_id: usize);
2430    fn key_down(&mut self, event: &KeyDownEvent, cx: &mut WindowContext, view_id: usize) -> bool;
2431    fn key_up(&mut self, event: &KeyUpEvent, cx: &mut WindowContext, view_id: usize) -> bool;
2432    fn modifiers_changed(
2433        &mut self,
2434        event: &ModifiersChangedEvent,
2435        cx: &mut WindowContext,
2436        view_id: usize,
2437    ) -> bool;
2438    fn keymap_context(&self, cx: &AppContext) -> KeymapContext;
2439    fn debug_json(&self, cx: &WindowContext) -> serde_json::Value;
2440
2441    fn text_for_range(&self, range: Range<usize>, cx: &WindowContext) -> Option<String>;
2442    fn selected_text_range(&self, cx: &WindowContext) -> Option<Range<usize>>;
2443    fn marked_text_range(&self, cx: &WindowContext) -> Option<Range<usize>>;
2444    fn unmark_text(&mut self, cx: &mut WindowContext, view_id: usize);
2445    fn replace_text_in_range(
2446        &mut self,
2447        range: Option<Range<usize>>,
2448        text: &str,
2449        cx: &mut WindowContext,
2450        view_id: usize,
2451    );
2452    fn replace_and_mark_text_in_range(
2453        &mut self,
2454        range: Option<Range<usize>>,
2455        new_text: &str,
2456        new_selected_range: Option<Range<usize>>,
2457        cx: &mut WindowContext,
2458        view_id: usize,
2459    );
2460    fn any_handle(&self, window_id: usize, view_id: usize, cx: &AppContext) -> AnyViewHandle {
2461        AnyViewHandle::new(
2462            window_id,
2463            view_id,
2464            self.as_any().type_id(),
2465            cx.ref_counts.clone(),
2466        )
2467    }
2468}
2469
2470impl<V> AnyView for V
2471where
2472    V: View,
2473{
2474    fn as_any(&self) -> &dyn Any {
2475        self
2476    }
2477
2478    fn as_any_mut(&mut self) -> &mut dyn Any {
2479        self
2480    }
2481
2482    fn release(&mut self, cx: &mut AppContext) {
2483        self.release(cx);
2484    }
2485
2486    fn app_will_quit(
2487        &mut self,
2488        cx: &mut AppContext,
2489    ) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
2490        self.app_will_quit(cx)
2491    }
2492
2493    fn ui_name(&self) -> &'static str {
2494        V::ui_name()
2495    }
2496
2497    fn render(&mut self, cx: &mut WindowContext, view_id: usize) -> Box<dyn AnyRootElement> {
2498        let mut view_context = ViewContext::mutable(cx, view_id);
2499        let element = V::render(self, &mut view_context);
2500        let view = WeakViewHandle::new(cx.window_id, view_id);
2501        Box::new(RootElement::new(element, view))
2502    }
2503
2504    fn focus_in(&mut self, focused_id: usize, cx: &mut WindowContext, view_id: usize) {
2505        let mut cx = ViewContext::mutable(cx, view_id);
2506        let focused_view_handle: AnyViewHandle = if view_id == focused_id {
2507            cx.handle().into_any()
2508        } else {
2509            let focused_type = cx
2510                .views
2511                .get(&(cx.window_id, focused_id))
2512                .unwrap()
2513                .as_any()
2514                .type_id();
2515            AnyViewHandle::new(
2516                cx.window_id,
2517                focused_id,
2518                focused_type,
2519                cx.ref_counts.clone(),
2520            )
2521        };
2522        View::focus_in(self, focused_view_handle, &mut cx);
2523    }
2524
2525    fn focus_out(&mut self, blurred_id: usize, cx: &mut WindowContext, view_id: usize) {
2526        let mut cx = ViewContext::mutable(cx, view_id);
2527        let blurred_view_handle: AnyViewHandle = if view_id == blurred_id {
2528            cx.handle().into_any()
2529        } else {
2530            let blurred_type = cx
2531                .views
2532                .get(&(cx.window_id, blurred_id))
2533                .unwrap()
2534                .as_any()
2535                .type_id();
2536            AnyViewHandle::new(
2537                cx.window_id,
2538                blurred_id,
2539                blurred_type,
2540                cx.ref_counts.clone(),
2541            )
2542        };
2543        View::focus_out(self, blurred_view_handle, &mut cx);
2544    }
2545
2546    fn key_down(&mut self, event: &KeyDownEvent, cx: &mut WindowContext, view_id: usize) -> bool {
2547        let mut cx = ViewContext::mutable(cx, view_id);
2548        View::key_down(self, event, &mut cx)
2549    }
2550
2551    fn key_up(&mut self, event: &KeyUpEvent, cx: &mut WindowContext, view_id: usize) -> bool {
2552        let mut cx = ViewContext::mutable(cx, view_id);
2553        View::key_up(self, event, &mut cx)
2554    }
2555
2556    fn modifiers_changed(
2557        &mut self,
2558        event: &ModifiersChangedEvent,
2559        cx: &mut WindowContext,
2560        view_id: usize,
2561    ) -> bool {
2562        let mut cx = ViewContext::mutable(cx, view_id);
2563        View::modifiers_changed(self, event, &mut cx)
2564    }
2565
2566    fn keymap_context(&self, cx: &AppContext) -> KeymapContext {
2567        View::keymap_context(self, cx)
2568    }
2569
2570    fn debug_json(&self, cx: &WindowContext) -> serde_json::Value {
2571        View::debug_json(self, cx)
2572    }
2573
2574    fn text_for_range(&self, range: Range<usize>, cx: &WindowContext) -> Option<String> {
2575        View::text_for_range(self, range, cx)
2576    }
2577
2578    fn selected_text_range(&self, cx: &WindowContext) -> Option<Range<usize>> {
2579        View::selected_text_range(self, cx)
2580    }
2581
2582    fn marked_text_range(&self, cx: &WindowContext) -> Option<Range<usize>> {
2583        View::marked_text_range(self, cx)
2584    }
2585
2586    fn unmark_text(&mut self, cx: &mut WindowContext, view_id: usize) {
2587        let mut cx = ViewContext::mutable(cx, view_id);
2588        View::unmark_text(self, &mut cx)
2589    }
2590
2591    fn replace_text_in_range(
2592        &mut self,
2593        range: Option<Range<usize>>,
2594        text: &str,
2595        cx: &mut WindowContext,
2596        view_id: usize,
2597    ) {
2598        let mut cx = ViewContext::mutable(cx, view_id);
2599        View::replace_text_in_range(self, range, text, &mut cx)
2600    }
2601
2602    fn replace_and_mark_text_in_range(
2603        &mut self,
2604        range: Option<Range<usize>>,
2605        new_text: &str,
2606        new_selected_range: Option<Range<usize>>,
2607        cx: &mut WindowContext,
2608        view_id: usize,
2609    ) {
2610        let mut cx = ViewContext::mutable(cx, view_id);
2611        View::replace_and_mark_text_in_range(self, range, new_text, new_selected_range, &mut cx)
2612    }
2613}
2614
2615pub struct ModelContext<'a, T: ?Sized> {
2616    app: &'a mut AppContext,
2617    model_id: usize,
2618    model_type: PhantomData<T>,
2619    halt_stream: bool,
2620}
2621
2622impl<'a, T: Entity> ModelContext<'a, T> {
2623    fn new(app: &'a mut AppContext, model_id: usize) -> Self {
2624        Self {
2625            app,
2626            model_id,
2627            model_type: PhantomData,
2628            halt_stream: false,
2629        }
2630    }
2631
2632    pub fn background(&self) -> &Arc<executor::Background> {
2633        &self.app.background
2634    }
2635
2636    pub fn halt_stream(&mut self) {
2637        self.halt_stream = true;
2638    }
2639
2640    pub fn model_id(&self) -> usize {
2641        self.model_id
2642    }
2643
2644    pub fn add_model<S, F>(&mut self, build_model: F) -> ModelHandle<S>
2645    where
2646        S: Entity,
2647        F: FnOnce(&mut ModelContext<S>) -> S,
2648    {
2649        self.app.add_model(build_model)
2650    }
2651
2652    pub fn emit(&mut self, payload: T::Event) {
2653        self.app.pending_effects.push_back(Effect::Event {
2654            entity_id: self.model_id,
2655            payload: Box::new(payload),
2656        });
2657    }
2658
2659    pub fn notify(&mut self) {
2660        self.app.notify_model(self.model_id);
2661    }
2662
2663    pub fn subscribe<S: Entity, F>(
2664        &mut self,
2665        handle: &ModelHandle<S>,
2666        mut callback: F,
2667    ) -> Subscription
2668    where
2669        S::Event: 'static,
2670        F: 'static + FnMut(&mut T, ModelHandle<S>, &S::Event, &mut ModelContext<T>),
2671    {
2672        let subscriber = self.weak_handle();
2673        self.app
2674            .subscribe_internal(handle, move |emitter, event, cx| {
2675                if let Some(subscriber) = subscriber.upgrade(cx) {
2676                    subscriber.update(cx, |subscriber, cx| {
2677                        callback(subscriber, emitter, event, cx);
2678                    });
2679                    true
2680                } else {
2681                    false
2682                }
2683            })
2684    }
2685
2686    pub fn observe<S, F>(&mut self, handle: &ModelHandle<S>, mut callback: F) -> Subscription
2687    where
2688        S: Entity,
2689        F: 'static + FnMut(&mut T, ModelHandle<S>, &mut ModelContext<T>),
2690    {
2691        let observer = self.weak_handle();
2692        self.app.observe_internal(handle, move |observed, cx| {
2693            if let Some(observer) = observer.upgrade(cx) {
2694                observer.update(cx, |observer, cx| {
2695                    callback(observer, observed, cx);
2696                });
2697                true
2698            } else {
2699                false
2700            }
2701        })
2702    }
2703
2704    pub fn observe_global<G, F>(&mut self, mut callback: F) -> Subscription
2705    where
2706        G: Any,
2707        F: 'static + FnMut(&mut T, &mut ModelContext<T>),
2708    {
2709        let observer = self.weak_handle();
2710        self.app.observe_global::<G, _>(move |cx| {
2711            if let Some(observer) = observer.upgrade(cx) {
2712                observer.update(cx, |observer, cx| callback(observer, cx));
2713            }
2714        })
2715    }
2716
2717    pub fn observe_release<S, F>(
2718        &mut self,
2719        handle: &ModelHandle<S>,
2720        mut callback: F,
2721    ) -> Subscription
2722    where
2723        S: Entity,
2724        F: 'static + FnMut(&mut T, &S, &mut ModelContext<T>),
2725    {
2726        let observer = self.weak_handle();
2727        self.app.observe_release(handle, move |released, cx| {
2728            if let Some(observer) = observer.upgrade(cx) {
2729                observer.update(cx, |observer, cx| {
2730                    callback(observer, released, cx);
2731                });
2732            }
2733        })
2734    }
2735
2736    pub fn handle(&self) -> ModelHandle<T> {
2737        ModelHandle::new(self.model_id, &self.app.ref_counts)
2738    }
2739
2740    pub fn weak_handle(&self) -> WeakModelHandle<T> {
2741        WeakModelHandle::new(self.model_id)
2742    }
2743
2744    pub fn spawn<F, Fut, S>(&mut self, f: F) -> Task<S>
2745    where
2746        F: FnOnce(ModelHandle<T>, AsyncAppContext) -> Fut,
2747        Fut: 'static + Future<Output = S>,
2748        S: 'static,
2749    {
2750        let handle = self.handle();
2751        self.app.spawn(|cx| f(handle, cx))
2752    }
2753
2754    pub fn spawn_weak<F, Fut, S>(&mut self, f: F) -> Task<S>
2755    where
2756        F: FnOnce(WeakModelHandle<T>, AsyncAppContext) -> Fut,
2757        Fut: 'static + Future<Output = S>,
2758        S: 'static,
2759    {
2760        let handle = self.weak_handle();
2761        self.app.spawn(|cx| f(handle, cx))
2762    }
2763}
2764
2765impl<M> AsRef<AppContext> for ModelContext<'_, M> {
2766    fn as_ref(&self) -> &AppContext {
2767        &self.app
2768    }
2769}
2770
2771impl<M> AsMut<AppContext> for ModelContext<'_, M> {
2772    fn as_mut(&mut self) -> &mut AppContext {
2773        self.app
2774    }
2775}
2776
2777impl<M> BorrowAppContext for ModelContext<'_, M> {
2778    fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
2779        self.app.read_with(f)
2780    }
2781
2782    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
2783        self.app.update(f)
2784    }
2785}
2786
2787impl<M> Deref for ModelContext<'_, M> {
2788    type Target = AppContext;
2789
2790    fn deref(&self) -> &Self::Target {
2791        self.app
2792    }
2793}
2794
2795impl<M> DerefMut for ModelContext<'_, M> {
2796    fn deref_mut(&mut self) -> &mut Self::Target {
2797        &mut self.app
2798    }
2799}
2800
2801pub struct ViewContext<'a, 'b, T: ?Sized> {
2802    window_context: Reference<'b, WindowContext<'a>>,
2803    view_id: usize,
2804    view_type: PhantomData<T>,
2805}
2806
2807impl<'a, 'b, T: View> Deref for ViewContext<'a, 'b, T> {
2808    type Target = WindowContext<'a>;
2809
2810    fn deref(&self) -> &Self::Target {
2811        &self.window_context
2812    }
2813}
2814
2815impl<T: View> DerefMut for ViewContext<'_, '_, T> {
2816    fn deref_mut(&mut self) -> &mut Self::Target {
2817        &mut self.window_context
2818    }
2819}
2820
2821impl<'a, 'b, V: View> ViewContext<'a, 'b, V> {
2822    pub(crate) fn mutable(window_context: &'b mut WindowContext<'a>, view_id: usize) -> Self {
2823        Self {
2824            window_context: Reference::Mutable(window_context),
2825            view_id,
2826            view_type: PhantomData,
2827        }
2828    }
2829
2830    pub(crate) fn immutable(window_context: &'b WindowContext<'a>, view_id: usize) -> Self {
2831        Self {
2832            window_context: Reference::Immutable(window_context),
2833            view_id,
2834            view_type: PhantomData,
2835        }
2836    }
2837
2838    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2839        &mut self.window_context
2840    }
2841
2842    pub fn handle(&self) -> ViewHandle<V> {
2843        ViewHandle::new(
2844            self.window_id,
2845            self.view_id,
2846            &self.window_context.ref_counts,
2847        )
2848    }
2849
2850    pub fn weak_handle(&self) -> WeakViewHandle<V> {
2851        WeakViewHandle::new(self.window_id, self.view_id)
2852    }
2853
2854    pub fn parent(&self) -> Option<usize> {
2855        self.window_context.parent(self.view_id)
2856    }
2857
2858    pub fn window_id(&self) -> usize {
2859        self.window_id
2860    }
2861
2862    pub fn view_id(&self) -> usize {
2863        self.view_id
2864    }
2865
2866    pub fn foreground(&self) -> &Rc<executor::Foreground> {
2867        self.window_context.foreground()
2868    }
2869
2870    pub fn background_executor(&self) -> &Arc<executor::Background> {
2871        &self.window_context.background
2872    }
2873
2874    pub fn platform(&self) -> &Arc<dyn Platform> {
2875        self.window_context.platform()
2876    }
2877
2878    pub fn prompt_for_paths(
2879        &self,
2880        options: PathPromptOptions,
2881    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2882        self.window_context.prompt_for_paths(options)
2883    }
2884
2885    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
2886        self.window_context.prompt_for_new_path(directory)
2887    }
2888
2889    pub fn reveal_path(&self, path: &Path) {
2890        self.window_context.reveal_path(path)
2891    }
2892
2893    pub fn focus(&mut self, handle: &AnyViewHandle) {
2894        self.window_context
2895            .focus(handle.window_id, Some(handle.view_id));
2896    }
2897
2898    pub fn focus_self(&mut self) {
2899        let window_id = self.window_id;
2900        let view_id = self.view_id;
2901        self.window_context.focus(window_id, Some(view_id));
2902    }
2903
2904    pub fn is_self_focused(&self) -> bool {
2905        self.window.focused_view_id == Some(self.view_id)
2906    }
2907
2908    pub fn is_parent_view_focused(&self) -> bool {
2909        if let Some(parent_view_id) = self.ancestors(self.view_id).next().clone() {
2910            self.focused_view_id() == Some(parent_view_id)
2911        } else {
2912            false
2913        }
2914    }
2915
2916    pub fn focus_parent_view(&mut self) {
2917        let next = self.ancestors(self.view_id).next().clone();
2918        if let Some(parent_view_id) = next {
2919            let window_id = self.window_id;
2920            self.window_context.focus(window_id, Some(parent_view_id));
2921        }
2922    }
2923
2924    pub fn is_child(&self, view: impl Into<AnyViewHandle>) -> bool {
2925        let view = view.into();
2926        if self.window_id != view.window_id {
2927            return false;
2928        }
2929        self.ancestors(view.view_id)
2930            .skip(1) // Skip self id
2931            .any(|parent| parent == self.view_id)
2932    }
2933
2934    pub fn blur(&mut self) {
2935        let window_id = self.window_id;
2936        self.window_context.focus(window_id, None);
2937    }
2938
2939    pub fn on_window_should_close<F>(&mut self, mut callback: F)
2940    where
2941        F: 'static + FnMut(&mut V, &mut ViewContext<V>) -> bool,
2942    {
2943        let window_id = self.window_id;
2944        let view = self.weak_handle();
2945        self.pending_effects
2946            .push_back(Effect::WindowShouldCloseSubscription {
2947                window_id,
2948                callback: Box::new(move |cx| {
2949                    cx.update_window(window_id, |cx| {
2950                        if let Some(view) = view.upgrade(cx) {
2951                            view.update(cx, |view, cx| callback(view, cx))
2952                        } else {
2953                            true
2954                        }
2955                    })
2956                    .unwrap_or(true)
2957                }),
2958            });
2959    }
2960
2961    pub fn add_view<S, F>(&mut self, build_view: F) -> ViewHandle<S>
2962    where
2963        S: View,
2964        F: FnOnce(&mut ViewContext<S>) -> S,
2965    {
2966        self.window_context
2967            .build_and_insert_view(ParentId::View(self.view_id), |cx| Some(build_view(cx)))
2968            .unwrap()
2969    }
2970
2971    pub fn add_option_view<S, F>(&mut self, build_view: F) -> Option<ViewHandle<S>>
2972    where
2973        S: View,
2974        F: FnOnce(&mut ViewContext<S>) -> Option<S>,
2975    {
2976        self.window_context
2977            .build_and_insert_view(ParentId::View(self.view_id), build_view)
2978    }
2979
2980    pub fn reparent(&mut self, view_handle: &AnyViewHandle) {
2981        if self.window_id != view_handle.window_id {
2982            panic!("Can't reparent view to a view from a different window");
2983        }
2984        self.parents
2985            .remove(&(view_handle.window_id, view_handle.view_id));
2986        let new_parent_id = self.view_id;
2987        self.parents.insert(
2988            (view_handle.window_id, view_handle.view_id),
2989            ParentId::View(new_parent_id),
2990        );
2991    }
2992
2993    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
2994    where
2995        E: Entity,
2996        E::Event: 'static,
2997        H: Handle<E>,
2998        F: 'static + FnMut(&mut V, H, &E::Event, &mut ViewContext<V>),
2999    {
3000        let subscriber = self.weak_handle();
3001        self.window_context
3002            .subscribe_internal(handle, move |emitter, event, cx| {
3003                if let Some(subscriber) = subscriber.upgrade(cx) {
3004                    subscriber.update(cx, |subscriber, cx| {
3005                        callback(subscriber, emitter, event, cx);
3006                    });
3007                    true
3008                } else {
3009                    false
3010                }
3011            })
3012    }
3013
3014    pub fn observe<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3015    where
3016        E: Entity,
3017        H: Handle<E>,
3018        F: 'static + FnMut(&mut V, H, &mut ViewContext<V>),
3019    {
3020        let window_id = self.window_id;
3021        let observer = self.weak_handle();
3022        self.window_context
3023            .observe_internal(handle, move |observed, cx| {
3024                cx.update_window(window_id, |cx| {
3025                    if let Some(observer) = observer.upgrade(cx) {
3026                        observer.update(cx, |observer, cx| {
3027                            callback(observer, observed, cx);
3028                        });
3029                        true
3030                    } else {
3031                        false
3032                    }
3033                })
3034                .unwrap_or(false)
3035            })
3036    }
3037
3038    pub fn observe_global<G, F>(&mut self, mut callback: F) -> Subscription
3039    where
3040        G: Any,
3041        F: 'static + FnMut(&mut V, &mut ViewContext<V>),
3042    {
3043        let window_id = self.window_id;
3044        let observer = self.weak_handle();
3045        self.window_context.observe_global::<G, _>(move |cx| {
3046            cx.update_window(window_id, |cx| {
3047                if let Some(observer) = observer.upgrade(cx) {
3048                    observer.update(cx, |observer, cx| callback(observer, cx));
3049                }
3050            });
3051        })
3052    }
3053
3054    pub fn observe_focus<F, W>(&mut self, handle: &ViewHandle<W>, mut callback: F) -> Subscription
3055    where
3056        F: 'static + FnMut(&mut V, ViewHandle<W>, bool, &mut ViewContext<V>),
3057        W: View,
3058    {
3059        let observer = self.weak_handle();
3060        self.window_context
3061            .observe_focus(handle, move |observed, focused, cx| {
3062                if let Some(observer) = observer.upgrade(cx) {
3063                    observer.update(cx, |observer, cx| {
3064                        callback(observer, observed, focused, cx);
3065                    });
3066                    true
3067                } else {
3068                    false
3069                }
3070            })
3071    }
3072
3073    pub fn observe_release<E, F, H>(&mut self, handle: &H, mut callback: F) -> Subscription
3074    where
3075        E: Entity,
3076        H: Handle<E>,
3077        F: 'static + FnMut(&mut V, &E, &mut ViewContext<V>),
3078    {
3079        let window_id = self.window_id;
3080        let observer = self.weak_handle();
3081        self.window_context
3082            .observe_release(handle, move |released, cx| {
3083                cx.update_window(window_id, |cx| {
3084                    if let Some(observer) = observer.upgrade(cx) {
3085                        observer.update(cx, |observer, cx| {
3086                            callback(observer, released, cx);
3087                        });
3088                    }
3089                });
3090            })
3091    }
3092
3093    pub fn observe_actions<F>(&mut self, mut callback: F) -> Subscription
3094    where
3095        F: 'static + FnMut(&mut V, TypeId, &mut ViewContext<V>),
3096    {
3097        let window_id = self.window_id;
3098        let observer = self.weak_handle();
3099        self.window_context.observe_actions(move |action_id, cx| {
3100            cx.update_window(window_id, |cx| {
3101                if let Some(observer) = observer.upgrade(cx) {
3102                    observer.update(cx, |observer, cx| {
3103                        callback(observer, action_id, cx);
3104                    });
3105                }
3106            });
3107        })
3108    }
3109
3110    pub fn observe_window_activation<F>(&mut self, mut callback: F) -> Subscription
3111    where
3112        F: 'static + FnMut(&mut V, bool, &mut ViewContext<V>),
3113    {
3114        let observer = self.weak_handle();
3115        self.window_context
3116            .observe_window_activation(move |active, cx| {
3117                if let Some(observer) = observer.upgrade(cx) {
3118                    observer.update(cx, |observer, cx| {
3119                        callback(observer, active, cx);
3120                    });
3121                    true
3122                } else {
3123                    false
3124                }
3125            })
3126    }
3127
3128    pub fn observe_fullscreen<F>(&mut self, mut callback: F) -> Subscription
3129    where
3130        F: 'static + FnMut(&mut V, bool, &mut ViewContext<V>),
3131    {
3132        let observer = self.weak_handle();
3133        self.window_context.observe_fullscreen(move |active, cx| {
3134            if let Some(observer) = observer.upgrade(cx) {
3135                observer.update(cx, |observer, cx| {
3136                    callback(observer, active, cx);
3137                });
3138                true
3139            } else {
3140                false
3141            }
3142        })
3143    }
3144
3145    pub fn observe_keystrokes<F>(&mut self, mut callback: F) -> Subscription
3146    where
3147        F: 'static
3148            + FnMut(
3149                &mut V,
3150                &Keystroke,
3151                Option<&Box<dyn Action>>,
3152                &MatchResult,
3153                &mut ViewContext<V>,
3154            ) -> bool,
3155    {
3156        let observer = self.weak_handle();
3157        self.window_context
3158            .observe_keystrokes(move |keystroke, result, handled_by, cx| {
3159                if let Some(observer) = observer.upgrade(cx) {
3160                    observer.update(cx, |observer, cx| {
3161                        callback(observer, keystroke, handled_by, result, cx);
3162                    });
3163                    true
3164                } else {
3165                    false
3166                }
3167            })
3168    }
3169
3170    pub fn observe_window_bounds<F>(&mut self, mut callback: F) -> Subscription
3171    where
3172        F: 'static + FnMut(&mut V, WindowBounds, Uuid, &mut ViewContext<V>),
3173    {
3174        let observer = self.weak_handle();
3175        self.window_context
3176            .observe_window_bounds(move |bounds, display, cx| {
3177                if let Some(observer) = observer.upgrade(cx) {
3178                    observer.update(cx, |observer, cx| {
3179                        callback(observer, bounds, display, cx);
3180                    });
3181                    true
3182                } else {
3183                    false
3184                }
3185            })
3186    }
3187
3188    pub fn observe_active_labeled_tasks<F>(&mut self, mut callback: F) -> Subscription
3189    where
3190        F: 'static + FnMut(&mut V, &mut ViewContext<V>),
3191    {
3192        let window_id = self.window_id;
3193        let observer = self.weak_handle();
3194        self.window_context.observe_active_labeled_tasks(move |cx| {
3195            cx.update_window(window_id, |cx| {
3196                if let Some(observer) = observer.upgrade(cx) {
3197                    observer.update(cx, |observer, cx| {
3198                        callback(observer, cx);
3199                    });
3200                    true
3201                } else {
3202                    false
3203                }
3204            })
3205            .unwrap_or(false)
3206        })
3207    }
3208
3209    pub fn emit(&mut self, payload: V::Event) {
3210        self.window_context
3211            .pending_effects
3212            .push_back(Effect::Event {
3213                entity_id: self.view_id,
3214                payload: Box::new(payload),
3215            });
3216    }
3217
3218    pub fn notify(&mut self) {
3219        let window_id = self.window_id;
3220        let view_id = self.view_id;
3221        self.window_context.notify_view(window_id, view_id);
3222    }
3223
3224    pub fn dispatch_action(&mut self, action: impl Action) {
3225        let window_id = self.window_id;
3226        let view_id = self.view_id;
3227        self.window_context
3228            .dispatch_action_at(window_id, view_id, action)
3229    }
3230
3231    pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
3232        let window_id = self.window_id;
3233        let view_id = self.view_id;
3234        self.window_context
3235            .dispatch_any_action_at(window_id, view_id, action)
3236    }
3237
3238    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut V, &mut ViewContext<V>)) {
3239        let handle = self.handle();
3240        self.window_context
3241            .defer(move |cx| handle.update(cx, |view, cx| callback(view, cx)))
3242    }
3243
3244    pub fn after_window_update(
3245        &mut self,
3246        callback: impl 'static + FnOnce(&mut V, &mut ViewContext<V>),
3247    ) {
3248        let window_id = self.window_id;
3249        let handle = self.handle();
3250        self.window_context.after_window_update(move |cx| {
3251            cx.update_window(window_id, |cx| {
3252                handle.update(cx, |view, cx| {
3253                    callback(view, cx);
3254                })
3255            });
3256        })
3257    }
3258
3259    pub fn propagate_action(&mut self) {
3260        self.window_context.halt_action_dispatch = false;
3261    }
3262
3263    pub fn spawn_labeled<F, Fut, S>(&mut self, task_label: &'static str, f: F) -> Task<S>
3264    where
3265        F: FnOnce(ViewHandle<V>, AsyncAppContext) -> Fut,
3266        Fut: 'static + Future<Output = S>,
3267        S: 'static,
3268    {
3269        let handle = self.handle();
3270        self.window_context
3271            .spawn_labeled(task_label, |cx| f(handle, cx))
3272    }
3273
3274    pub fn spawn<F, Fut, S>(&mut self, f: F) -> Task<S>
3275    where
3276        F: FnOnce(ViewHandle<V>, AsyncAppContext) -> Fut,
3277        Fut: 'static + Future<Output = S>,
3278        S: 'static,
3279    {
3280        let handle = self.handle();
3281        self.window_context.spawn(|cx| f(handle, cx))
3282    }
3283
3284    pub fn spawn_weak<F, Fut, S>(&mut self, f: F) -> Task<S>
3285    where
3286        F: FnOnce(WeakViewHandle<V>, AsyncAppContext) -> Fut,
3287        Fut: 'static + Future<Output = S>,
3288        S: 'static,
3289    {
3290        let handle = self.weak_handle();
3291        self.window_context.spawn(|cx| f(handle, cx))
3292    }
3293
3294    pub fn mouse_state<Tag: 'static>(&self, region_id: usize) -> MouseState {
3295        let region_id = MouseRegionId::new::<Tag>(self.view_id, region_id);
3296        MouseState {
3297            hovered: self.window.hovered_region_ids.contains(&region_id),
3298            clicked: self
3299                .window
3300                .clicked_region_ids
3301                .get(&region_id)
3302                .and_then(|_| self.window.clicked_button),
3303            accessed_hovered: false,
3304            accessed_clicked: false,
3305        }
3306    }
3307
3308    pub fn element_state<Tag: 'static, T: 'static>(
3309        &mut self,
3310        element_id: usize,
3311        initial: T,
3312    ) -> ElementStateHandle<T> {
3313        let id = ElementStateId {
3314            view_id: self.view_id(),
3315            element_id,
3316            tag: TypeId::of::<Tag>(),
3317        };
3318        self.element_states
3319            .entry(id)
3320            .or_insert_with(|| Box::new(initial));
3321        ElementStateHandle::new(id, self.frame_count, &self.ref_counts)
3322    }
3323
3324    pub fn default_element_state<Tag: 'static, T: 'static + Default>(
3325        &mut self,
3326        element_id: usize,
3327    ) -> ElementStateHandle<T> {
3328        self.element_state::<Tag, T>(element_id, T::default())
3329    }
3330}
3331
3332impl<V> BorrowAppContext for ViewContext<'_, '_, V> {
3333    fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
3334        BorrowAppContext::read_with(&*self.window_context, f)
3335    }
3336
3337    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
3338        BorrowAppContext::update(&mut *self.window_context, f)
3339    }
3340}
3341
3342impl<V> BorrowWindowContext for ViewContext<'_, '_, V> {
3343    type ReturnValue<T> = T;
3344
3345    fn read_with<T, F: FnOnce(&WindowContext) -> T>(&self, window_id: usize, f: F) -> T {
3346        BorrowWindowContext::read_with(&*self.window_context, window_id, f)
3347    }
3348
3349    fn update<T, F: FnOnce(&mut WindowContext) -> T>(&mut self, window_id: usize, f: F) -> T {
3350        BorrowWindowContext::update(&mut *self.window_context, window_id, f)
3351    }
3352}
3353
3354pub struct EventContext<'a, 'b, 'c, V: View> {
3355    view_context: &'c mut ViewContext<'a, 'b, V>,
3356    pub(crate) handled: bool,
3357}
3358
3359impl<'a, 'b, 'c, V: View> EventContext<'a, 'b, 'c, V> {
3360    pub(crate) fn new(view_context: &'c mut ViewContext<'a, 'b, V>) -> Self {
3361        EventContext {
3362            view_context,
3363            handled: true,
3364        }
3365    }
3366
3367    pub fn propagate_event(&mut self) {
3368        self.handled = false;
3369    }
3370}
3371
3372impl<'a, 'b, 'c, V: View> Deref for EventContext<'a, 'b, 'c, V> {
3373    type Target = ViewContext<'a, 'b, V>;
3374
3375    fn deref(&self) -> &Self::Target {
3376        &self.view_context
3377    }
3378}
3379
3380impl<V: View> DerefMut for EventContext<'_, '_, '_, V> {
3381    fn deref_mut(&mut self) -> &mut Self::Target {
3382        &mut self.view_context
3383    }
3384}
3385
3386impl<V: View> BorrowAppContext for EventContext<'_, '_, '_, V> {
3387    fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
3388        BorrowAppContext::read_with(&*self.view_context, f)
3389    }
3390
3391    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
3392        BorrowAppContext::update(&mut *self.view_context, f)
3393    }
3394}
3395
3396impl<V: View> BorrowWindowContext for EventContext<'_, '_, '_, V> {
3397    type ReturnValue<T> = T;
3398
3399    fn read_with<T, F: FnOnce(&WindowContext) -> T>(&self, window_id: usize, f: F) -> T {
3400        BorrowWindowContext::read_with(&*self.view_context, window_id, f)
3401    }
3402
3403    fn update<T, F: FnOnce(&mut WindowContext) -> T>(&mut self, window_id: usize, f: F) -> T {
3404        BorrowWindowContext::update(&mut *self.view_context, window_id, f)
3405    }
3406}
3407
3408pub(crate) enum Reference<'a, T> {
3409    Immutable(&'a T),
3410    Mutable(&'a mut T),
3411}
3412
3413impl<'a, T> Deref for Reference<'a, T> {
3414    type Target = T;
3415
3416    fn deref(&self) -> &Self::Target {
3417        match self {
3418            Reference::Immutable(target) => target,
3419            Reference::Mutable(target) => target,
3420        }
3421    }
3422}
3423
3424impl<'a, T> DerefMut for Reference<'a, T> {
3425    fn deref_mut(&mut self) -> &mut Self::Target {
3426        match self {
3427            Reference::Immutable(_) => {
3428                panic!("cannot mutably deref an immutable reference. this is a bug in GPUI.");
3429            }
3430            Reference::Mutable(target) => target,
3431        }
3432    }
3433}
3434
3435#[derive(Debug, Clone, Default)]
3436pub struct MouseState {
3437    pub(crate) hovered: bool,
3438    pub(crate) clicked: Option<MouseButton>,
3439    pub(crate) accessed_hovered: bool,
3440    pub(crate) accessed_clicked: bool,
3441}
3442
3443impl MouseState {
3444    pub fn hovered(&mut self) -> bool {
3445        self.accessed_hovered = true;
3446        self.hovered
3447    }
3448
3449    pub fn clicked(&mut self) -> Option<MouseButton> {
3450        self.accessed_clicked = true;
3451        self.clicked
3452    }
3453
3454    pub fn accessed_hovered(&self) -> bool {
3455        self.accessed_hovered
3456    }
3457
3458    pub fn accessed_clicked(&self) -> bool {
3459        self.accessed_clicked
3460    }
3461}
3462
3463pub trait Handle<T> {
3464    type Weak: 'static;
3465    fn id(&self) -> usize;
3466    fn location(&self) -> EntityLocation;
3467    fn downgrade(&self) -> Self::Weak;
3468    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3469    where
3470        Self: Sized;
3471}
3472
3473pub trait WeakHandle {
3474    fn id(&self) -> usize;
3475}
3476
3477#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3478pub enum EntityLocation {
3479    Model(usize),
3480    View(usize, usize),
3481}
3482
3483pub struct ModelHandle<T: Entity> {
3484    any_handle: AnyModelHandle,
3485    model_type: PhantomData<T>,
3486}
3487
3488impl<T: Entity> Deref for ModelHandle<T> {
3489    type Target = AnyModelHandle;
3490
3491    fn deref(&self) -> &Self::Target {
3492        &self.any_handle
3493    }
3494}
3495
3496impl<T: Entity> ModelHandle<T> {
3497    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3498        Self {
3499            any_handle: AnyModelHandle::new(model_id, TypeId::of::<T>(), ref_counts.clone()),
3500            model_type: PhantomData,
3501        }
3502    }
3503
3504    pub fn downgrade(&self) -> WeakModelHandle<T> {
3505        WeakModelHandle::new(self.model_id)
3506    }
3507
3508    pub fn id(&self) -> usize {
3509        self.model_id
3510    }
3511
3512    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3513        cx.read_model(self)
3514    }
3515
3516    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3517    where
3518        C: BorrowAppContext,
3519        F: FnOnce(&T, &AppContext) -> S,
3520    {
3521        cx.read_with(|cx| read(self.read(cx), cx))
3522    }
3523
3524    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3525    where
3526        C: BorrowAppContext,
3527        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
3528    {
3529        let mut update = Some(update);
3530        cx.update(|cx| {
3531            cx.update_model(self, &mut |model, cx| {
3532                let update = update.take().unwrap();
3533                update(model, cx)
3534            })
3535        })
3536    }
3537}
3538
3539impl<T: Entity> Clone for ModelHandle<T> {
3540    fn clone(&self) -> Self {
3541        Self::new(self.model_id, &self.ref_counts)
3542    }
3543}
3544
3545impl<T: Entity> PartialEq for ModelHandle<T> {
3546    fn eq(&self, other: &Self) -> bool {
3547        self.model_id == other.model_id
3548    }
3549}
3550
3551impl<T: Entity> Eq for ModelHandle<T> {}
3552
3553impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
3554    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
3555        self.model_id == other.model_id
3556    }
3557}
3558
3559impl<T: Entity> Hash for ModelHandle<T> {
3560    fn hash<H: Hasher>(&self, state: &mut H) {
3561        self.model_id.hash(state);
3562    }
3563}
3564
3565impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
3566    fn borrow(&self) -> &usize {
3567        &self.model_id
3568    }
3569}
3570
3571impl<T: Entity> Debug for ModelHandle<T> {
3572    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3573        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
3574            .field(&self.model_id)
3575            .finish()
3576    }
3577}
3578
3579unsafe impl<T: Entity> Send for ModelHandle<T> {}
3580unsafe impl<T: Entity> Sync for ModelHandle<T> {}
3581
3582impl<T: Entity> Handle<T> for ModelHandle<T> {
3583    type Weak = WeakModelHandle<T>;
3584
3585    fn id(&self) -> usize {
3586        self.model_id
3587    }
3588
3589    fn location(&self) -> EntityLocation {
3590        EntityLocation::Model(self.model_id)
3591    }
3592
3593    fn downgrade(&self) -> Self::Weak {
3594        self.downgrade()
3595    }
3596
3597    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3598    where
3599        Self: Sized,
3600    {
3601        weak.upgrade(cx)
3602    }
3603}
3604
3605pub struct WeakModelHandle<T> {
3606    any_handle: AnyWeakModelHandle,
3607    model_type: PhantomData<T>,
3608}
3609
3610impl<T> WeakModelHandle<T> {
3611    pub fn into_any(self) -> AnyWeakModelHandle {
3612        self.any_handle
3613    }
3614}
3615
3616impl<T> Deref for WeakModelHandle<T> {
3617    type Target = AnyWeakModelHandle;
3618
3619    fn deref(&self) -> &Self::Target {
3620        &self.any_handle
3621    }
3622}
3623
3624impl<T> WeakHandle for WeakModelHandle<T> {
3625    fn id(&self) -> usize {
3626        self.model_id
3627    }
3628}
3629
3630unsafe impl<T> Send for WeakModelHandle<T> {}
3631unsafe impl<T> Sync for WeakModelHandle<T> {}
3632
3633impl<T: Entity> WeakModelHandle<T> {
3634    fn new(model_id: usize) -> Self {
3635        Self {
3636            any_handle: AnyWeakModelHandle {
3637                model_id,
3638                model_type: TypeId::of::<T>(),
3639            },
3640            model_type: PhantomData,
3641        }
3642    }
3643
3644    pub fn id(&self) -> usize {
3645        self.model_id
3646    }
3647
3648    pub fn is_upgradable(&self, cx: &impl BorrowAppContext) -> bool {
3649        cx.read_with(|cx| cx.model_handle_is_upgradable(self))
3650    }
3651
3652    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<T>> {
3653        cx.read_with(|cx| cx.upgrade_model_handle(self))
3654    }
3655}
3656
3657impl<T> Hash for WeakModelHandle<T> {
3658    fn hash<H: Hasher>(&self, state: &mut H) {
3659        self.model_id.hash(state)
3660    }
3661}
3662
3663impl<T> PartialEq for WeakModelHandle<T> {
3664    fn eq(&self, other: &Self) -> bool {
3665        self.model_id == other.model_id
3666    }
3667}
3668
3669impl<T> Eq for WeakModelHandle<T> {}
3670
3671impl<T: Entity> PartialEq<ModelHandle<T>> for WeakModelHandle<T> {
3672    fn eq(&self, other: &ModelHandle<T>) -> bool {
3673        self.model_id == other.model_id
3674    }
3675}
3676
3677impl<T> Clone for WeakModelHandle<T> {
3678    fn clone(&self) -> Self {
3679        Self {
3680            any_handle: self.any_handle.clone(),
3681            model_type: PhantomData,
3682        }
3683    }
3684}
3685
3686impl<T> Copy for WeakModelHandle<T> {}
3687
3688#[repr(transparent)]
3689pub struct ViewHandle<T> {
3690    any_handle: AnyViewHandle,
3691    view_type: PhantomData<T>,
3692}
3693
3694impl<T> Deref for ViewHandle<T> {
3695    type Target = AnyViewHandle;
3696
3697    fn deref(&self) -> &Self::Target {
3698        &self.any_handle
3699    }
3700}
3701
3702impl<T: View> ViewHandle<T> {
3703    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3704        Self {
3705            any_handle: AnyViewHandle::new(
3706                window_id,
3707                view_id,
3708                TypeId::of::<T>(),
3709                ref_counts.clone(),
3710            ),
3711            view_type: PhantomData,
3712        }
3713    }
3714
3715    pub fn downgrade(&self) -> WeakViewHandle<T> {
3716        WeakViewHandle::new(self.window_id, self.view_id)
3717    }
3718
3719    pub fn into_any(self) -> AnyViewHandle {
3720        self.any_handle
3721    }
3722
3723    pub fn window_id(&self) -> usize {
3724        self.window_id
3725    }
3726
3727    pub fn id(&self) -> usize {
3728        self.view_id
3729    }
3730
3731    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3732        cx.read_view(self)
3733    }
3734
3735    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> C::ReturnValue<S>
3736    where
3737        C: BorrowWindowContext,
3738        F: FnOnce(&T, &ViewContext<T>) -> S,
3739    {
3740        cx.read_with(self.window_id, |cx| {
3741            let cx = ViewContext::immutable(cx, self.view_id);
3742            read(cx.read_view(self), &cx)
3743        })
3744    }
3745
3746    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> C::ReturnValue<S>
3747    where
3748        C: BorrowWindowContext,
3749        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
3750    {
3751        let mut update = Some(update);
3752
3753        cx.update(self.window_id, |cx| {
3754            cx.update_view(self, &mut |view, cx| {
3755                let update = update.take().unwrap();
3756                update(view, cx)
3757            })
3758        })
3759    }
3760
3761    pub fn is_focused(&self, cx: &WindowContext) -> bool {
3762        cx.focused_view_id() == Some(self.view_id)
3763    }
3764}
3765
3766impl<T: View> Clone for ViewHandle<T> {
3767    fn clone(&self) -> Self {
3768        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
3769    }
3770}
3771
3772impl<T> PartialEq for ViewHandle<T> {
3773    fn eq(&self, other: &Self) -> bool {
3774        self.window_id == other.window_id && self.view_id == other.view_id
3775    }
3776}
3777
3778impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
3779    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
3780        self.window_id == other.window_id && self.view_id == other.view_id
3781    }
3782}
3783
3784impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
3785    fn eq(&self, other: &ViewHandle<T>) -> bool {
3786        self.window_id == other.window_id && self.view_id == other.view_id
3787    }
3788}
3789
3790impl<T> Eq for ViewHandle<T> {}
3791
3792impl<T> Hash for ViewHandle<T> {
3793    fn hash<H: Hasher>(&self, state: &mut H) {
3794        self.window_id.hash(state);
3795        self.view_id.hash(state);
3796    }
3797}
3798
3799impl<T> Debug for ViewHandle<T> {
3800    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3801        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
3802            .field("window_id", &self.window_id)
3803            .field("view_id", &self.view_id)
3804            .finish()
3805    }
3806}
3807
3808impl<T: View> Handle<T> for ViewHandle<T> {
3809    type Weak = WeakViewHandle<T>;
3810
3811    fn id(&self) -> usize {
3812        self.view_id
3813    }
3814
3815    fn location(&self) -> EntityLocation {
3816        EntityLocation::View(self.window_id, self.view_id)
3817    }
3818
3819    fn downgrade(&self) -> Self::Weak {
3820        self.downgrade()
3821    }
3822
3823    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3824    where
3825        Self: Sized,
3826    {
3827        weak.upgrade(cx)
3828    }
3829}
3830
3831pub struct AnyViewHandle {
3832    window_id: usize,
3833    view_id: usize,
3834    view_type: TypeId,
3835    ref_counts: Arc<Mutex<RefCounts>>,
3836
3837    #[cfg(any(test, feature = "test-support"))]
3838    handle_id: usize,
3839}
3840
3841impl AnyViewHandle {
3842    fn new(
3843        window_id: usize,
3844        view_id: usize,
3845        view_type: TypeId,
3846        ref_counts: Arc<Mutex<RefCounts>>,
3847    ) -> Self {
3848        ref_counts.lock().inc_view(window_id, view_id);
3849
3850        #[cfg(any(test, feature = "test-support"))]
3851        let handle_id = ref_counts
3852            .lock()
3853            .leak_detector
3854            .lock()
3855            .handle_created(None, view_id);
3856
3857        Self {
3858            window_id,
3859            view_id,
3860            view_type,
3861            ref_counts,
3862            #[cfg(any(test, feature = "test-support"))]
3863            handle_id,
3864        }
3865    }
3866
3867    pub fn window_id(&self) -> usize {
3868        self.window_id
3869    }
3870
3871    pub fn id(&self) -> usize {
3872        self.view_id
3873    }
3874
3875    pub fn is<T: 'static>(&self) -> bool {
3876        TypeId::of::<T>() == self.view_type
3877    }
3878
3879    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
3880        if self.is::<T>() {
3881            Some(ViewHandle {
3882                any_handle: self,
3883                view_type: PhantomData,
3884            })
3885        } else {
3886            None
3887        }
3888    }
3889
3890    pub fn downcast_ref<T: View>(&self) -> Option<&ViewHandle<T>> {
3891        if self.is::<T>() {
3892            Some(unsafe { mem::transmute(self) })
3893        } else {
3894            None
3895        }
3896    }
3897
3898    pub fn downgrade(&self) -> AnyWeakViewHandle {
3899        AnyWeakViewHandle {
3900            window_id: self.window_id,
3901            view_id: self.view_id,
3902            view_type: self.view_type,
3903        }
3904    }
3905
3906    pub fn view_type(&self) -> TypeId {
3907        self.view_type
3908    }
3909
3910    pub fn debug_json<'a, 'b>(&self, cx: &'b WindowContext<'a>) -> serde_json::Value {
3911        cx.views
3912            .get(&(self.window_id, self.view_id))
3913            .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
3914    }
3915}
3916
3917impl Clone for AnyViewHandle {
3918    fn clone(&self) -> Self {
3919        Self::new(
3920            self.window_id,
3921            self.view_id,
3922            self.view_type,
3923            self.ref_counts.clone(),
3924        )
3925    }
3926}
3927
3928impl<T> PartialEq<ViewHandle<T>> for AnyViewHandle {
3929    fn eq(&self, other: &ViewHandle<T>) -> bool {
3930        self.window_id == other.window_id && self.view_id == other.view_id
3931    }
3932}
3933
3934impl Drop for AnyViewHandle {
3935    fn drop(&mut self) {
3936        self.ref_counts
3937            .lock()
3938            .dec_view(self.window_id, self.view_id);
3939        #[cfg(any(test, feature = "test-support"))]
3940        self.ref_counts
3941            .lock()
3942            .leak_detector
3943            .lock()
3944            .handle_dropped(self.view_id, self.handle_id);
3945    }
3946}
3947
3948pub struct AnyModelHandle {
3949    model_id: usize,
3950    model_type: TypeId,
3951    ref_counts: Arc<Mutex<RefCounts>>,
3952
3953    #[cfg(any(test, feature = "test-support"))]
3954    handle_id: usize,
3955}
3956
3957impl AnyModelHandle {
3958    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
3959        ref_counts.lock().inc_model(model_id);
3960
3961        #[cfg(any(test, feature = "test-support"))]
3962        let handle_id = ref_counts
3963            .lock()
3964            .leak_detector
3965            .lock()
3966            .handle_created(None, model_id);
3967
3968        Self {
3969            model_id,
3970            model_type,
3971            ref_counts,
3972
3973            #[cfg(any(test, feature = "test-support"))]
3974            handle_id,
3975        }
3976    }
3977
3978    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
3979        if self.is::<T>() {
3980            Some(ModelHandle {
3981                any_handle: self,
3982                model_type: PhantomData,
3983            })
3984        } else {
3985            None
3986        }
3987    }
3988
3989    pub fn downgrade(&self) -> AnyWeakModelHandle {
3990        AnyWeakModelHandle {
3991            model_id: self.model_id,
3992            model_type: self.model_type,
3993        }
3994    }
3995
3996    pub fn is<T: Entity>(&self) -> bool {
3997        self.model_type == TypeId::of::<T>()
3998    }
3999
4000    pub fn model_type(&self) -> TypeId {
4001        self.model_type
4002    }
4003}
4004
4005impl Clone for AnyModelHandle {
4006    fn clone(&self) -> Self {
4007        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
4008    }
4009}
4010
4011impl Drop for AnyModelHandle {
4012    fn drop(&mut self) {
4013        let mut ref_counts = self.ref_counts.lock();
4014        ref_counts.dec_model(self.model_id);
4015
4016        #[cfg(any(test, feature = "test-support"))]
4017        ref_counts
4018            .leak_detector
4019            .lock()
4020            .handle_dropped(self.model_id, self.handle_id);
4021    }
4022}
4023
4024#[derive(Hash, PartialEq, Eq, Debug, Clone, Copy)]
4025pub struct AnyWeakModelHandle {
4026    model_id: usize,
4027    model_type: TypeId,
4028}
4029
4030impl AnyWeakModelHandle {
4031    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<AnyModelHandle> {
4032        cx.read_with(|cx| cx.upgrade_any_model_handle(self))
4033    }
4034
4035    pub fn model_type(&self) -> TypeId {
4036        self.model_type
4037    }
4038
4039    fn is<T: 'static>(&self) -> bool {
4040        TypeId::of::<T>() == self.model_type
4041    }
4042
4043    pub fn downcast<T: Entity>(self) -> Option<WeakModelHandle<T>> {
4044        if self.is::<T>() {
4045            let result = Some(WeakModelHandle {
4046                any_handle: self,
4047                model_type: PhantomData,
4048            });
4049
4050            result
4051        } else {
4052            None
4053        }
4054    }
4055}
4056
4057#[derive(Debug, Copy)]
4058pub struct WeakViewHandle<T> {
4059    any_handle: AnyWeakViewHandle,
4060    view_type: PhantomData<T>,
4061}
4062
4063impl<T> WeakHandle for WeakViewHandle<T> {
4064    fn id(&self) -> usize {
4065        self.view_id
4066    }
4067}
4068
4069impl<V: View> WeakViewHandle<V> {
4070    fn new(window_id: usize, view_id: usize) -> Self {
4071        Self {
4072            any_handle: AnyWeakViewHandle {
4073                window_id,
4074                view_id,
4075                view_type: TypeId::of::<V>(),
4076            },
4077            view_type: PhantomData,
4078        }
4079    }
4080
4081    pub fn id(&self) -> usize {
4082        self.view_id
4083    }
4084
4085    pub fn window_id(&self) -> usize {
4086        self.window_id
4087    }
4088
4089    pub fn into_any(self) -> AnyWeakViewHandle {
4090        self.any_handle
4091    }
4092
4093    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ViewHandle<V>> {
4094        cx.read_with(|cx| cx.upgrade_view_handle(self))
4095    }
4096
4097    pub fn update<T>(
4098        &self,
4099        cx: &mut impl BorrowAppContext,
4100        update: impl FnOnce(&mut V, &mut ViewContext<V>) -> T,
4101    ) -> Option<T> {
4102        cx.update(|cx| {
4103            let handle = cx.upgrade_view_handle(self)?;
4104
4105            cx.update_window(self.window_id, |cx| handle.update(cx, update))
4106        })
4107    }
4108}
4109
4110impl<T> Deref for WeakViewHandle<T> {
4111    type Target = AnyWeakViewHandle;
4112
4113    fn deref(&self) -> &Self::Target {
4114        &self.any_handle
4115    }
4116}
4117
4118impl<T> Clone for WeakViewHandle<T> {
4119    fn clone(&self) -> Self {
4120        Self {
4121            any_handle: self.any_handle.clone(),
4122            view_type: PhantomData,
4123        }
4124    }
4125}
4126
4127impl<T> PartialEq for WeakViewHandle<T> {
4128    fn eq(&self, other: &Self) -> bool {
4129        self.window_id == other.window_id && self.view_id == other.view_id
4130    }
4131}
4132
4133impl<T> Eq for WeakViewHandle<T> {}
4134
4135impl<T> Hash for WeakViewHandle<T> {
4136    fn hash<H: Hasher>(&self, state: &mut H) {
4137        self.any_handle.hash(state);
4138    }
4139}
4140
4141#[derive(Debug, Clone, Copy)]
4142pub struct AnyWeakViewHandle {
4143    window_id: usize,
4144    view_id: usize,
4145    view_type: TypeId,
4146}
4147
4148impl AnyWeakViewHandle {
4149    pub fn id(&self) -> usize {
4150        self.view_id
4151    }
4152
4153    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<AnyViewHandle> {
4154        cx.read_with(|cx| cx.upgrade_any_view_handle(self))
4155    }
4156}
4157
4158impl Hash for AnyWeakViewHandle {
4159    fn hash<H: Hasher>(&self, state: &mut H) {
4160        self.window_id.hash(state);
4161        self.view_id.hash(state);
4162        self.view_type.hash(state);
4163    }
4164}
4165
4166#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4167pub struct ElementStateId {
4168    view_id: usize,
4169    element_id: usize,
4170    tag: TypeId,
4171}
4172
4173pub struct ElementStateHandle<T> {
4174    value_type: PhantomData<T>,
4175    id: ElementStateId,
4176    ref_counts: Weak<Mutex<RefCounts>>,
4177}
4178
4179impl<T: 'static> ElementStateHandle<T> {
4180    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4181        ref_counts.lock().inc_element_state(id, frame_id);
4182        Self {
4183            value_type: PhantomData,
4184            id,
4185            ref_counts: Arc::downgrade(ref_counts),
4186        }
4187    }
4188
4189    pub fn id(&self) -> ElementStateId {
4190        self.id
4191    }
4192
4193    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4194        cx.element_states
4195            .get(&self.id)
4196            .unwrap()
4197            .downcast_ref()
4198            .unwrap()
4199    }
4200
4201    pub fn update<C, D, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4202    where
4203        C: DerefMut<Target = D>,
4204        D: DerefMut<Target = AppContext>,
4205    {
4206        let mut element_state = cx.deref_mut().element_states.remove(&self.id).unwrap();
4207        let result = f(element_state.downcast_mut().unwrap(), cx);
4208        cx.deref_mut().element_states.insert(self.id, element_state);
4209        result
4210    }
4211}
4212
4213impl<T> Drop for ElementStateHandle<T> {
4214    fn drop(&mut self) {
4215        if let Some(ref_counts) = self.ref_counts.upgrade() {
4216            ref_counts.lock().dec_element_state(self.id);
4217        }
4218    }
4219}
4220
4221#[must_use]
4222pub enum Subscription {
4223    Subscription(callback_collection::Subscription<usize, SubscriptionCallback>),
4224    Observation(callback_collection::Subscription<usize, ObservationCallback>),
4225    GlobalSubscription(callback_collection::Subscription<TypeId, GlobalSubscriptionCallback>),
4226    GlobalObservation(callback_collection::Subscription<TypeId, GlobalObservationCallback>),
4227    FocusObservation(callback_collection::Subscription<usize, FocusObservationCallback>),
4228    WindowActivationObservation(callback_collection::Subscription<usize, WindowActivationCallback>),
4229    WindowFullscreenObservation(callback_collection::Subscription<usize, WindowFullscreenCallback>),
4230    WindowBoundsObservation(callback_collection::Subscription<usize, WindowBoundsCallback>),
4231    KeystrokeObservation(callback_collection::Subscription<usize, KeystrokeCallback>),
4232    ReleaseObservation(callback_collection::Subscription<usize, ReleaseObservationCallback>),
4233    ActionObservation(callback_collection::Subscription<(), ActionObservationCallback>),
4234    ActiveLabeledTasksObservation(
4235        callback_collection::Subscription<(), ActiveLabeledTasksCallback>,
4236    ),
4237}
4238
4239impl Subscription {
4240    pub fn id(&self) -> usize {
4241        match self {
4242            Subscription::Subscription(subscription) => subscription.id(),
4243            Subscription::Observation(subscription) => subscription.id(),
4244            Subscription::GlobalSubscription(subscription) => subscription.id(),
4245            Subscription::GlobalObservation(subscription) => subscription.id(),
4246            Subscription::FocusObservation(subscription) => subscription.id(),
4247            Subscription::WindowActivationObservation(subscription) => subscription.id(),
4248            Subscription::WindowFullscreenObservation(subscription) => subscription.id(),
4249            Subscription::WindowBoundsObservation(subscription) => subscription.id(),
4250            Subscription::KeystrokeObservation(subscription) => subscription.id(),
4251            Subscription::ReleaseObservation(subscription) => subscription.id(),
4252            Subscription::ActionObservation(subscription) => subscription.id(),
4253            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.id(),
4254        }
4255    }
4256
4257    pub fn detach(&mut self) {
4258        match self {
4259            Subscription::Subscription(subscription) => subscription.detach(),
4260            Subscription::GlobalSubscription(subscription) => subscription.detach(),
4261            Subscription::Observation(subscription) => subscription.detach(),
4262            Subscription::GlobalObservation(subscription) => subscription.detach(),
4263            Subscription::FocusObservation(subscription) => subscription.detach(),
4264            Subscription::KeystrokeObservation(subscription) => subscription.detach(),
4265            Subscription::WindowActivationObservation(subscription) => subscription.detach(),
4266            Subscription::WindowFullscreenObservation(subscription) => subscription.detach(),
4267            Subscription::WindowBoundsObservation(subscription) => subscription.detach(),
4268            Subscription::ReleaseObservation(subscription) => subscription.detach(),
4269            Subscription::ActionObservation(subscription) => subscription.detach(),
4270            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.detach(),
4271        }
4272    }
4273}
4274
4275#[cfg(test)]
4276mod tests {
4277    use super::*;
4278    use crate::{
4279        actions,
4280        elements::*,
4281        impl_actions,
4282        platform::{MouseButton, MouseButtonEvent},
4283        window::ChildView,
4284    };
4285    use itertools::Itertools;
4286    use postage::{sink::Sink, stream::Stream};
4287    use serde::Deserialize;
4288    use smol::future::poll_once;
4289    use std::{
4290        cell::Cell,
4291        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
4292    };
4293
4294    #[crate::test(self)]
4295    fn test_model_handles(cx: &mut AppContext) {
4296        struct Model {
4297            other: Option<ModelHandle<Model>>,
4298            events: Vec<String>,
4299        }
4300
4301        impl Entity for Model {
4302            type Event = usize;
4303        }
4304
4305        impl Model {
4306            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4307                if let Some(other) = other.as_ref() {
4308                    cx.observe(other, |me, _, _| {
4309                        me.events.push("notified".into());
4310                    })
4311                    .detach();
4312                    cx.subscribe(other, |me, _, event, _| {
4313                        me.events.push(format!("observed event {}", event));
4314                    })
4315                    .detach();
4316                }
4317
4318                Self {
4319                    other,
4320                    events: Vec::new(),
4321                }
4322            }
4323        }
4324
4325        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4326        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4327        assert_eq!(cx.models.len(), 2);
4328
4329        handle_1.update(cx, |model, cx| {
4330            model.events.push("updated".into());
4331            cx.emit(1);
4332            cx.notify();
4333            cx.emit(2);
4334        });
4335        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4336        assert_eq!(
4337            handle_2.read(cx).events,
4338            vec![
4339                "observed event 1".to_string(),
4340                "notified".to_string(),
4341                "observed event 2".to_string(),
4342            ]
4343        );
4344
4345        handle_2.update(cx, |model, _| {
4346            drop(handle_1);
4347            model.other.take();
4348        });
4349
4350        assert_eq!(cx.models.len(), 1);
4351        assert!(cx.subscriptions.is_empty());
4352        assert!(cx.observations.is_empty());
4353    }
4354
4355    #[crate::test(self)]
4356    fn test_model_events(cx: &mut AppContext) {
4357        #[derive(Default)]
4358        struct Model {
4359            events: Vec<usize>,
4360        }
4361
4362        impl Entity for Model {
4363            type Event = usize;
4364        }
4365
4366        let handle_1 = cx.add_model(|_| Model::default());
4367        let handle_2 = cx.add_model(|_| Model::default());
4368
4369        handle_1.update(cx, |_, cx| {
4370            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
4371                model.events.push(*event);
4372
4373                cx.subscribe(&emitter, |model, _, event, _| {
4374                    model.events.push(*event * 2);
4375                })
4376                .detach();
4377            })
4378            .detach();
4379        });
4380
4381        handle_2.update(cx, |_, c| c.emit(7));
4382        assert_eq!(handle_1.read(cx).events, vec![7]);
4383
4384        handle_2.update(cx, |_, c| c.emit(5));
4385        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4386    }
4387
4388    #[crate::test(self)]
4389    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
4390        #[derive(Default)]
4391        struct Model;
4392
4393        impl Entity for Model {
4394            type Event = ();
4395        }
4396
4397        let events = Rc::new(RefCell::new(Vec::new()));
4398        cx.add_model(|cx| {
4399            drop(cx.subscribe(&cx.handle(), {
4400                let events = events.clone();
4401                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
4402            }));
4403            cx.subscribe(&cx.handle(), {
4404                let events = events.clone();
4405                move |_, _, _, _| events.borrow_mut().push("before emit")
4406            })
4407            .detach();
4408            cx.emit(());
4409            cx.subscribe(&cx.handle(), {
4410                let events = events.clone();
4411                move |_, _, _, _| events.borrow_mut().push("after emit")
4412            })
4413            .detach();
4414            Model
4415        });
4416        assert_eq!(*events.borrow(), ["before emit"]);
4417    }
4418
4419    #[crate::test(self)]
4420    fn test_observe_and_notify_from_model(cx: &mut AppContext) {
4421        #[derive(Default)]
4422        struct Model {
4423            count: usize,
4424            events: Vec<usize>,
4425        }
4426
4427        impl Entity for Model {
4428            type Event = ();
4429        }
4430
4431        let handle_1 = cx.add_model(|_| Model::default());
4432        let handle_2 = cx.add_model(|_| Model::default());
4433
4434        handle_1.update(cx, |_, c| {
4435            c.observe(&handle_2, move |model, observed, c| {
4436                model.events.push(observed.read(c).count);
4437                c.observe(&observed, |model, observed, c| {
4438                    model.events.push(observed.read(c).count * 2);
4439                })
4440                .detach();
4441            })
4442            .detach();
4443        });
4444
4445        handle_2.update(cx, |model, c| {
4446            model.count = 7;
4447            c.notify()
4448        });
4449        assert_eq!(handle_1.read(cx).events, vec![7]);
4450
4451        handle_2.update(cx, |model, c| {
4452            model.count = 5;
4453            c.notify()
4454        });
4455        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
4456    }
4457
4458    #[crate::test(self)]
4459    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
4460        #[derive(Default)]
4461        struct Model;
4462
4463        impl Entity for Model {
4464            type Event = ();
4465        }
4466
4467        let events = Rc::new(RefCell::new(Vec::new()));
4468        cx.add_model(|cx| {
4469            drop(cx.observe(&cx.handle(), {
4470                let events = events.clone();
4471                move |_, _, _| events.borrow_mut().push("dropped before flush")
4472            }));
4473            cx.observe(&cx.handle(), {
4474                let events = events.clone();
4475                move |_, _, _| events.borrow_mut().push("before notify")
4476            })
4477            .detach();
4478            cx.notify();
4479            cx.observe(&cx.handle(), {
4480                let events = events.clone();
4481                move |_, _, _| events.borrow_mut().push("after notify")
4482            })
4483            .detach();
4484            Model
4485        });
4486        assert_eq!(*events.borrow(), ["before notify"]);
4487    }
4488
4489    #[crate::test(self)]
4490    fn test_defer_and_after_window_update(cx: &mut TestAppContext) {
4491        struct View {
4492            render_count: usize,
4493        }
4494
4495        impl Entity for View {
4496            type Event = usize;
4497        }
4498
4499        impl super::View for View {
4500            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
4501                post_inc(&mut self.render_count);
4502                Empty::new().into_any()
4503            }
4504
4505            fn ui_name() -> &'static str {
4506                "View"
4507            }
4508        }
4509
4510        let (_, view) = cx.add_window(|_| View { render_count: 0 });
4511        let called_defer = Rc::new(AtomicBool::new(false));
4512        let called_after_window_update = Rc::new(AtomicBool::new(false));
4513
4514        view.update(cx, |this, cx| {
4515            assert_eq!(this.render_count, 1);
4516            cx.defer({
4517                let called_defer = called_defer.clone();
4518                move |this, _| {
4519                    assert_eq!(this.render_count, 1);
4520                    called_defer.store(true, SeqCst);
4521                }
4522            });
4523            cx.after_window_update({
4524                let called_after_window_update = called_after_window_update.clone();
4525                move |this, cx| {
4526                    assert_eq!(this.render_count, 2);
4527                    called_after_window_update.store(true, SeqCst);
4528                    cx.notify();
4529                }
4530            });
4531            assert!(!called_defer.load(SeqCst));
4532            assert!(!called_after_window_update.load(SeqCst));
4533            cx.notify();
4534        });
4535
4536        assert!(called_defer.load(SeqCst));
4537        assert!(called_after_window_update.load(SeqCst));
4538        assert_eq!(view.read_with(cx, |view, _| view.render_count), 3);
4539    }
4540
4541    #[crate::test(self)]
4542    fn test_view_handles(cx: &mut TestAppContext) {
4543        struct View {
4544            other: Option<ViewHandle<View>>,
4545            events: Vec<String>,
4546        }
4547
4548        impl Entity for View {
4549            type Event = usize;
4550        }
4551
4552        impl super::View for View {
4553            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
4554                Empty::new().into_any()
4555            }
4556
4557            fn ui_name() -> &'static str {
4558                "View"
4559            }
4560        }
4561
4562        impl View {
4563            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
4564                if let Some(other) = other.as_ref() {
4565                    cx.subscribe(other, |me, _, event, _| {
4566                        me.events.push(format!("observed event {}", event));
4567                    })
4568                    .detach();
4569                }
4570                Self {
4571                    other,
4572                    events: Vec::new(),
4573                }
4574            }
4575        }
4576
4577        let (_, root_view) = cx.add_window(|cx| View::new(None, cx));
4578        let handle_1 = cx.add_view(&root_view, |cx| View::new(None, cx));
4579        let handle_2 = cx.add_view(&root_view, |cx| View::new(Some(handle_1.clone()), cx));
4580        assert_eq!(cx.read(|cx| cx.views.len()), 3);
4581
4582        handle_1.update(cx, |view, cx| {
4583            view.events.push("updated".into());
4584            cx.emit(1);
4585            cx.emit(2);
4586        });
4587        handle_1.read_with(cx, |view, _| {
4588            assert_eq!(view.events, vec!["updated".to_string()]);
4589        });
4590        handle_2.read_with(cx, |view, _| {
4591            assert_eq!(
4592                view.events,
4593                vec![
4594                    "observed event 1".to_string(),
4595                    "observed event 2".to_string(),
4596                ]
4597            );
4598        });
4599
4600        handle_2.update(cx, |view, _| {
4601            drop(handle_1);
4602            view.other.take();
4603        });
4604
4605        cx.read(|cx| {
4606            assert_eq!(cx.views.len(), 2);
4607            assert!(cx.subscriptions.is_empty());
4608            assert!(cx.observations.is_empty());
4609        });
4610    }
4611
4612    #[crate::test(self)]
4613    fn test_add_window(cx: &mut AppContext) {
4614        struct View {
4615            mouse_down_count: Arc<AtomicUsize>,
4616        }
4617
4618        impl Entity for View {
4619            type Event = ();
4620        }
4621
4622        impl super::View for View {
4623            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
4624                enum Handler {}
4625                let mouse_down_count = self.mouse_down_count.clone();
4626                MouseEventHandler::<Handler, _>::new(0, cx, |_, _| Empty::new())
4627                    .on_down(MouseButton::Left, move |_, _, _| {
4628                        mouse_down_count.fetch_add(1, SeqCst);
4629                    })
4630                    .into_any()
4631            }
4632
4633            fn ui_name() -> &'static str {
4634                "View"
4635            }
4636        }
4637
4638        let mouse_down_count = Arc::new(AtomicUsize::new(0));
4639        let (window_id, _) = cx.add_window(Default::default(), |_| View {
4640            mouse_down_count: mouse_down_count.clone(),
4641        });
4642
4643        cx.update_window(window_id, |cx| {
4644            // Ensure window's root element is in a valid lifecycle state.
4645            cx.dispatch_event(
4646                Event::MouseDown(MouseButtonEvent {
4647                    position: Default::default(),
4648                    button: MouseButton::Left,
4649                    modifiers: Default::default(),
4650                    click_count: 1,
4651                }),
4652                false,
4653            );
4654            assert_eq!(mouse_down_count.load(SeqCst), 1);
4655        });
4656    }
4657
4658    #[crate::test(self)]
4659    fn test_entity_release_hooks(cx: &mut AppContext) {
4660        struct Model {
4661            released: Rc<Cell<bool>>,
4662        }
4663
4664        struct View {
4665            released: Rc<Cell<bool>>,
4666        }
4667
4668        impl Entity for Model {
4669            type Event = ();
4670
4671            fn release(&mut self, _: &mut AppContext) {
4672                self.released.set(true);
4673            }
4674        }
4675
4676        impl Entity for View {
4677            type Event = ();
4678
4679            fn release(&mut self, _: &mut AppContext) {
4680                self.released.set(true);
4681            }
4682        }
4683
4684        impl super::View for View {
4685            fn ui_name() -> &'static str {
4686                "View"
4687            }
4688
4689            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
4690                Empty::new().into_any()
4691            }
4692        }
4693
4694        let model_released = Rc::new(Cell::new(false));
4695        let model_release_observed = Rc::new(Cell::new(false));
4696        let view_released = Rc::new(Cell::new(false));
4697        let view_release_observed = Rc::new(Cell::new(false));
4698
4699        let model = cx.add_model(|_| Model {
4700            released: model_released.clone(),
4701        });
4702        let (window_id, view) = cx.add_window(Default::default(), |_| View {
4703            released: view_released.clone(),
4704        });
4705        assert!(!model_released.get());
4706        assert!(!view_released.get());
4707
4708        cx.observe_release(&model, {
4709            let model_release_observed = model_release_observed.clone();
4710            move |_, _| model_release_observed.set(true)
4711        })
4712        .detach();
4713        cx.observe_release(&view, {
4714            let view_release_observed = view_release_observed.clone();
4715            move |_, _| view_release_observed.set(true)
4716        })
4717        .detach();
4718
4719        cx.update(move |_| {
4720            drop(model);
4721        });
4722        assert!(model_released.get());
4723        assert!(model_release_observed.get());
4724
4725        drop(view);
4726        cx.remove_window(window_id);
4727        assert!(view_released.get());
4728        assert!(view_release_observed.get());
4729    }
4730
4731    #[crate::test(self)]
4732    fn test_view_events(cx: &mut TestAppContext) {
4733        struct Model;
4734
4735        impl Entity for Model {
4736            type Event = String;
4737        }
4738
4739        let (_, handle_1) = cx.add_window(|_| TestView::default());
4740        let handle_2 = cx.add_view(&handle_1, |_| TestView::default());
4741        let handle_3 = cx.add_model(|_| Model);
4742
4743        handle_1.update(cx, |_, cx| {
4744            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
4745                me.events.push(event.clone());
4746
4747                cx.subscribe(&emitter, |me, _, event, _| {
4748                    me.events.push(format!("{event} from inner"));
4749                })
4750                .detach();
4751            })
4752            .detach();
4753
4754            cx.subscribe(&handle_3, |me, _, event, _| {
4755                me.events.push(event.clone());
4756            })
4757            .detach();
4758        });
4759
4760        handle_2.update(cx, |_, c| c.emit("7".into()));
4761        handle_1.read_with(cx, |view, _| assert_eq!(view.events, ["7"]));
4762
4763        handle_2.update(cx, |_, c| c.emit("5".into()));
4764        handle_1.read_with(cx, |view, _| {
4765            assert_eq!(view.events, ["7", "5", "5 from inner"])
4766        });
4767
4768        handle_3.update(cx, |_, c| c.emit("9".into()));
4769        handle_1.read_with(cx, |view, _| {
4770            assert_eq!(view.events, ["7", "5", "5 from inner", "9"])
4771        });
4772    }
4773
4774    #[crate::test(self)]
4775    fn test_global_events(cx: &mut AppContext) {
4776        #[derive(Clone, Debug, Eq, PartialEq)]
4777        struct GlobalEvent(u64);
4778
4779        let events = Rc::new(RefCell::new(Vec::new()));
4780        let first_subscription;
4781        let second_subscription;
4782
4783        {
4784            let events = events.clone();
4785            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
4786                events.borrow_mut().push(("First", e.clone()));
4787            });
4788        }
4789
4790        {
4791            let events = events.clone();
4792            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
4793                events.borrow_mut().push(("Second", e.clone()));
4794            });
4795        }
4796
4797        cx.update(|cx| {
4798            cx.emit_global(GlobalEvent(1));
4799            cx.emit_global(GlobalEvent(2));
4800        });
4801
4802        drop(first_subscription);
4803
4804        cx.update(|cx| {
4805            cx.emit_global(GlobalEvent(3));
4806        });
4807
4808        drop(second_subscription);
4809
4810        cx.update(|cx| {
4811            cx.emit_global(GlobalEvent(4));
4812        });
4813
4814        assert_eq!(
4815            &*events.borrow(),
4816            &[
4817                ("First", GlobalEvent(1)),
4818                ("Second", GlobalEvent(1)),
4819                ("First", GlobalEvent(2)),
4820                ("Second", GlobalEvent(2)),
4821                ("Second", GlobalEvent(3)),
4822            ]
4823        );
4824    }
4825
4826    #[crate::test(self)]
4827    fn test_global_events_emitted_before_subscription_in_same_update_cycle(cx: &mut AppContext) {
4828        let events = Rc::new(RefCell::new(Vec::new()));
4829        cx.update(|cx| {
4830            {
4831                let events = events.clone();
4832                drop(cx.subscribe_global(move |_: &(), _| {
4833                    events.borrow_mut().push("dropped before emit");
4834                }));
4835            }
4836
4837            {
4838                let events = events.clone();
4839                cx.subscribe_global(move |_: &(), _| {
4840                    events.borrow_mut().push("before emit");
4841                })
4842                .detach();
4843            }
4844
4845            cx.emit_global(());
4846
4847            {
4848                let events = events.clone();
4849                cx.subscribe_global(move |_: &(), _| {
4850                    events.borrow_mut().push("after emit");
4851                })
4852                .detach();
4853            }
4854        });
4855
4856        assert_eq!(*events.borrow(), ["before emit"]);
4857    }
4858
4859    #[crate::test(self)]
4860    fn test_global_nested_events(cx: &mut AppContext) {
4861        #[derive(Clone, Debug, Eq, PartialEq)]
4862        struct GlobalEvent(u64);
4863
4864        let events = Rc::new(RefCell::new(Vec::new()));
4865
4866        {
4867            let events = events.clone();
4868            cx.subscribe_global(move |e: &GlobalEvent, cx| {
4869                events.borrow_mut().push(("Outer", e.clone()));
4870
4871                if e.0 == 1 {
4872                    let events = events.clone();
4873                    cx.subscribe_global(move |e: &GlobalEvent, _| {
4874                        events.borrow_mut().push(("Inner", e.clone()));
4875                    })
4876                    .detach();
4877                }
4878            })
4879            .detach();
4880        }
4881
4882        cx.update(|cx| {
4883            cx.emit_global(GlobalEvent(1));
4884            cx.emit_global(GlobalEvent(2));
4885            cx.emit_global(GlobalEvent(3));
4886        });
4887        cx.update(|cx| {
4888            cx.emit_global(GlobalEvent(4));
4889        });
4890
4891        assert_eq!(
4892            &*events.borrow(),
4893            &[
4894                ("Outer", GlobalEvent(1)),
4895                ("Outer", GlobalEvent(2)),
4896                ("Outer", GlobalEvent(3)),
4897                ("Outer", GlobalEvent(4)),
4898                ("Inner", GlobalEvent(4)),
4899            ]
4900        );
4901    }
4902
4903    #[crate::test(self)]
4904    fn test_global(cx: &mut AppContext) {
4905        type Global = usize;
4906
4907        let observation_count = Rc::new(RefCell::new(0));
4908        let subscription = cx.observe_global::<Global, _>({
4909            let observation_count = observation_count.clone();
4910            move |_| {
4911                *observation_count.borrow_mut() += 1;
4912            }
4913        });
4914
4915        assert!(!cx.has_global::<Global>());
4916        assert_eq!(cx.default_global::<Global>(), &0);
4917        assert_eq!(*observation_count.borrow(), 1);
4918        assert!(cx.has_global::<Global>());
4919        assert_eq!(
4920            cx.update_global::<Global, _, _>(|global, _| {
4921                *global = 1;
4922                "Update Result"
4923            }),
4924            "Update Result"
4925        );
4926        assert_eq!(*observation_count.borrow(), 2);
4927        assert_eq!(cx.global::<Global>(), &1);
4928
4929        drop(subscription);
4930        cx.update_global::<Global, _, _>(|global, _| {
4931            *global = 2;
4932        });
4933        assert_eq!(*observation_count.borrow(), 2);
4934
4935        type OtherGlobal = f32;
4936
4937        let observation_count = Rc::new(RefCell::new(0));
4938        cx.observe_global::<OtherGlobal, _>({
4939            let observation_count = observation_count.clone();
4940            move |_| {
4941                *observation_count.borrow_mut() += 1;
4942            }
4943        })
4944        .detach();
4945
4946        assert_eq!(
4947            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
4948                assert_eq!(global, &0.0);
4949                *global = 2.0;
4950                "Default update result"
4951            }),
4952            "Default update result"
4953        );
4954        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
4955        assert_eq!(*observation_count.borrow(), 1);
4956    }
4957
4958    #[crate::test(self)]
4959    fn test_dropping_subscribers(cx: &mut TestAppContext) {
4960        struct Model;
4961
4962        impl Entity for Model {
4963            type Event = ();
4964        }
4965
4966        let (_, root_view) = cx.add_window(|_| TestView::default());
4967        let observing_view = cx.add_view(&root_view, |_| TestView::default());
4968        let emitting_view = cx.add_view(&root_view, |_| TestView::default());
4969        let observing_model = cx.add_model(|_| Model);
4970        let observed_model = cx.add_model(|_| Model);
4971
4972        observing_view.update(cx, |_, cx| {
4973            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
4974            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4975        });
4976        observing_model.update(cx, |_, cx| {
4977            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4978        });
4979
4980        cx.update(|_| {
4981            drop(observing_view);
4982            drop(observing_model);
4983        });
4984
4985        emitting_view.update(cx, |_, cx| cx.emit(Default::default()));
4986        observed_model.update(cx, |_, cx| cx.emit(()));
4987    }
4988
4989    #[crate::test(self)]
4990    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
4991        let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
4992            drop(cx.subscribe(&cx.handle(), {
4993                move |this, _, _, _| this.events.push("dropped before flush".into())
4994            }));
4995            cx.subscribe(&cx.handle(), {
4996                move |this, _, _, _| this.events.push("before emit".into())
4997            })
4998            .detach();
4999            cx.emit("the event".into());
5000            cx.subscribe(&cx.handle(), {
5001                move |this, _, _, _| this.events.push("after emit".into())
5002            })
5003            .detach();
5004            TestView { events: Vec::new() }
5005        });
5006
5007        assert_eq!(view.read(cx).events, ["before emit"]);
5008    }
5009
5010    #[crate::test(self)]
5011    fn test_observe_and_notify_from_view(cx: &mut TestAppContext) {
5012        #[derive(Default)]
5013        struct Model {
5014            state: String,
5015        }
5016
5017        impl Entity for Model {
5018            type Event = ();
5019        }
5020
5021        let (_, view) = cx.add_window(|_| TestView::default());
5022        let model = cx.add_model(|_| Model {
5023            state: "old-state".into(),
5024        });
5025
5026        view.update(cx, |_, c| {
5027            c.observe(&model, |me, observed, cx| {
5028                me.events.push(observed.read(cx).state.clone())
5029            })
5030            .detach();
5031        });
5032
5033        model.update(cx, |model, cx| {
5034            model.state = "new-state".into();
5035            cx.notify();
5036        });
5037        view.read_with(cx, |view, _| assert_eq!(view.events, ["new-state"]));
5038    }
5039
5040    #[crate::test(self)]
5041    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
5042        let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
5043            drop(cx.observe(&cx.handle(), {
5044                move |this, _, _| this.events.push("dropped before flush".into())
5045            }));
5046            cx.observe(&cx.handle(), {
5047                move |this, _, _| this.events.push("before notify".into())
5048            })
5049            .detach();
5050            cx.notify();
5051            cx.observe(&cx.handle(), {
5052                move |this, _, _| this.events.push("after notify".into())
5053            })
5054            .detach();
5055            TestView { events: Vec::new() }
5056        });
5057
5058        assert_eq!(view.read(cx).events, ["before notify"]);
5059    }
5060
5061    #[crate::test(self)]
5062    fn test_notify_and_drop_observe_subscription_in_same_update_cycle(cx: &mut TestAppContext) {
5063        struct Model;
5064        impl Entity for Model {
5065            type Event = ();
5066        }
5067
5068        let model = cx.add_model(|_| Model);
5069        let (_, view) = cx.add_window(|_| TestView::default());
5070
5071        view.update(cx, |_, cx| {
5072            model.update(cx, |_, cx| cx.notify());
5073            drop(cx.observe(&model, move |this, _, _| {
5074                this.events.push("model notified".into());
5075            }));
5076            model.update(cx, |_, cx| cx.notify());
5077        });
5078
5079        for _ in 0..3 {
5080            model.update(cx, |_, cx| cx.notify());
5081        }
5082        view.read_with(cx, |view, _| assert_eq!(view.events, Vec::<&str>::new()));
5083    }
5084
5085    #[crate::test(self)]
5086    fn test_dropping_observers(cx: &mut TestAppContext) {
5087        struct Model;
5088
5089        impl Entity for Model {
5090            type Event = ();
5091        }
5092
5093        let (_, root_view) = cx.add_window(|_| TestView::default());
5094        let observing_view = cx.add_view(&root_view, |_| TestView::default());
5095        let observing_model = cx.add_model(|_| Model);
5096        let observed_model = cx.add_model(|_| Model);
5097
5098        observing_view.update(cx, |_, cx| {
5099            cx.observe(&observed_model, |_, _, _| {}).detach();
5100        });
5101        observing_model.update(cx, |_, cx| {
5102            cx.observe(&observed_model, |_, _, _| {}).detach();
5103        });
5104
5105        cx.update(|_| {
5106            drop(observing_view);
5107            drop(observing_model);
5108        });
5109
5110        observed_model.update(cx, |_, cx| cx.notify());
5111    }
5112
5113    #[crate::test(self)]
5114    fn test_dropping_subscriptions_during_callback(cx: &mut TestAppContext) {
5115        struct Model;
5116
5117        impl Entity for Model {
5118            type Event = u64;
5119        }
5120
5121        // Events
5122        let observing_model = cx.add_model(|_| Model);
5123        let observed_model = cx.add_model(|_| Model);
5124
5125        let events = Rc::new(RefCell::new(Vec::new()));
5126
5127        observing_model.update(cx, |_, cx| {
5128            let events = events.clone();
5129            let subscription = Rc::new(RefCell::new(None));
5130            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
5131                let subscription = subscription.clone();
5132                move |_, _, e, _| {
5133                    subscription.borrow_mut().take();
5134                    events.borrow_mut().push(*e);
5135                }
5136            }));
5137        });
5138
5139        observed_model.update(cx, |_, cx| {
5140            cx.emit(1);
5141            cx.emit(2);
5142        });
5143
5144        assert_eq!(*events.borrow(), [1]);
5145
5146        // Global Events
5147        #[derive(Clone, Debug, Eq, PartialEq)]
5148        struct GlobalEvent(u64);
5149
5150        let events = Rc::new(RefCell::new(Vec::new()));
5151
5152        {
5153            let events = events.clone();
5154            let subscription = Rc::new(RefCell::new(None));
5155            *subscription.borrow_mut() = Some(cx.subscribe_global({
5156                let subscription = subscription.clone();
5157                move |e: &GlobalEvent, _| {
5158                    subscription.borrow_mut().take();
5159                    events.borrow_mut().push(e.clone());
5160                }
5161            }));
5162        }
5163
5164        cx.update(|cx| {
5165            cx.emit_global(GlobalEvent(1));
5166            cx.emit_global(GlobalEvent(2));
5167        });
5168
5169        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
5170
5171        // Model Observation
5172        let observing_model = cx.add_model(|_| Model);
5173        let observed_model = cx.add_model(|_| Model);
5174
5175        let observation_count = Rc::new(RefCell::new(0));
5176
5177        observing_model.update(cx, |_, cx| {
5178            let observation_count = observation_count.clone();
5179            let subscription = Rc::new(RefCell::new(None));
5180            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
5181                let subscription = subscription.clone();
5182                move |_, _, _| {
5183                    subscription.borrow_mut().take();
5184                    *observation_count.borrow_mut() += 1;
5185                }
5186            }));
5187        });
5188
5189        observed_model.update(cx, |_, cx| {
5190            cx.notify();
5191        });
5192
5193        observed_model.update(cx, |_, cx| {
5194            cx.notify();
5195        });
5196
5197        assert_eq!(*observation_count.borrow(), 1);
5198
5199        // View Observation
5200        struct View;
5201
5202        impl Entity for View {
5203            type Event = ();
5204        }
5205
5206        impl super::View for View {
5207            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5208                Empty::new().into_any()
5209            }
5210
5211            fn ui_name() -> &'static str {
5212                "View"
5213            }
5214        }
5215
5216        let (_, root_view) = cx.add_window(|_| View);
5217        let observing_view = cx.add_view(&root_view, |_| View);
5218        let observed_view = cx.add_view(&root_view, |_| View);
5219
5220        let observation_count = Rc::new(RefCell::new(0));
5221        observing_view.update(cx, |_, cx| {
5222            let observation_count = observation_count.clone();
5223            let subscription = Rc::new(RefCell::new(None));
5224            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
5225                let subscription = subscription.clone();
5226                move |_, _, _| {
5227                    subscription.borrow_mut().take();
5228                    *observation_count.borrow_mut() += 1;
5229                }
5230            }));
5231        });
5232
5233        observed_view.update(cx, |_, cx| {
5234            cx.notify();
5235        });
5236
5237        observed_view.update(cx, |_, cx| {
5238            cx.notify();
5239        });
5240
5241        assert_eq!(*observation_count.borrow(), 1);
5242
5243        // Global Observation
5244        let observation_count = Rc::new(RefCell::new(0));
5245        let subscription = Rc::new(RefCell::new(None));
5246        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
5247            let observation_count = observation_count.clone();
5248            let subscription = subscription.clone();
5249            move |_| {
5250                subscription.borrow_mut().take();
5251                *observation_count.borrow_mut() += 1;
5252            }
5253        }));
5254
5255        cx.update(|cx| {
5256            cx.default_global::<()>();
5257            cx.set_global(());
5258        });
5259        assert_eq!(*observation_count.borrow(), 1);
5260    }
5261
5262    #[crate::test(self)]
5263    fn test_focus(cx: &mut TestAppContext) {
5264        struct View {
5265            name: String,
5266            events: Arc<Mutex<Vec<String>>>,
5267        }
5268
5269        impl Entity for View {
5270            type Event = ();
5271        }
5272
5273        impl super::View for View {
5274            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5275                Empty::new().into_any()
5276            }
5277
5278            fn ui_name() -> &'static str {
5279                "View"
5280            }
5281
5282            fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
5283                if cx.handle().id() == focused.id() {
5284                    self.events.lock().push(format!("{} focused", &self.name));
5285                }
5286            }
5287
5288            fn focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
5289                if cx.handle().id() == blurred.id() {
5290                    self.events.lock().push(format!("{} blurred", &self.name));
5291                }
5292            }
5293        }
5294
5295        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
5296        let (window_id, view_1) = cx.add_window(|_| View {
5297            events: view_events.clone(),
5298            name: "view 1".to_string(),
5299        });
5300        let view_2 = cx.add_view(&view_1, |_| View {
5301            events: view_events.clone(),
5302            name: "view 2".to_string(),
5303        });
5304
5305        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
5306        view_1.update(cx, |_, cx| {
5307            cx.observe_focus(&view_2, {
5308                let observed_events = observed_events.clone();
5309                move |this, view, focused, cx| {
5310                    let label = if focused { "focus" } else { "blur" };
5311                    observed_events.lock().push(format!(
5312                        "{} observed {}'s {}",
5313                        this.name,
5314                        view.read(cx).name,
5315                        label
5316                    ))
5317                }
5318            })
5319            .detach();
5320        });
5321        view_2.update(cx, |_, cx| {
5322            cx.observe_focus(&view_1, {
5323                let observed_events = observed_events.clone();
5324                move |this, view, focused, cx| {
5325                    let label = if focused { "focus" } else { "blur" };
5326                    observed_events.lock().push(format!(
5327                        "{} observed {}'s {}",
5328                        this.name,
5329                        view.read(cx).name,
5330                        label
5331                    ))
5332                }
5333            })
5334            .detach();
5335        });
5336        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5337        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5338
5339        view_1.update(cx, |_, cx| {
5340            // Ensure focus events are sent for all intermediate focuses
5341            cx.focus(&view_2);
5342            cx.focus(&view_1);
5343            cx.focus(&view_2);
5344        });
5345
5346        cx.read_window(window_id, |cx| {
5347            assert!(cx.is_child_focused(&view_1));
5348            assert!(!cx.is_child_focused(&view_2));
5349        });
5350        assert_eq!(
5351            mem::take(&mut *view_events.lock()),
5352            [
5353                "view 1 blurred",
5354                "view 2 focused",
5355                "view 2 blurred",
5356                "view 1 focused",
5357                "view 1 blurred",
5358                "view 2 focused"
5359            ],
5360        );
5361        assert_eq!(
5362            mem::take(&mut *observed_events.lock()),
5363            [
5364                "view 2 observed view 1's blur",
5365                "view 1 observed view 2's focus",
5366                "view 1 observed view 2's blur",
5367                "view 2 observed view 1's focus",
5368                "view 2 observed view 1's blur",
5369                "view 1 observed view 2's focus"
5370            ]
5371        );
5372
5373        view_1.update(cx, |_, cx| cx.focus(&view_1));
5374        cx.read_window(window_id, |cx| {
5375            assert!(!cx.is_child_focused(&view_1));
5376            assert!(!cx.is_child_focused(&view_2));
5377        });
5378        assert_eq!(
5379            mem::take(&mut *view_events.lock()),
5380            ["view 2 blurred", "view 1 focused"],
5381        );
5382        assert_eq!(
5383            mem::take(&mut *observed_events.lock()),
5384            [
5385                "view 1 observed view 2's blur",
5386                "view 2 observed view 1's focus"
5387            ]
5388        );
5389
5390        view_1.update(cx, |_, cx| cx.focus(&view_2));
5391        assert_eq!(
5392            mem::take(&mut *view_events.lock()),
5393            ["view 1 blurred", "view 2 focused"],
5394        );
5395        assert_eq!(
5396            mem::take(&mut *observed_events.lock()),
5397            [
5398                "view 2 observed view 1's blur",
5399                "view 1 observed view 2's focus"
5400            ]
5401        );
5402
5403        view_1.update(cx, |_, _| drop(view_2));
5404        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5405        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5406    }
5407
5408    #[crate::test(self)]
5409    fn test_deserialize_actions(cx: &mut AppContext) {
5410        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
5411        pub struct ComplexAction {
5412            arg: String,
5413            count: usize,
5414        }
5415
5416        actions!(test::something, [SimpleAction]);
5417        impl_actions!(test::something, [ComplexAction]);
5418
5419        cx.add_global_action(move |_: &SimpleAction, _: &mut AppContext| {});
5420        cx.add_global_action(move |_: &ComplexAction, _: &mut AppContext| {});
5421
5422        let action1 = cx
5423            .deserialize_action(
5424                "test::something::ComplexAction",
5425                Some(r#"{"arg": "a", "count": 5}"#),
5426            )
5427            .unwrap();
5428        let action2 = cx
5429            .deserialize_action("test::something::SimpleAction", None)
5430            .unwrap();
5431        assert_eq!(
5432            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
5433            &ComplexAction {
5434                arg: "a".to_string(),
5435                count: 5,
5436            }
5437        );
5438        assert_eq!(
5439            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
5440            &SimpleAction
5441        );
5442    }
5443
5444    #[crate::test(self)]
5445    fn test_dispatch_action(cx: &mut AppContext) {
5446        struct ViewA {
5447            id: usize,
5448        }
5449
5450        impl Entity for ViewA {
5451            type Event = ();
5452        }
5453
5454        impl View for ViewA {
5455            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5456                Empty::new().into_any()
5457            }
5458
5459            fn ui_name() -> &'static str {
5460                "View"
5461            }
5462        }
5463
5464        struct ViewB {
5465            id: usize,
5466        }
5467
5468        impl Entity for ViewB {
5469            type Event = ();
5470        }
5471
5472        impl View for ViewB {
5473            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5474                Empty::new().into_any()
5475            }
5476
5477            fn ui_name() -> &'static str {
5478                "View"
5479            }
5480        }
5481
5482        #[derive(Clone, Default, Deserialize, PartialEq)]
5483        pub struct Action(pub String);
5484
5485        impl_actions!(test, [Action]);
5486
5487        let actions = Rc::new(RefCell::new(Vec::new()));
5488
5489        cx.add_global_action({
5490            let actions = actions.clone();
5491            move |_: &Action, _: &mut AppContext| {
5492                actions.borrow_mut().push("global".to_string());
5493            }
5494        });
5495
5496        cx.add_action({
5497            let actions = actions.clone();
5498            move |view: &mut ViewA, action: &Action, cx| {
5499                assert_eq!(action.0, "bar");
5500                cx.propagate_action();
5501                actions.borrow_mut().push(format!("{} a", view.id));
5502            }
5503        });
5504
5505        cx.add_action({
5506            let actions = actions.clone();
5507            move |view: &mut ViewA, _: &Action, cx| {
5508                if view.id != 1 {
5509                    cx.add_view(|cx| {
5510                        cx.propagate_action(); // Still works on a nested ViewContext
5511                        ViewB { id: 5 }
5512                    });
5513                }
5514                actions.borrow_mut().push(format!("{} b", view.id));
5515            }
5516        });
5517
5518        cx.add_action({
5519            let actions = actions.clone();
5520            move |view: &mut ViewB, _: &Action, cx| {
5521                cx.propagate_action();
5522                actions.borrow_mut().push(format!("{} c", view.id));
5523            }
5524        });
5525
5526        cx.add_action({
5527            let actions = actions.clone();
5528            move |view: &mut ViewB, _: &Action, cx| {
5529                cx.propagate_action();
5530                actions.borrow_mut().push(format!("{} d", view.id));
5531            }
5532        });
5533
5534        cx.capture_action({
5535            let actions = actions.clone();
5536            move |view: &mut ViewA, _: &Action, cx| {
5537                cx.propagate_action();
5538                actions.borrow_mut().push(format!("{} capture", view.id));
5539            }
5540        });
5541
5542        let observed_actions = Rc::new(RefCell::new(Vec::new()));
5543        cx.observe_actions({
5544            let observed_actions = observed_actions.clone();
5545            move |action_id, _| observed_actions.borrow_mut().push(action_id)
5546        })
5547        .detach();
5548
5549        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
5550        let view_2 = cx.add_view(&view_1, |_| ViewB { id: 2 });
5551        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
5552        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
5553
5554        cx.update_window(window_id, |cx| {
5555            cx.handle_dispatch_action_from_effect(Some(view_4.id()), &Action("bar".to_string()))
5556        });
5557
5558        assert_eq!(
5559            *actions.borrow(),
5560            vec![
5561                "1 capture",
5562                "3 capture",
5563                "4 d",
5564                "4 c",
5565                "3 b",
5566                "3 a",
5567                "2 d",
5568                "2 c",
5569                "1 b"
5570            ]
5571        );
5572        assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
5573
5574        // Remove view_1, which doesn't propagate the action
5575
5576        let (window_id, view_2) = cx.add_window(Default::default(), |_| ViewB { id: 2 });
5577        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
5578        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
5579
5580        actions.borrow_mut().clear();
5581        cx.update_window(window_id, |cx| {
5582            cx.handle_dispatch_action_from_effect(Some(view_4.id()), &Action("bar".to_string()))
5583        });
5584
5585        assert_eq!(
5586            *actions.borrow(),
5587            vec![
5588                "3 capture",
5589                "4 d",
5590                "4 c",
5591                "3 b",
5592                "3 a",
5593                "2 d",
5594                "2 c",
5595                "global"
5596            ]
5597        );
5598        assert_eq!(
5599            *observed_actions.borrow(),
5600            [Action::default().id(), Action::default().id()]
5601        );
5602    }
5603
5604    #[crate::test(self)]
5605    fn test_dispatch_keystroke(cx: &mut AppContext) {
5606        #[derive(Clone, Deserialize, PartialEq)]
5607        pub struct Action(String);
5608
5609        impl_actions!(test, [Action]);
5610
5611        struct View {
5612            id: usize,
5613            keymap_context: KeymapContext,
5614        }
5615
5616        impl Entity for View {
5617            type Event = ();
5618        }
5619
5620        impl super::View for View {
5621            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5622                Empty::new().into_any()
5623            }
5624
5625            fn ui_name() -> &'static str {
5626                "View"
5627            }
5628
5629            fn keymap_context(&self, _: &AppContext) -> KeymapContext {
5630                self.keymap_context.clone()
5631            }
5632        }
5633
5634        impl View {
5635            fn new(id: usize) -> Self {
5636                View {
5637                    id,
5638                    keymap_context: KeymapContext::default(),
5639                }
5640            }
5641        }
5642
5643        let mut view_1 = View::new(1);
5644        let mut view_2 = View::new(2);
5645        let mut view_3 = View::new(3);
5646        view_1.keymap_context.add_identifier("a");
5647        view_2.keymap_context.add_identifier("a");
5648        view_2.keymap_context.add_identifier("b");
5649        view_3.keymap_context.add_identifier("a");
5650        view_3.keymap_context.add_identifier("b");
5651        view_3.keymap_context.add_identifier("c");
5652
5653        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
5654        let view_2 = cx.add_view(&view_1, |_| view_2);
5655        let _view_3 = cx.add_view(&view_2, |cx| {
5656            cx.focus_self();
5657            view_3
5658        });
5659
5660        // This binding only dispatches an action on view 2 because that view will have
5661        // "a" and "b" in its context, but not "c".
5662        cx.add_bindings(vec![Binding::new(
5663            "a",
5664            Action("a".to_string()),
5665            Some("a && b && !c"),
5666        )]);
5667
5668        cx.add_bindings(vec![Binding::new("b", Action("b".to_string()), None)]);
5669
5670        // This binding only dispatches an action on views 2 and 3, because they have
5671        // a parent view with a in its context
5672        cx.add_bindings(vec![Binding::new(
5673            "c",
5674            Action("c".to_string()),
5675            Some("b > c"),
5676        )]);
5677
5678        // This binding only dispatches an action on view 2, because they have
5679        // a parent view with a in its context
5680        cx.add_bindings(vec![Binding::new(
5681            "d",
5682            Action("d".to_string()),
5683            Some("a && !b > b"),
5684        )]);
5685
5686        let actions = Rc::new(RefCell::new(Vec::new()));
5687        cx.add_action({
5688            let actions = actions.clone();
5689            move |view: &mut View, action: &Action, cx| {
5690                actions
5691                    .borrow_mut()
5692                    .push(format!("{} {}", view.id, action.0));
5693
5694                if action.0 == "b" {
5695                    cx.propagate_action();
5696                }
5697            }
5698        });
5699
5700        cx.add_global_action({
5701            let actions = actions.clone();
5702            move |action: &Action, _| {
5703                actions.borrow_mut().push(format!("global {}", action.0));
5704            }
5705        });
5706
5707        cx.update_window(window_id, |cx| {
5708            cx.dispatch_keystroke(&Keystroke::parse("a").unwrap())
5709        });
5710        assert_eq!(&*actions.borrow(), &["2 a"]);
5711        actions.borrow_mut().clear();
5712
5713        cx.update_window(window_id, |cx| {
5714            cx.dispatch_keystroke(&Keystroke::parse("b").unwrap());
5715        });
5716
5717        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
5718        actions.borrow_mut().clear();
5719
5720        cx.update_window(window_id, |cx| {
5721            cx.dispatch_keystroke(&Keystroke::parse("c").unwrap());
5722        });
5723        assert_eq!(&*actions.borrow(), &["3 c"]);
5724        actions.borrow_mut().clear();
5725
5726        cx.update_window(window_id, |cx| {
5727            cx.dispatch_keystroke(&Keystroke::parse("d").unwrap());
5728        });
5729        assert_eq!(&*actions.borrow(), &["2 d"]);
5730        actions.borrow_mut().clear();
5731    }
5732
5733    #[crate::test(self)]
5734    fn test_keystrokes_for_action(cx: &mut AppContext) {
5735        actions!(test, [Action1, Action2, GlobalAction]);
5736
5737        struct View1 {}
5738        struct View2 {}
5739
5740        impl Entity for View1 {
5741            type Event = ();
5742        }
5743        impl Entity for View2 {
5744            type Event = ();
5745        }
5746
5747        impl super::View for View1 {
5748            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5749                Empty::new().into_any()
5750            }
5751            fn ui_name() -> &'static str {
5752                "View1"
5753            }
5754        }
5755        impl super::View for View2 {
5756            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5757                Empty::new().into_any()
5758            }
5759            fn ui_name() -> &'static str {
5760                "View2"
5761            }
5762        }
5763
5764        let (window_id, view_1) = cx.add_window(Default::default(), |_| View1 {});
5765        let view_2 = cx.add_view(&view_1, |cx| {
5766            cx.focus_self();
5767            View2 {}
5768        });
5769
5770        cx.add_action(|_: &mut View1, _: &Action1, _cx| {});
5771        cx.add_action(|_: &mut View2, _: &Action2, _cx| {});
5772        cx.add_global_action(|_: &GlobalAction, _| {});
5773
5774        cx.add_bindings(vec![
5775            Binding::new("a", Action1, Some("View1")),
5776            Binding::new("b", Action2, Some("View1 > View2")),
5777            Binding::new("c", GlobalAction, Some("View3")), // View 3 does not exist
5778        ]);
5779
5780        cx.update_window(window_id, |cx| {
5781            // Sanity check
5782            assert_eq!(
5783                cx.keystrokes_for_action(view_1.id(), &Action1)
5784                    .unwrap()
5785                    .as_slice(),
5786                &[Keystroke::parse("a").unwrap()]
5787            );
5788            assert_eq!(
5789                cx.keystrokes_for_action(view_2.id(), &Action2)
5790                    .unwrap()
5791                    .as_slice(),
5792                &[Keystroke::parse("b").unwrap()]
5793            );
5794
5795            // The 'a' keystroke propagates up the view tree from view_2
5796            // to view_1. The action, Action1, is handled by view_1.
5797            assert_eq!(
5798                cx.keystrokes_for_action(view_2.id(), &Action1)
5799                    .unwrap()
5800                    .as_slice(),
5801                &[Keystroke::parse("a").unwrap()]
5802            );
5803
5804            // Actions that are handled below the current view don't have bindings
5805            assert_eq!(cx.keystrokes_for_action(view_1.id(), &Action2), None);
5806
5807            // Actions that are handled in other branches of the tree should not have a binding
5808            assert_eq!(cx.keystrokes_for_action(view_2.id(), &GlobalAction), None);
5809
5810            // Check that global actions do not have a binding, even if a binding does exist in another view
5811            assert_eq!(
5812                &available_actions(view_1.id(), cx),
5813                &[
5814                    ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
5815                    ("test::GlobalAction", vec![])
5816                ],
5817            );
5818
5819            // Check that view 1 actions and bindings are available even when called from view 2
5820            assert_eq!(
5821                &available_actions(view_2.id(), cx),
5822                &[
5823                    ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
5824                    ("test::Action2", vec![Keystroke::parse("b").unwrap()]),
5825                    ("test::GlobalAction", vec![]),
5826                ],
5827            );
5828        });
5829
5830        // Produces a list of actions and key bindings
5831        fn available_actions(
5832            view_id: usize,
5833            cx: &WindowContext,
5834        ) -> Vec<(&'static str, Vec<Keystroke>)> {
5835            cx.available_actions(view_id)
5836                .map(|(action_name, _, bindings)| {
5837                    (
5838                        action_name,
5839                        bindings
5840                            .iter()
5841                            .map(|binding| binding.keystrokes()[0].clone())
5842                            .collect::<Vec<_>>(),
5843                    )
5844                })
5845                .sorted_by(|(name1, _), (name2, _)| name1.cmp(name2))
5846                .collect()
5847        }
5848    }
5849
5850    #[crate::test(self)]
5851    async fn test_model_condition(cx: &mut TestAppContext) {
5852        struct Counter(usize);
5853
5854        impl super::Entity for Counter {
5855            type Event = ();
5856        }
5857
5858        impl Counter {
5859            fn inc(&mut self, cx: &mut ModelContext<Self>) {
5860                self.0 += 1;
5861                cx.notify();
5862            }
5863        }
5864
5865        let model = cx.add_model(|_| Counter(0));
5866
5867        let condition1 = model.condition(cx, |model, _| model.0 == 2);
5868        let condition2 = model.condition(cx, |model, _| model.0 == 3);
5869        smol::pin!(condition1, condition2);
5870
5871        model.update(cx, |model, cx| model.inc(cx));
5872        assert_eq!(poll_once(&mut condition1).await, None);
5873        assert_eq!(poll_once(&mut condition2).await, None);
5874
5875        model.update(cx, |model, cx| model.inc(cx));
5876        assert_eq!(poll_once(&mut condition1).await, Some(()));
5877        assert_eq!(poll_once(&mut condition2).await, None);
5878
5879        model.update(cx, |model, cx| model.inc(cx));
5880        assert_eq!(poll_once(&mut condition2).await, Some(()));
5881
5882        model.update(cx, |_, cx| cx.notify());
5883    }
5884
5885    #[crate::test(self)]
5886    #[should_panic]
5887    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
5888        struct Model;
5889
5890        impl super::Entity for Model {
5891            type Event = ();
5892        }
5893
5894        let model = cx.add_model(|_| Model);
5895        model.condition(cx, |_, _| false).await;
5896    }
5897
5898    #[crate::test(self)]
5899    #[should_panic(expected = "model dropped with pending condition")]
5900    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
5901        struct Model;
5902
5903        impl super::Entity for Model {
5904            type Event = ();
5905        }
5906
5907        let model = cx.add_model(|_| Model);
5908        let condition = model.condition(cx, |_, _| false);
5909        cx.update(|_| drop(model));
5910        condition.await;
5911    }
5912
5913    #[crate::test(self)]
5914    async fn test_view_condition(cx: &mut TestAppContext) {
5915        struct Counter(usize);
5916
5917        impl super::Entity for Counter {
5918            type Event = ();
5919        }
5920
5921        impl super::View for Counter {
5922            fn ui_name() -> &'static str {
5923                "test view"
5924            }
5925
5926            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5927                Empty::new().into_any()
5928            }
5929        }
5930
5931        impl Counter {
5932            fn inc(&mut self, cx: &mut ViewContext<Self>) {
5933                self.0 += 1;
5934                cx.notify();
5935            }
5936        }
5937
5938        let (_, view) = cx.add_window(|_| Counter(0));
5939
5940        let condition1 = view.condition(cx, |view, _| view.0 == 2);
5941        let condition2 = view.condition(cx, |view, _| view.0 == 3);
5942        smol::pin!(condition1, condition2);
5943
5944        view.update(cx, |view, cx| view.inc(cx));
5945        assert_eq!(poll_once(&mut condition1).await, None);
5946        assert_eq!(poll_once(&mut condition2).await, None);
5947
5948        view.update(cx, |view, cx| view.inc(cx));
5949        assert_eq!(poll_once(&mut condition1).await, Some(()));
5950        assert_eq!(poll_once(&mut condition2).await, None);
5951
5952        view.update(cx, |view, cx| view.inc(cx));
5953        assert_eq!(poll_once(&mut condition2).await, Some(()));
5954        view.update(cx, |_, cx| cx.notify());
5955    }
5956
5957    #[crate::test(self)]
5958    #[should_panic]
5959    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
5960        let (_, view) = cx.add_window(|_| TestView::default());
5961        view.condition(cx, |_, _| false).await;
5962    }
5963
5964    #[crate::test(self)]
5965    #[should_panic(expected = "view dropped with pending condition")]
5966    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
5967        let (_, root_view) = cx.add_window(|_| TestView::default());
5968        let view = cx.add_view(&root_view, |_| TestView::default());
5969
5970        let condition = view.condition(cx, |_, _| false);
5971        cx.update(|_| drop(view));
5972        condition.await;
5973    }
5974
5975    #[crate::test(self)]
5976    fn test_refresh_windows(cx: &mut AppContext) {
5977        struct View(usize);
5978
5979        impl super::Entity for View {
5980            type Event = ();
5981        }
5982
5983        impl super::View for View {
5984            fn ui_name() -> &'static str {
5985                "test view"
5986            }
5987
5988            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5989                Empty::new().into_any_named(format!("render count: {}", post_inc(&mut self.0)))
5990            }
5991        }
5992
5993        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
5994        cx.update_window(window_id, |cx| {
5995            assert_eq!(
5996                cx.window.rendered_views[&root_view.id()].name(),
5997                Some("render count: 0")
5998            );
5999        });
6000
6001        let view = cx.add_view(&root_view, |cx| {
6002            cx.refresh_windows();
6003            View(0)
6004        });
6005
6006        cx.update_window(window_id, |cx| {
6007            assert_eq!(
6008                cx.window.rendered_views[&root_view.id()].name(),
6009                Some("render count: 1")
6010            );
6011            assert_eq!(
6012                cx.window.rendered_views[&view.id()].name(),
6013                Some("render count: 0")
6014            );
6015        });
6016
6017        cx.update(|cx| cx.refresh_windows());
6018
6019        cx.update_window(window_id, |cx| {
6020            assert_eq!(
6021                cx.window.rendered_views[&root_view.id()].name(),
6022                Some("render count: 2")
6023            );
6024            assert_eq!(
6025                cx.window.rendered_views[&view.id()].name(),
6026                Some("render count: 1")
6027            );
6028        });
6029
6030        cx.update(|cx| {
6031            cx.refresh_windows();
6032            drop(view);
6033        });
6034
6035        cx.update_window(window_id, |cx| {
6036            assert_eq!(
6037                cx.window.rendered_views[&root_view.id()].name(),
6038                Some("render count: 3")
6039            );
6040            assert_eq!(cx.window.rendered_views.len(), 1);
6041        });
6042    }
6043
6044    #[crate::test(self)]
6045    async fn test_labeled_tasks(cx: &mut TestAppContext) {
6046        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6047        let (mut sender, mut reciever) = postage::oneshot::channel::<()>();
6048        let task = cx
6049            .update(|cx| cx.spawn_labeled("Test Label", |_| async move { reciever.recv().await }));
6050
6051        assert_eq!(
6052            Some("Test Label"),
6053            cx.update(|cx| cx.active_labeled_tasks().next())
6054        );
6055        sender
6056            .send(())
6057            .await
6058            .expect("Could not send message to complete task");
6059        task.await;
6060
6061        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6062    }
6063
6064    #[crate::test(self)]
6065    async fn test_window_activation(cx: &mut TestAppContext) {
6066        struct View(&'static str);
6067
6068        impl super::Entity for View {
6069            type Event = ();
6070        }
6071
6072        impl super::View for View {
6073            fn ui_name() -> &'static str {
6074                "test view"
6075            }
6076
6077            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6078                Empty::new().into_any()
6079            }
6080        }
6081
6082        let events = Rc::new(RefCell::new(Vec::new()));
6083        let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6084            cx.observe_window_activation({
6085                let events = events.clone();
6086                move |this, active, _| events.borrow_mut().push((this.0, active))
6087            })
6088            .detach();
6089            View("window 1")
6090        });
6091        assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
6092
6093        let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6094            cx.observe_window_activation({
6095                let events = events.clone();
6096                move |this, active, _| events.borrow_mut().push((this.0, active))
6097            })
6098            .detach();
6099            View("window 2")
6100        });
6101        assert_eq!(
6102            mem::take(&mut *events.borrow_mut()),
6103            [("window 1", false), ("window 2", true)]
6104        );
6105
6106        let (window_3, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6107            cx.observe_window_activation({
6108                let events = events.clone();
6109                move |this, active, _| events.borrow_mut().push((this.0, active))
6110            })
6111            .detach();
6112            View("window 3")
6113        });
6114        assert_eq!(
6115            mem::take(&mut *events.borrow_mut()),
6116            [("window 2", false), ("window 3", true)]
6117        );
6118
6119        cx.simulate_window_activation(Some(window_2));
6120        assert_eq!(
6121            mem::take(&mut *events.borrow_mut()),
6122            [("window 3", false), ("window 2", true)]
6123        );
6124
6125        cx.simulate_window_activation(Some(window_1));
6126        assert_eq!(
6127            mem::take(&mut *events.borrow_mut()),
6128            [("window 2", false), ("window 1", true)]
6129        );
6130
6131        cx.simulate_window_activation(Some(window_3));
6132        assert_eq!(
6133            mem::take(&mut *events.borrow_mut()),
6134            [("window 1", false), ("window 3", true)]
6135        );
6136
6137        cx.simulate_window_activation(Some(window_3));
6138        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6139    }
6140
6141    #[crate::test(self)]
6142    fn test_child_view(cx: &mut TestAppContext) {
6143        struct Child {
6144            rendered: Rc<Cell<bool>>,
6145            dropped: Rc<Cell<bool>>,
6146        }
6147
6148        impl super::Entity for Child {
6149            type Event = ();
6150        }
6151
6152        impl super::View for Child {
6153            fn ui_name() -> &'static str {
6154                "child view"
6155            }
6156
6157            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6158                self.rendered.set(true);
6159                Empty::new().into_any()
6160            }
6161        }
6162
6163        impl Drop for Child {
6164            fn drop(&mut self) {
6165                self.dropped.set(true);
6166            }
6167        }
6168
6169        struct Parent {
6170            child: Option<ViewHandle<Child>>,
6171        }
6172
6173        impl super::Entity for Parent {
6174            type Event = ();
6175        }
6176
6177        impl super::View for Parent {
6178            fn ui_name() -> &'static str {
6179                "parent view"
6180            }
6181
6182            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
6183                if let Some(child) = self.child.as_ref() {
6184                    ChildView::new(child, cx).into_any()
6185                } else {
6186                    Empty::new().into_any()
6187                }
6188            }
6189        }
6190
6191        let child_rendered = Rc::new(Cell::new(false));
6192        let child_dropped = Rc::new(Cell::new(false));
6193        let (_, root_view) = cx.add_window(|cx| Parent {
6194            child: Some(cx.add_view(|_| Child {
6195                rendered: child_rendered.clone(),
6196                dropped: child_dropped.clone(),
6197            })),
6198        });
6199        assert!(child_rendered.take());
6200        assert!(!child_dropped.take());
6201
6202        root_view.update(cx, |view, cx| {
6203            view.child.take();
6204            cx.notify();
6205        });
6206        assert!(!child_rendered.take());
6207        assert!(child_dropped.take());
6208    }
6209
6210    #[derive(Default)]
6211    struct TestView {
6212        events: Vec<String>,
6213    }
6214
6215    impl Entity for TestView {
6216        type Event = String;
6217    }
6218
6219    impl View for TestView {
6220        fn ui_name() -> &'static str {
6221            "TestView"
6222        }
6223
6224        fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6225            Empty::new().into_any()
6226        }
6227    }
6228}