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(WeakViewHandle<V>, AsyncAppContext) -> Fut,
3266        Fut: 'static + Future<Output = S>,
3267        S: 'static,
3268    {
3269        let handle = self.weak_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(WeakViewHandle<V>, AsyncAppContext) -> Fut,
3277        Fut: 'static + Future<Output = S>,
3278        S: 'static,
3279    {
3280        let handle = self.weak_handle();
3281        self.window_context.spawn(|cx| f(handle, cx))
3282    }
3283
3284    pub fn mouse_state<Tag: 'static>(&self, region_id: usize) -> MouseState {
3285        let region_id = MouseRegionId::new::<Tag>(self.view_id, region_id);
3286        MouseState {
3287            hovered: self.window.hovered_region_ids.contains(&region_id),
3288            clicked: self
3289                .window
3290                .clicked_region_ids
3291                .get(&region_id)
3292                .and_then(|_| self.window.clicked_button),
3293            accessed_hovered: false,
3294            accessed_clicked: false,
3295        }
3296    }
3297
3298    pub fn element_state<Tag: 'static, T: 'static>(
3299        &mut self,
3300        element_id: usize,
3301        initial: T,
3302    ) -> ElementStateHandle<T> {
3303        let id = ElementStateId {
3304            view_id: self.view_id(),
3305            element_id,
3306            tag: TypeId::of::<Tag>(),
3307        };
3308        self.element_states
3309            .entry(id)
3310            .or_insert_with(|| Box::new(initial));
3311        ElementStateHandle::new(id, self.frame_count, &self.ref_counts)
3312    }
3313
3314    pub fn default_element_state<Tag: 'static, T: 'static + Default>(
3315        &mut self,
3316        element_id: usize,
3317    ) -> ElementStateHandle<T> {
3318        self.element_state::<Tag, T>(element_id, T::default())
3319    }
3320}
3321
3322impl<V> BorrowAppContext for ViewContext<'_, '_, V> {
3323    fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
3324        BorrowAppContext::read_with(&*self.window_context, f)
3325    }
3326
3327    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
3328        BorrowAppContext::update(&mut *self.window_context, f)
3329    }
3330}
3331
3332impl<V> BorrowWindowContext for ViewContext<'_, '_, V> {
3333    type ReturnValue<T> = T;
3334
3335    fn read_with<T, F: FnOnce(&WindowContext) -> T>(&self, window_id: usize, f: F) -> T {
3336        BorrowWindowContext::read_with(&*self.window_context, window_id, f)
3337    }
3338
3339    fn update<T, F: FnOnce(&mut WindowContext) -> T>(&mut self, window_id: usize, f: F) -> T {
3340        BorrowWindowContext::update(&mut *self.window_context, window_id, f)
3341    }
3342}
3343
3344pub struct EventContext<'a, 'b, 'c, V: View> {
3345    view_context: &'c mut ViewContext<'a, 'b, V>,
3346    pub(crate) handled: bool,
3347}
3348
3349impl<'a, 'b, 'c, V: View> EventContext<'a, 'b, 'c, V> {
3350    pub(crate) fn new(view_context: &'c mut ViewContext<'a, 'b, V>) -> Self {
3351        EventContext {
3352            view_context,
3353            handled: true,
3354        }
3355    }
3356
3357    pub fn propagate_event(&mut self) {
3358        self.handled = false;
3359    }
3360}
3361
3362impl<'a, 'b, 'c, V: View> Deref for EventContext<'a, 'b, 'c, V> {
3363    type Target = ViewContext<'a, 'b, V>;
3364
3365    fn deref(&self) -> &Self::Target {
3366        &self.view_context
3367    }
3368}
3369
3370impl<V: View> DerefMut for EventContext<'_, '_, '_, V> {
3371    fn deref_mut(&mut self) -> &mut Self::Target {
3372        &mut self.view_context
3373    }
3374}
3375
3376impl<V: View> BorrowAppContext for EventContext<'_, '_, '_, V> {
3377    fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
3378        BorrowAppContext::read_with(&*self.view_context, f)
3379    }
3380
3381    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
3382        BorrowAppContext::update(&mut *self.view_context, f)
3383    }
3384}
3385
3386impl<V: View> BorrowWindowContext for EventContext<'_, '_, '_, V> {
3387    type ReturnValue<T> = T;
3388
3389    fn read_with<T, F: FnOnce(&WindowContext) -> T>(&self, window_id: usize, f: F) -> T {
3390        BorrowWindowContext::read_with(&*self.view_context, window_id, f)
3391    }
3392
3393    fn update<T, F: FnOnce(&mut WindowContext) -> T>(&mut self, window_id: usize, f: F) -> T {
3394        BorrowWindowContext::update(&mut *self.view_context, window_id, f)
3395    }
3396}
3397
3398pub(crate) enum Reference<'a, T> {
3399    Immutable(&'a T),
3400    Mutable(&'a mut T),
3401}
3402
3403impl<'a, T> Deref for Reference<'a, T> {
3404    type Target = T;
3405
3406    fn deref(&self) -> &Self::Target {
3407        match self {
3408            Reference::Immutable(target) => target,
3409            Reference::Mutable(target) => target,
3410        }
3411    }
3412}
3413
3414impl<'a, T> DerefMut for Reference<'a, T> {
3415    fn deref_mut(&mut self) -> &mut Self::Target {
3416        match self {
3417            Reference::Immutable(_) => {
3418                panic!("cannot mutably deref an immutable reference. this is a bug in GPUI.");
3419            }
3420            Reference::Mutable(target) => target,
3421        }
3422    }
3423}
3424
3425#[derive(Debug, Clone, Default)]
3426pub struct MouseState {
3427    pub(crate) hovered: bool,
3428    pub(crate) clicked: Option<MouseButton>,
3429    pub(crate) accessed_hovered: bool,
3430    pub(crate) accessed_clicked: bool,
3431}
3432
3433impl MouseState {
3434    pub fn hovered(&mut self) -> bool {
3435        self.accessed_hovered = true;
3436        self.hovered
3437    }
3438
3439    pub fn clicked(&mut self) -> Option<MouseButton> {
3440        self.accessed_clicked = true;
3441        self.clicked
3442    }
3443
3444    pub fn accessed_hovered(&self) -> bool {
3445        self.accessed_hovered
3446    }
3447
3448    pub fn accessed_clicked(&self) -> bool {
3449        self.accessed_clicked
3450    }
3451}
3452
3453pub trait Handle<T> {
3454    type Weak: 'static;
3455    fn id(&self) -> usize;
3456    fn location(&self) -> EntityLocation;
3457    fn downgrade(&self) -> Self::Weak;
3458    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3459    where
3460        Self: Sized;
3461}
3462
3463pub trait WeakHandle {
3464    fn id(&self) -> usize;
3465}
3466
3467#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3468pub enum EntityLocation {
3469    Model(usize),
3470    View(usize, usize),
3471}
3472
3473pub struct ModelHandle<T: Entity> {
3474    any_handle: AnyModelHandle,
3475    model_type: PhantomData<T>,
3476}
3477
3478impl<T: Entity> Deref for ModelHandle<T> {
3479    type Target = AnyModelHandle;
3480
3481    fn deref(&self) -> &Self::Target {
3482        &self.any_handle
3483    }
3484}
3485
3486impl<T: Entity> ModelHandle<T> {
3487    fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3488        Self {
3489            any_handle: AnyModelHandle::new(model_id, TypeId::of::<T>(), ref_counts.clone()),
3490            model_type: PhantomData,
3491        }
3492    }
3493
3494    pub fn downgrade(&self) -> WeakModelHandle<T> {
3495        WeakModelHandle::new(self.model_id)
3496    }
3497
3498    pub fn id(&self) -> usize {
3499        self.model_id
3500    }
3501
3502    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3503        cx.read_model(self)
3504    }
3505
3506    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> S
3507    where
3508        C: BorrowAppContext,
3509        F: FnOnce(&T, &AppContext) -> S,
3510    {
3511        cx.read_with(|cx| read(self.read(cx), cx))
3512    }
3513
3514    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> S
3515    where
3516        C: BorrowAppContext,
3517        F: FnOnce(&mut T, &mut ModelContext<T>) -> S,
3518    {
3519        let mut update = Some(update);
3520        cx.update(|cx| {
3521            cx.update_model(self, &mut |model, cx| {
3522                let update = update.take().unwrap();
3523                update(model, cx)
3524            })
3525        })
3526    }
3527}
3528
3529impl<T: Entity> Clone for ModelHandle<T> {
3530    fn clone(&self) -> Self {
3531        Self::new(self.model_id, &self.ref_counts)
3532    }
3533}
3534
3535impl<T: Entity> PartialEq for ModelHandle<T> {
3536    fn eq(&self, other: &Self) -> bool {
3537        self.model_id == other.model_id
3538    }
3539}
3540
3541impl<T: Entity> Eq for ModelHandle<T> {}
3542
3543impl<T: Entity> PartialEq<WeakModelHandle<T>> for ModelHandle<T> {
3544    fn eq(&self, other: &WeakModelHandle<T>) -> bool {
3545        self.model_id == other.model_id
3546    }
3547}
3548
3549impl<T: Entity> Hash for ModelHandle<T> {
3550    fn hash<H: Hasher>(&self, state: &mut H) {
3551        self.model_id.hash(state);
3552    }
3553}
3554
3555impl<T: Entity> std::borrow::Borrow<usize> for ModelHandle<T> {
3556    fn borrow(&self) -> &usize {
3557        &self.model_id
3558    }
3559}
3560
3561impl<T: Entity> Debug for ModelHandle<T> {
3562    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3563        f.debug_tuple(&format!("ModelHandle<{}>", type_name::<T>()))
3564            .field(&self.model_id)
3565            .finish()
3566    }
3567}
3568
3569unsafe impl<T: Entity> Send for ModelHandle<T> {}
3570unsafe impl<T: Entity> Sync for ModelHandle<T> {}
3571
3572impl<T: Entity> Handle<T> for ModelHandle<T> {
3573    type Weak = WeakModelHandle<T>;
3574
3575    fn id(&self) -> usize {
3576        self.model_id
3577    }
3578
3579    fn location(&self) -> EntityLocation {
3580        EntityLocation::Model(self.model_id)
3581    }
3582
3583    fn downgrade(&self) -> Self::Weak {
3584        self.downgrade()
3585    }
3586
3587    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3588    where
3589        Self: Sized,
3590    {
3591        weak.upgrade(cx)
3592    }
3593}
3594
3595pub struct WeakModelHandle<T> {
3596    any_handle: AnyWeakModelHandle,
3597    model_type: PhantomData<T>,
3598}
3599
3600impl<T> WeakModelHandle<T> {
3601    pub fn into_any(self) -> AnyWeakModelHandle {
3602        self.any_handle
3603    }
3604}
3605
3606impl<T> Deref for WeakModelHandle<T> {
3607    type Target = AnyWeakModelHandle;
3608
3609    fn deref(&self) -> &Self::Target {
3610        &self.any_handle
3611    }
3612}
3613
3614impl<T> WeakHandle for WeakModelHandle<T> {
3615    fn id(&self) -> usize {
3616        self.model_id
3617    }
3618}
3619
3620unsafe impl<T> Send for WeakModelHandle<T> {}
3621unsafe impl<T> Sync for WeakModelHandle<T> {}
3622
3623impl<T: Entity> WeakModelHandle<T> {
3624    fn new(model_id: usize) -> Self {
3625        Self {
3626            any_handle: AnyWeakModelHandle {
3627                model_id,
3628                model_type: TypeId::of::<T>(),
3629            },
3630            model_type: PhantomData,
3631        }
3632    }
3633
3634    pub fn id(&self) -> usize {
3635        self.model_id
3636    }
3637
3638    pub fn is_upgradable(&self, cx: &impl BorrowAppContext) -> bool {
3639        cx.read_with(|cx| cx.model_handle_is_upgradable(self))
3640    }
3641
3642    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<T>> {
3643        cx.read_with(|cx| cx.upgrade_model_handle(self))
3644    }
3645}
3646
3647impl<T> Hash for WeakModelHandle<T> {
3648    fn hash<H: Hasher>(&self, state: &mut H) {
3649        self.model_id.hash(state)
3650    }
3651}
3652
3653impl<T> PartialEq for WeakModelHandle<T> {
3654    fn eq(&self, other: &Self) -> bool {
3655        self.model_id == other.model_id
3656    }
3657}
3658
3659impl<T> Eq for WeakModelHandle<T> {}
3660
3661impl<T: Entity> PartialEq<ModelHandle<T>> for WeakModelHandle<T> {
3662    fn eq(&self, other: &ModelHandle<T>) -> bool {
3663        self.model_id == other.model_id
3664    }
3665}
3666
3667impl<T> Clone for WeakModelHandle<T> {
3668    fn clone(&self) -> Self {
3669        Self {
3670            any_handle: self.any_handle.clone(),
3671            model_type: PhantomData,
3672        }
3673    }
3674}
3675
3676impl<T> Copy for WeakModelHandle<T> {}
3677
3678#[repr(transparent)]
3679pub struct ViewHandle<T> {
3680    any_handle: AnyViewHandle,
3681    view_type: PhantomData<T>,
3682}
3683
3684impl<T> Deref for ViewHandle<T> {
3685    type Target = AnyViewHandle;
3686
3687    fn deref(&self) -> &Self::Target {
3688        &self.any_handle
3689    }
3690}
3691
3692impl<T: View> ViewHandle<T> {
3693    fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
3694        Self {
3695            any_handle: AnyViewHandle::new(
3696                window_id,
3697                view_id,
3698                TypeId::of::<T>(),
3699                ref_counts.clone(),
3700            ),
3701            view_type: PhantomData,
3702        }
3703    }
3704
3705    pub fn downgrade(&self) -> WeakViewHandle<T> {
3706        WeakViewHandle::new(self.window_id, self.view_id)
3707    }
3708
3709    pub fn into_any(self) -> AnyViewHandle {
3710        self.any_handle
3711    }
3712
3713    pub fn window_id(&self) -> usize {
3714        self.window_id
3715    }
3716
3717    pub fn id(&self) -> usize {
3718        self.view_id
3719    }
3720
3721    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
3722        cx.read_view(self)
3723    }
3724
3725    pub fn read_with<C, F, S>(&self, cx: &C, read: F) -> C::ReturnValue<S>
3726    where
3727        C: BorrowWindowContext,
3728        F: FnOnce(&T, &ViewContext<T>) -> S,
3729    {
3730        cx.read_with(self.window_id, |cx| {
3731            let cx = ViewContext::immutable(cx, self.view_id);
3732            read(cx.read_view(self), &cx)
3733        })
3734    }
3735
3736    pub fn update<C, F, S>(&self, cx: &mut C, update: F) -> C::ReturnValue<S>
3737    where
3738        C: BorrowWindowContext,
3739        F: FnOnce(&mut T, &mut ViewContext<T>) -> S,
3740    {
3741        let mut update = Some(update);
3742
3743        cx.update(self.window_id, |cx| {
3744            cx.update_view(self, &mut |view, cx| {
3745                let update = update.take().unwrap();
3746                update(view, cx)
3747            })
3748        })
3749    }
3750
3751    pub fn is_focused(&self, cx: &WindowContext) -> bool {
3752        cx.focused_view_id() == Some(self.view_id)
3753    }
3754}
3755
3756impl<T: View> Clone for ViewHandle<T> {
3757    fn clone(&self) -> Self {
3758        ViewHandle::new(self.window_id, self.view_id, &self.ref_counts)
3759    }
3760}
3761
3762impl<T> PartialEq for ViewHandle<T> {
3763    fn eq(&self, other: &Self) -> bool {
3764        self.window_id == other.window_id && self.view_id == other.view_id
3765    }
3766}
3767
3768impl<T> PartialEq<WeakViewHandle<T>> for ViewHandle<T> {
3769    fn eq(&self, other: &WeakViewHandle<T>) -> bool {
3770        self.window_id == other.window_id && self.view_id == other.view_id
3771    }
3772}
3773
3774impl<T> PartialEq<ViewHandle<T>> for WeakViewHandle<T> {
3775    fn eq(&self, other: &ViewHandle<T>) -> bool {
3776        self.window_id == other.window_id && self.view_id == other.view_id
3777    }
3778}
3779
3780impl<T> Eq for ViewHandle<T> {}
3781
3782impl<T> Hash for ViewHandle<T> {
3783    fn hash<H: Hasher>(&self, state: &mut H) {
3784        self.window_id.hash(state);
3785        self.view_id.hash(state);
3786    }
3787}
3788
3789impl<T> Debug for ViewHandle<T> {
3790    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3791        f.debug_struct(&format!("ViewHandle<{}>", type_name::<T>()))
3792            .field("window_id", &self.window_id)
3793            .field("view_id", &self.view_id)
3794            .finish()
3795    }
3796}
3797
3798impl<T: View> Handle<T> for ViewHandle<T> {
3799    type Weak = WeakViewHandle<T>;
3800
3801    fn id(&self) -> usize {
3802        self.view_id
3803    }
3804
3805    fn location(&self) -> EntityLocation {
3806        EntityLocation::View(self.window_id, self.view_id)
3807    }
3808
3809    fn downgrade(&self) -> Self::Weak {
3810        self.downgrade()
3811    }
3812
3813    fn upgrade_from(weak: &Self::Weak, cx: &AppContext) -> Option<Self>
3814    where
3815        Self: Sized,
3816    {
3817        weak.upgrade(cx)
3818    }
3819}
3820
3821pub struct AnyViewHandle {
3822    window_id: usize,
3823    view_id: usize,
3824    view_type: TypeId,
3825    ref_counts: Arc<Mutex<RefCounts>>,
3826
3827    #[cfg(any(test, feature = "test-support"))]
3828    handle_id: usize,
3829}
3830
3831impl AnyViewHandle {
3832    fn new(
3833        window_id: usize,
3834        view_id: usize,
3835        view_type: TypeId,
3836        ref_counts: Arc<Mutex<RefCounts>>,
3837    ) -> Self {
3838        ref_counts.lock().inc_view(window_id, view_id);
3839
3840        #[cfg(any(test, feature = "test-support"))]
3841        let handle_id = ref_counts
3842            .lock()
3843            .leak_detector
3844            .lock()
3845            .handle_created(None, view_id);
3846
3847        Self {
3848            window_id,
3849            view_id,
3850            view_type,
3851            ref_counts,
3852            #[cfg(any(test, feature = "test-support"))]
3853            handle_id,
3854        }
3855    }
3856
3857    pub fn window_id(&self) -> usize {
3858        self.window_id
3859    }
3860
3861    pub fn id(&self) -> usize {
3862        self.view_id
3863    }
3864
3865    pub fn is<T: 'static>(&self) -> bool {
3866        TypeId::of::<T>() == self.view_type
3867    }
3868
3869    pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
3870        if self.is::<T>() {
3871            Some(ViewHandle {
3872                any_handle: self,
3873                view_type: PhantomData,
3874            })
3875        } else {
3876            None
3877        }
3878    }
3879
3880    pub fn downcast_ref<T: View>(&self) -> Option<&ViewHandle<T>> {
3881        if self.is::<T>() {
3882            Some(unsafe { mem::transmute(self) })
3883        } else {
3884            None
3885        }
3886    }
3887
3888    pub fn downgrade(&self) -> AnyWeakViewHandle {
3889        AnyWeakViewHandle {
3890            window_id: self.window_id,
3891            view_id: self.view_id,
3892            view_type: self.view_type,
3893        }
3894    }
3895
3896    pub fn view_type(&self) -> TypeId {
3897        self.view_type
3898    }
3899
3900    pub fn debug_json<'a, 'b>(&self, cx: &'b WindowContext<'a>) -> serde_json::Value {
3901        cx.views
3902            .get(&(self.window_id, self.view_id))
3903            .map_or_else(|| serde_json::Value::Null, |view| view.debug_json(cx))
3904    }
3905}
3906
3907impl Clone for AnyViewHandle {
3908    fn clone(&self) -> Self {
3909        Self::new(
3910            self.window_id,
3911            self.view_id,
3912            self.view_type,
3913            self.ref_counts.clone(),
3914        )
3915    }
3916}
3917
3918impl<T> PartialEq<ViewHandle<T>> for AnyViewHandle {
3919    fn eq(&self, other: &ViewHandle<T>) -> bool {
3920        self.window_id == other.window_id && self.view_id == other.view_id
3921    }
3922}
3923
3924impl Drop for AnyViewHandle {
3925    fn drop(&mut self) {
3926        self.ref_counts
3927            .lock()
3928            .dec_view(self.window_id, self.view_id);
3929        #[cfg(any(test, feature = "test-support"))]
3930        self.ref_counts
3931            .lock()
3932            .leak_detector
3933            .lock()
3934            .handle_dropped(self.view_id, self.handle_id);
3935    }
3936}
3937
3938pub struct AnyModelHandle {
3939    model_id: usize,
3940    model_type: TypeId,
3941    ref_counts: Arc<Mutex<RefCounts>>,
3942
3943    #[cfg(any(test, feature = "test-support"))]
3944    handle_id: usize,
3945}
3946
3947impl AnyModelHandle {
3948    fn new(model_id: usize, model_type: TypeId, ref_counts: Arc<Mutex<RefCounts>>) -> Self {
3949        ref_counts.lock().inc_model(model_id);
3950
3951        #[cfg(any(test, feature = "test-support"))]
3952        let handle_id = ref_counts
3953            .lock()
3954            .leak_detector
3955            .lock()
3956            .handle_created(None, model_id);
3957
3958        Self {
3959            model_id,
3960            model_type,
3961            ref_counts,
3962
3963            #[cfg(any(test, feature = "test-support"))]
3964            handle_id,
3965        }
3966    }
3967
3968    pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
3969        if self.is::<T>() {
3970            Some(ModelHandle {
3971                any_handle: self,
3972                model_type: PhantomData,
3973            })
3974        } else {
3975            None
3976        }
3977    }
3978
3979    pub fn downgrade(&self) -> AnyWeakModelHandle {
3980        AnyWeakModelHandle {
3981            model_id: self.model_id,
3982            model_type: self.model_type,
3983        }
3984    }
3985
3986    pub fn is<T: Entity>(&self) -> bool {
3987        self.model_type == TypeId::of::<T>()
3988    }
3989
3990    pub fn model_type(&self) -> TypeId {
3991        self.model_type
3992    }
3993}
3994
3995impl Clone for AnyModelHandle {
3996    fn clone(&self) -> Self {
3997        Self::new(self.model_id, self.model_type, self.ref_counts.clone())
3998    }
3999}
4000
4001impl Drop for AnyModelHandle {
4002    fn drop(&mut self) {
4003        let mut ref_counts = self.ref_counts.lock();
4004        ref_counts.dec_model(self.model_id);
4005
4006        #[cfg(any(test, feature = "test-support"))]
4007        ref_counts
4008            .leak_detector
4009            .lock()
4010            .handle_dropped(self.model_id, self.handle_id);
4011    }
4012}
4013
4014#[derive(Hash, PartialEq, Eq, Debug, Clone, Copy)]
4015pub struct AnyWeakModelHandle {
4016    model_id: usize,
4017    model_type: TypeId,
4018}
4019
4020impl AnyWeakModelHandle {
4021    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<AnyModelHandle> {
4022        cx.read_with(|cx| cx.upgrade_any_model_handle(self))
4023    }
4024
4025    pub fn model_type(&self) -> TypeId {
4026        self.model_type
4027    }
4028
4029    fn is<T: 'static>(&self) -> bool {
4030        TypeId::of::<T>() == self.model_type
4031    }
4032
4033    pub fn downcast<T: Entity>(self) -> Option<WeakModelHandle<T>> {
4034        if self.is::<T>() {
4035            let result = Some(WeakModelHandle {
4036                any_handle: self,
4037                model_type: PhantomData,
4038            });
4039
4040            result
4041        } else {
4042            None
4043        }
4044    }
4045}
4046
4047#[derive(Debug, Copy)]
4048pub struct WeakViewHandle<T> {
4049    any_handle: AnyWeakViewHandle,
4050    view_type: PhantomData<T>,
4051}
4052
4053impl<T> WeakHandle for WeakViewHandle<T> {
4054    fn id(&self) -> usize {
4055        self.view_id
4056    }
4057}
4058
4059impl<V: View> WeakViewHandle<V> {
4060    fn new(window_id: usize, view_id: usize) -> Self {
4061        Self {
4062            any_handle: AnyWeakViewHandle {
4063                window_id,
4064                view_id,
4065                view_type: TypeId::of::<V>(),
4066            },
4067            view_type: PhantomData,
4068        }
4069    }
4070
4071    pub fn id(&self) -> usize {
4072        self.view_id
4073    }
4074
4075    pub fn window_id(&self) -> usize {
4076        self.window_id
4077    }
4078
4079    pub fn into_any(self) -> AnyWeakViewHandle {
4080        self.any_handle
4081    }
4082
4083    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ViewHandle<V>> {
4084        cx.read_with(|cx| cx.upgrade_view_handle(self))
4085    }
4086
4087    pub fn read_with<T>(
4088        &self,
4089        cx: &impl BorrowAppContext,
4090        read: impl FnOnce(&V, &ViewContext<V>) -> T,
4091    ) -> Result<T> {
4092        cx.read_with(|cx| {
4093            let handle = cx
4094                .upgrade_view_handle(self)
4095                .ok_or_else(|| anyhow!("view {} was dropped", V::ui_name()))?;
4096            cx.read_window(self.window_id, |cx| handle.read_with(cx, read))
4097                .ok_or_else(|| anyhow!("window was removed"))
4098        })
4099    }
4100
4101    pub fn update<T>(
4102        &self,
4103        cx: &mut impl BorrowAppContext,
4104        update: impl FnOnce(&mut V, &mut ViewContext<V>) -> T,
4105    ) -> Result<T> {
4106        cx.update(|cx| {
4107            let handle = cx
4108                .upgrade_view_handle(self)
4109                .ok_or_else(|| anyhow!("view {} was dropped", V::ui_name()))?;
4110            cx.update_window(self.window_id, |cx| handle.update(cx, update))
4111                .ok_or_else(|| anyhow!("window was removed"))
4112        })
4113    }
4114}
4115
4116impl<T> Deref for WeakViewHandle<T> {
4117    type Target = AnyWeakViewHandle;
4118
4119    fn deref(&self) -> &Self::Target {
4120        &self.any_handle
4121    }
4122}
4123
4124impl<T> Clone for WeakViewHandle<T> {
4125    fn clone(&self) -> Self {
4126        Self {
4127            any_handle: self.any_handle.clone(),
4128            view_type: PhantomData,
4129        }
4130    }
4131}
4132
4133impl<T> PartialEq for WeakViewHandle<T> {
4134    fn eq(&self, other: &Self) -> bool {
4135        self.window_id == other.window_id && self.view_id == other.view_id
4136    }
4137}
4138
4139impl<T> Eq for WeakViewHandle<T> {}
4140
4141impl<T> Hash for WeakViewHandle<T> {
4142    fn hash<H: Hasher>(&self, state: &mut H) {
4143        self.any_handle.hash(state);
4144    }
4145}
4146
4147#[derive(Debug, Clone, Copy)]
4148pub struct AnyWeakViewHandle {
4149    window_id: usize,
4150    view_id: usize,
4151    view_type: TypeId,
4152}
4153
4154impl AnyWeakViewHandle {
4155    pub fn id(&self) -> usize {
4156        self.view_id
4157    }
4158
4159    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<AnyViewHandle> {
4160        cx.read_with(|cx| cx.upgrade_any_view_handle(self))
4161    }
4162}
4163
4164impl Hash for AnyWeakViewHandle {
4165    fn hash<H: Hasher>(&self, state: &mut H) {
4166        self.window_id.hash(state);
4167        self.view_id.hash(state);
4168        self.view_type.hash(state);
4169    }
4170}
4171
4172#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4173pub struct ElementStateId {
4174    view_id: usize,
4175    element_id: usize,
4176    tag: TypeId,
4177}
4178
4179pub struct ElementStateHandle<T> {
4180    value_type: PhantomData<T>,
4181    id: ElementStateId,
4182    ref_counts: Weak<Mutex<RefCounts>>,
4183}
4184
4185impl<T: 'static> ElementStateHandle<T> {
4186    fn new(id: ElementStateId, frame_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
4187        ref_counts.lock().inc_element_state(id, frame_id);
4188        Self {
4189            value_type: PhantomData,
4190            id,
4191            ref_counts: Arc::downgrade(ref_counts),
4192        }
4193    }
4194
4195    pub fn id(&self) -> ElementStateId {
4196        self.id
4197    }
4198
4199    pub fn read<'a>(&self, cx: &'a AppContext) -> &'a T {
4200        cx.element_states
4201            .get(&self.id)
4202            .unwrap()
4203            .downcast_ref()
4204            .unwrap()
4205    }
4206
4207    pub fn update<C, D, R>(&self, cx: &mut C, f: impl FnOnce(&mut T, &mut C) -> R) -> R
4208    where
4209        C: DerefMut<Target = D>,
4210        D: DerefMut<Target = AppContext>,
4211    {
4212        let mut element_state = cx.deref_mut().element_states.remove(&self.id).unwrap();
4213        let result = f(element_state.downcast_mut().unwrap(), cx);
4214        cx.deref_mut().element_states.insert(self.id, element_state);
4215        result
4216    }
4217}
4218
4219impl<T> Drop for ElementStateHandle<T> {
4220    fn drop(&mut self) {
4221        if let Some(ref_counts) = self.ref_counts.upgrade() {
4222            ref_counts.lock().dec_element_state(self.id);
4223        }
4224    }
4225}
4226
4227#[must_use]
4228pub enum Subscription {
4229    Subscription(callback_collection::Subscription<usize, SubscriptionCallback>),
4230    Observation(callback_collection::Subscription<usize, ObservationCallback>),
4231    GlobalSubscription(callback_collection::Subscription<TypeId, GlobalSubscriptionCallback>),
4232    GlobalObservation(callback_collection::Subscription<TypeId, GlobalObservationCallback>),
4233    FocusObservation(callback_collection::Subscription<usize, FocusObservationCallback>),
4234    WindowActivationObservation(callback_collection::Subscription<usize, WindowActivationCallback>),
4235    WindowFullscreenObservation(callback_collection::Subscription<usize, WindowFullscreenCallback>),
4236    WindowBoundsObservation(callback_collection::Subscription<usize, WindowBoundsCallback>),
4237    KeystrokeObservation(callback_collection::Subscription<usize, KeystrokeCallback>),
4238    ReleaseObservation(callback_collection::Subscription<usize, ReleaseObservationCallback>),
4239    ActionObservation(callback_collection::Subscription<(), ActionObservationCallback>),
4240    ActiveLabeledTasksObservation(
4241        callback_collection::Subscription<(), ActiveLabeledTasksCallback>,
4242    ),
4243}
4244
4245impl Subscription {
4246    pub fn id(&self) -> usize {
4247        match self {
4248            Subscription::Subscription(subscription) => subscription.id(),
4249            Subscription::Observation(subscription) => subscription.id(),
4250            Subscription::GlobalSubscription(subscription) => subscription.id(),
4251            Subscription::GlobalObservation(subscription) => subscription.id(),
4252            Subscription::FocusObservation(subscription) => subscription.id(),
4253            Subscription::WindowActivationObservation(subscription) => subscription.id(),
4254            Subscription::WindowFullscreenObservation(subscription) => subscription.id(),
4255            Subscription::WindowBoundsObservation(subscription) => subscription.id(),
4256            Subscription::KeystrokeObservation(subscription) => subscription.id(),
4257            Subscription::ReleaseObservation(subscription) => subscription.id(),
4258            Subscription::ActionObservation(subscription) => subscription.id(),
4259            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.id(),
4260        }
4261    }
4262
4263    pub fn detach(&mut self) {
4264        match self {
4265            Subscription::Subscription(subscription) => subscription.detach(),
4266            Subscription::GlobalSubscription(subscription) => subscription.detach(),
4267            Subscription::Observation(subscription) => subscription.detach(),
4268            Subscription::GlobalObservation(subscription) => subscription.detach(),
4269            Subscription::FocusObservation(subscription) => subscription.detach(),
4270            Subscription::KeystrokeObservation(subscription) => subscription.detach(),
4271            Subscription::WindowActivationObservation(subscription) => subscription.detach(),
4272            Subscription::WindowFullscreenObservation(subscription) => subscription.detach(),
4273            Subscription::WindowBoundsObservation(subscription) => subscription.detach(),
4274            Subscription::ReleaseObservation(subscription) => subscription.detach(),
4275            Subscription::ActionObservation(subscription) => subscription.detach(),
4276            Subscription::ActiveLabeledTasksObservation(subscription) => subscription.detach(),
4277        }
4278    }
4279}
4280
4281#[cfg(test)]
4282mod tests {
4283    use super::*;
4284    use crate::{
4285        actions,
4286        elements::*,
4287        impl_actions,
4288        platform::{MouseButton, MouseButtonEvent},
4289        window::ChildView,
4290    };
4291    use itertools::Itertools;
4292    use postage::{sink::Sink, stream::Stream};
4293    use serde::Deserialize;
4294    use smol::future::poll_once;
4295    use std::{
4296        cell::Cell,
4297        sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
4298    };
4299
4300    #[crate::test(self)]
4301    fn test_model_handles(cx: &mut AppContext) {
4302        struct Model {
4303            other: Option<ModelHandle<Model>>,
4304            events: Vec<String>,
4305        }
4306
4307        impl Entity for Model {
4308            type Event = usize;
4309        }
4310
4311        impl Model {
4312            fn new(other: Option<ModelHandle<Self>>, cx: &mut ModelContext<Self>) -> Self {
4313                if let Some(other) = other.as_ref() {
4314                    cx.observe(other, |me, _, _| {
4315                        me.events.push("notified".into());
4316                    })
4317                    .detach();
4318                    cx.subscribe(other, |me, _, event, _| {
4319                        me.events.push(format!("observed event {}", event));
4320                    })
4321                    .detach();
4322                }
4323
4324                Self {
4325                    other,
4326                    events: Vec::new(),
4327                }
4328            }
4329        }
4330
4331        let handle_1 = cx.add_model(|cx| Model::new(None, cx));
4332        let handle_2 = cx.add_model(|cx| Model::new(Some(handle_1.clone()), cx));
4333        assert_eq!(cx.models.len(), 2);
4334
4335        handle_1.update(cx, |model, cx| {
4336            model.events.push("updated".into());
4337            cx.emit(1);
4338            cx.notify();
4339            cx.emit(2);
4340        });
4341        assert_eq!(handle_1.read(cx).events, vec!["updated".to_string()]);
4342        assert_eq!(
4343            handle_2.read(cx).events,
4344            vec![
4345                "observed event 1".to_string(),
4346                "notified".to_string(),
4347                "observed event 2".to_string(),
4348            ]
4349        );
4350
4351        handle_2.update(cx, |model, _| {
4352            drop(handle_1);
4353            model.other.take();
4354        });
4355
4356        assert_eq!(cx.models.len(), 1);
4357        assert!(cx.subscriptions.is_empty());
4358        assert!(cx.observations.is_empty());
4359    }
4360
4361    #[crate::test(self)]
4362    fn test_model_events(cx: &mut AppContext) {
4363        #[derive(Default)]
4364        struct Model {
4365            events: Vec<usize>,
4366        }
4367
4368        impl Entity for Model {
4369            type Event = usize;
4370        }
4371
4372        let handle_1 = cx.add_model(|_| Model::default());
4373        let handle_2 = cx.add_model(|_| Model::default());
4374
4375        handle_1.update(cx, |_, cx| {
4376            cx.subscribe(&handle_2, move |model: &mut Model, emitter, event, cx| {
4377                model.events.push(*event);
4378
4379                cx.subscribe(&emitter, |model, _, event, _| {
4380                    model.events.push(*event * 2);
4381                })
4382                .detach();
4383            })
4384            .detach();
4385        });
4386
4387        handle_2.update(cx, |_, c| c.emit(7));
4388        assert_eq!(handle_1.read(cx).events, vec![7]);
4389
4390        handle_2.update(cx, |_, c| c.emit(5));
4391        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10]);
4392    }
4393
4394    #[crate::test(self)]
4395    fn test_model_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
4396        #[derive(Default)]
4397        struct Model;
4398
4399        impl Entity for Model {
4400            type Event = ();
4401        }
4402
4403        let events = Rc::new(RefCell::new(Vec::new()));
4404        cx.add_model(|cx| {
4405            drop(cx.subscribe(&cx.handle(), {
4406                let events = events.clone();
4407                move |_, _, _, _| events.borrow_mut().push("dropped before flush")
4408            }));
4409            cx.subscribe(&cx.handle(), {
4410                let events = events.clone();
4411                move |_, _, _, _| events.borrow_mut().push("before emit")
4412            })
4413            .detach();
4414            cx.emit(());
4415            cx.subscribe(&cx.handle(), {
4416                let events = events.clone();
4417                move |_, _, _, _| events.borrow_mut().push("after emit")
4418            })
4419            .detach();
4420            Model
4421        });
4422        assert_eq!(*events.borrow(), ["before emit"]);
4423    }
4424
4425    #[crate::test(self)]
4426    fn test_observe_and_notify_from_model(cx: &mut AppContext) {
4427        #[derive(Default)]
4428        struct Model {
4429            count: usize,
4430            events: Vec<usize>,
4431        }
4432
4433        impl Entity for Model {
4434            type Event = ();
4435        }
4436
4437        let handle_1 = cx.add_model(|_| Model::default());
4438        let handle_2 = cx.add_model(|_| Model::default());
4439
4440        handle_1.update(cx, |_, c| {
4441            c.observe(&handle_2, move |model, observed, c| {
4442                model.events.push(observed.read(c).count);
4443                c.observe(&observed, |model, observed, c| {
4444                    model.events.push(observed.read(c).count * 2);
4445                })
4446                .detach();
4447            })
4448            .detach();
4449        });
4450
4451        handle_2.update(cx, |model, c| {
4452            model.count = 7;
4453            c.notify()
4454        });
4455        assert_eq!(handle_1.read(cx).events, vec![7]);
4456
4457        handle_2.update(cx, |model, c| {
4458            model.count = 5;
4459            c.notify()
4460        });
4461        assert_eq!(handle_1.read(cx).events, vec![7, 5, 10])
4462    }
4463
4464    #[crate::test(self)]
4465    fn test_model_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
4466        #[derive(Default)]
4467        struct Model;
4468
4469        impl Entity for Model {
4470            type Event = ();
4471        }
4472
4473        let events = Rc::new(RefCell::new(Vec::new()));
4474        cx.add_model(|cx| {
4475            drop(cx.observe(&cx.handle(), {
4476                let events = events.clone();
4477                move |_, _, _| events.borrow_mut().push("dropped before flush")
4478            }));
4479            cx.observe(&cx.handle(), {
4480                let events = events.clone();
4481                move |_, _, _| events.borrow_mut().push("before notify")
4482            })
4483            .detach();
4484            cx.notify();
4485            cx.observe(&cx.handle(), {
4486                let events = events.clone();
4487                move |_, _, _| events.borrow_mut().push("after notify")
4488            })
4489            .detach();
4490            Model
4491        });
4492        assert_eq!(*events.borrow(), ["before notify"]);
4493    }
4494
4495    #[crate::test(self)]
4496    fn test_defer_and_after_window_update(cx: &mut TestAppContext) {
4497        struct View {
4498            render_count: usize,
4499        }
4500
4501        impl Entity for View {
4502            type Event = usize;
4503        }
4504
4505        impl super::View for View {
4506            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
4507                post_inc(&mut self.render_count);
4508                Empty::new().into_any()
4509            }
4510
4511            fn ui_name() -> &'static str {
4512                "View"
4513            }
4514        }
4515
4516        let (_, view) = cx.add_window(|_| View { render_count: 0 });
4517        let called_defer = Rc::new(AtomicBool::new(false));
4518        let called_after_window_update = Rc::new(AtomicBool::new(false));
4519
4520        view.update(cx, |this, cx| {
4521            assert_eq!(this.render_count, 1);
4522            cx.defer({
4523                let called_defer = called_defer.clone();
4524                move |this, _| {
4525                    assert_eq!(this.render_count, 1);
4526                    called_defer.store(true, SeqCst);
4527                }
4528            });
4529            cx.after_window_update({
4530                let called_after_window_update = called_after_window_update.clone();
4531                move |this, cx| {
4532                    assert_eq!(this.render_count, 2);
4533                    called_after_window_update.store(true, SeqCst);
4534                    cx.notify();
4535                }
4536            });
4537            assert!(!called_defer.load(SeqCst));
4538            assert!(!called_after_window_update.load(SeqCst));
4539            cx.notify();
4540        });
4541
4542        assert!(called_defer.load(SeqCst));
4543        assert!(called_after_window_update.load(SeqCst));
4544        assert_eq!(view.read_with(cx, |view, _| view.render_count), 3);
4545    }
4546
4547    #[crate::test(self)]
4548    fn test_view_handles(cx: &mut TestAppContext) {
4549        struct View {
4550            other: Option<ViewHandle<View>>,
4551            events: Vec<String>,
4552        }
4553
4554        impl Entity for View {
4555            type Event = usize;
4556        }
4557
4558        impl super::View for View {
4559            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
4560                Empty::new().into_any()
4561            }
4562
4563            fn ui_name() -> &'static str {
4564                "View"
4565            }
4566        }
4567
4568        impl View {
4569            fn new(other: Option<ViewHandle<View>>, cx: &mut ViewContext<Self>) -> Self {
4570                if let Some(other) = other.as_ref() {
4571                    cx.subscribe(other, |me, _, event, _| {
4572                        me.events.push(format!("observed event {}", event));
4573                    })
4574                    .detach();
4575                }
4576                Self {
4577                    other,
4578                    events: Vec::new(),
4579                }
4580            }
4581        }
4582
4583        let (_, root_view) = cx.add_window(|cx| View::new(None, cx));
4584        let handle_1 = cx.add_view(&root_view, |cx| View::new(None, cx));
4585        let handle_2 = cx.add_view(&root_view, |cx| View::new(Some(handle_1.clone()), cx));
4586        assert_eq!(cx.read(|cx| cx.views.len()), 3);
4587
4588        handle_1.update(cx, |view, cx| {
4589            view.events.push("updated".into());
4590            cx.emit(1);
4591            cx.emit(2);
4592        });
4593        handle_1.read_with(cx, |view, _| {
4594            assert_eq!(view.events, vec!["updated".to_string()]);
4595        });
4596        handle_2.read_with(cx, |view, _| {
4597            assert_eq!(
4598                view.events,
4599                vec![
4600                    "observed event 1".to_string(),
4601                    "observed event 2".to_string(),
4602                ]
4603            );
4604        });
4605
4606        handle_2.update(cx, |view, _| {
4607            drop(handle_1);
4608            view.other.take();
4609        });
4610
4611        cx.read(|cx| {
4612            assert_eq!(cx.views.len(), 2);
4613            assert!(cx.subscriptions.is_empty());
4614            assert!(cx.observations.is_empty());
4615        });
4616    }
4617
4618    #[crate::test(self)]
4619    fn test_add_window(cx: &mut AppContext) {
4620        struct View {
4621            mouse_down_count: Arc<AtomicUsize>,
4622        }
4623
4624        impl Entity for View {
4625            type Event = ();
4626        }
4627
4628        impl super::View for View {
4629            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
4630                enum Handler {}
4631                let mouse_down_count = self.mouse_down_count.clone();
4632                MouseEventHandler::<Handler, _>::new(0, cx, |_, _| Empty::new())
4633                    .on_down(MouseButton::Left, move |_, _, _| {
4634                        mouse_down_count.fetch_add(1, SeqCst);
4635                    })
4636                    .into_any()
4637            }
4638
4639            fn ui_name() -> &'static str {
4640                "View"
4641            }
4642        }
4643
4644        let mouse_down_count = Arc::new(AtomicUsize::new(0));
4645        let (window_id, _) = cx.add_window(Default::default(), |_| View {
4646            mouse_down_count: mouse_down_count.clone(),
4647        });
4648
4649        cx.update_window(window_id, |cx| {
4650            // Ensure window's root element is in a valid lifecycle state.
4651            cx.dispatch_event(
4652                Event::MouseDown(MouseButtonEvent {
4653                    position: Default::default(),
4654                    button: MouseButton::Left,
4655                    modifiers: Default::default(),
4656                    click_count: 1,
4657                }),
4658                false,
4659            );
4660            assert_eq!(mouse_down_count.load(SeqCst), 1);
4661        });
4662    }
4663
4664    #[crate::test(self)]
4665    fn test_entity_release_hooks(cx: &mut AppContext) {
4666        struct Model {
4667            released: Rc<Cell<bool>>,
4668        }
4669
4670        struct View {
4671            released: Rc<Cell<bool>>,
4672        }
4673
4674        impl Entity for Model {
4675            type Event = ();
4676
4677            fn release(&mut self, _: &mut AppContext) {
4678                self.released.set(true);
4679            }
4680        }
4681
4682        impl Entity for View {
4683            type Event = ();
4684
4685            fn release(&mut self, _: &mut AppContext) {
4686                self.released.set(true);
4687            }
4688        }
4689
4690        impl super::View for View {
4691            fn ui_name() -> &'static str {
4692                "View"
4693            }
4694
4695            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
4696                Empty::new().into_any()
4697            }
4698        }
4699
4700        let model_released = Rc::new(Cell::new(false));
4701        let model_release_observed = Rc::new(Cell::new(false));
4702        let view_released = Rc::new(Cell::new(false));
4703        let view_release_observed = Rc::new(Cell::new(false));
4704
4705        let model = cx.add_model(|_| Model {
4706            released: model_released.clone(),
4707        });
4708        let (window_id, view) = cx.add_window(Default::default(), |_| View {
4709            released: view_released.clone(),
4710        });
4711        assert!(!model_released.get());
4712        assert!(!view_released.get());
4713
4714        cx.observe_release(&model, {
4715            let model_release_observed = model_release_observed.clone();
4716            move |_, _| model_release_observed.set(true)
4717        })
4718        .detach();
4719        cx.observe_release(&view, {
4720            let view_release_observed = view_release_observed.clone();
4721            move |_, _| view_release_observed.set(true)
4722        })
4723        .detach();
4724
4725        cx.update(move |_| {
4726            drop(model);
4727        });
4728        assert!(model_released.get());
4729        assert!(model_release_observed.get());
4730
4731        drop(view);
4732        cx.remove_window(window_id);
4733        assert!(view_released.get());
4734        assert!(view_release_observed.get());
4735    }
4736
4737    #[crate::test(self)]
4738    fn test_view_events(cx: &mut TestAppContext) {
4739        struct Model;
4740
4741        impl Entity for Model {
4742            type Event = String;
4743        }
4744
4745        let (_, handle_1) = cx.add_window(|_| TestView::default());
4746        let handle_2 = cx.add_view(&handle_1, |_| TestView::default());
4747        let handle_3 = cx.add_model(|_| Model);
4748
4749        handle_1.update(cx, |_, cx| {
4750            cx.subscribe(&handle_2, move |me, emitter, event, cx| {
4751                me.events.push(event.clone());
4752
4753                cx.subscribe(&emitter, |me, _, event, _| {
4754                    me.events.push(format!("{event} from inner"));
4755                })
4756                .detach();
4757            })
4758            .detach();
4759
4760            cx.subscribe(&handle_3, |me, _, event, _| {
4761                me.events.push(event.clone());
4762            })
4763            .detach();
4764        });
4765
4766        handle_2.update(cx, |_, c| c.emit("7".into()));
4767        handle_1.read_with(cx, |view, _| assert_eq!(view.events, ["7"]));
4768
4769        handle_2.update(cx, |_, c| c.emit("5".into()));
4770        handle_1.read_with(cx, |view, _| {
4771            assert_eq!(view.events, ["7", "5", "5 from inner"])
4772        });
4773
4774        handle_3.update(cx, |_, c| c.emit("9".into()));
4775        handle_1.read_with(cx, |view, _| {
4776            assert_eq!(view.events, ["7", "5", "5 from inner", "9"])
4777        });
4778    }
4779
4780    #[crate::test(self)]
4781    fn test_global_events(cx: &mut AppContext) {
4782        #[derive(Clone, Debug, Eq, PartialEq)]
4783        struct GlobalEvent(u64);
4784
4785        let events = Rc::new(RefCell::new(Vec::new()));
4786        let first_subscription;
4787        let second_subscription;
4788
4789        {
4790            let events = events.clone();
4791            first_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
4792                events.borrow_mut().push(("First", e.clone()));
4793            });
4794        }
4795
4796        {
4797            let events = events.clone();
4798            second_subscription = cx.subscribe_global(move |e: &GlobalEvent, _| {
4799                events.borrow_mut().push(("Second", e.clone()));
4800            });
4801        }
4802
4803        cx.update(|cx| {
4804            cx.emit_global(GlobalEvent(1));
4805            cx.emit_global(GlobalEvent(2));
4806        });
4807
4808        drop(first_subscription);
4809
4810        cx.update(|cx| {
4811            cx.emit_global(GlobalEvent(3));
4812        });
4813
4814        drop(second_subscription);
4815
4816        cx.update(|cx| {
4817            cx.emit_global(GlobalEvent(4));
4818        });
4819
4820        assert_eq!(
4821            &*events.borrow(),
4822            &[
4823                ("First", GlobalEvent(1)),
4824                ("Second", GlobalEvent(1)),
4825                ("First", GlobalEvent(2)),
4826                ("Second", GlobalEvent(2)),
4827                ("Second", GlobalEvent(3)),
4828            ]
4829        );
4830    }
4831
4832    #[crate::test(self)]
4833    fn test_global_events_emitted_before_subscription_in_same_update_cycle(cx: &mut AppContext) {
4834        let events = Rc::new(RefCell::new(Vec::new()));
4835        cx.update(|cx| {
4836            {
4837                let events = events.clone();
4838                drop(cx.subscribe_global(move |_: &(), _| {
4839                    events.borrow_mut().push("dropped before emit");
4840                }));
4841            }
4842
4843            {
4844                let events = events.clone();
4845                cx.subscribe_global(move |_: &(), _| {
4846                    events.borrow_mut().push("before emit");
4847                })
4848                .detach();
4849            }
4850
4851            cx.emit_global(());
4852
4853            {
4854                let events = events.clone();
4855                cx.subscribe_global(move |_: &(), _| {
4856                    events.borrow_mut().push("after emit");
4857                })
4858                .detach();
4859            }
4860        });
4861
4862        assert_eq!(*events.borrow(), ["before emit"]);
4863    }
4864
4865    #[crate::test(self)]
4866    fn test_global_nested_events(cx: &mut AppContext) {
4867        #[derive(Clone, Debug, Eq, PartialEq)]
4868        struct GlobalEvent(u64);
4869
4870        let events = Rc::new(RefCell::new(Vec::new()));
4871
4872        {
4873            let events = events.clone();
4874            cx.subscribe_global(move |e: &GlobalEvent, cx| {
4875                events.borrow_mut().push(("Outer", e.clone()));
4876
4877                if e.0 == 1 {
4878                    let events = events.clone();
4879                    cx.subscribe_global(move |e: &GlobalEvent, _| {
4880                        events.borrow_mut().push(("Inner", e.clone()));
4881                    })
4882                    .detach();
4883                }
4884            })
4885            .detach();
4886        }
4887
4888        cx.update(|cx| {
4889            cx.emit_global(GlobalEvent(1));
4890            cx.emit_global(GlobalEvent(2));
4891            cx.emit_global(GlobalEvent(3));
4892        });
4893        cx.update(|cx| {
4894            cx.emit_global(GlobalEvent(4));
4895        });
4896
4897        assert_eq!(
4898            &*events.borrow(),
4899            &[
4900                ("Outer", GlobalEvent(1)),
4901                ("Outer", GlobalEvent(2)),
4902                ("Outer", GlobalEvent(3)),
4903                ("Outer", GlobalEvent(4)),
4904                ("Inner", GlobalEvent(4)),
4905            ]
4906        );
4907    }
4908
4909    #[crate::test(self)]
4910    fn test_global(cx: &mut AppContext) {
4911        type Global = usize;
4912
4913        let observation_count = Rc::new(RefCell::new(0));
4914        let subscription = cx.observe_global::<Global, _>({
4915            let observation_count = observation_count.clone();
4916            move |_| {
4917                *observation_count.borrow_mut() += 1;
4918            }
4919        });
4920
4921        assert!(!cx.has_global::<Global>());
4922        assert_eq!(cx.default_global::<Global>(), &0);
4923        assert_eq!(*observation_count.borrow(), 1);
4924        assert!(cx.has_global::<Global>());
4925        assert_eq!(
4926            cx.update_global::<Global, _, _>(|global, _| {
4927                *global = 1;
4928                "Update Result"
4929            }),
4930            "Update Result"
4931        );
4932        assert_eq!(*observation_count.borrow(), 2);
4933        assert_eq!(cx.global::<Global>(), &1);
4934
4935        drop(subscription);
4936        cx.update_global::<Global, _, _>(|global, _| {
4937            *global = 2;
4938        });
4939        assert_eq!(*observation_count.borrow(), 2);
4940
4941        type OtherGlobal = f32;
4942
4943        let observation_count = Rc::new(RefCell::new(0));
4944        cx.observe_global::<OtherGlobal, _>({
4945            let observation_count = observation_count.clone();
4946            move |_| {
4947                *observation_count.borrow_mut() += 1;
4948            }
4949        })
4950        .detach();
4951
4952        assert_eq!(
4953            cx.update_default_global::<OtherGlobal, _, _>(|global, _| {
4954                assert_eq!(global, &0.0);
4955                *global = 2.0;
4956                "Default update result"
4957            }),
4958            "Default update result"
4959        );
4960        assert_eq!(cx.global::<OtherGlobal>(), &2.0);
4961        assert_eq!(*observation_count.borrow(), 1);
4962    }
4963
4964    #[crate::test(self)]
4965    fn test_dropping_subscribers(cx: &mut TestAppContext) {
4966        struct Model;
4967
4968        impl Entity for Model {
4969            type Event = ();
4970        }
4971
4972        let (_, root_view) = cx.add_window(|_| TestView::default());
4973        let observing_view = cx.add_view(&root_view, |_| TestView::default());
4974        let emitting_view = cx.add_view(&root_view, |_| TestView::default());
4975        let observing_model = cx.add_model(|_| Model);
4976        let observed_model = cx.add_model(|_| Model);
4977
4978        observing_view.update(cx, |_, cx| {
4979            cx.subscribe(&emitting_view, |_, _, _, _| {}).detach();
4980            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4981        });
4982        observing_model.update(cx, |_, cx| {
4983            cx.subscribe(&observed_model, |_, _, _, _| {}).detach();
4984        });
4985
4986        cx.update(|_| {
4987            drop(observing_view);
4988            drop(observing_model);
4989        });
4990
4991        emitting_view.update(cx, |_, cx| cx.emit(Default::default()));
4992        observed_model.update(cx, |_, cx| cx.emit(()));
4993    }
4994
4995    #[crate::test(self)]
4996    fn test_view_emit_before_subscribe_in_same_update_cycle(cx: &mut AppContext) {
4997        let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
4998            drop(cx.subscribe(&cx.handle(), {
4999                move |this, _, _, _| this.events.push("dropped before flush".into())
5000            }));
5001            cx.subscribe(&cx.handle(), {
5002                move |this, _, _, _| this.events.push("before emit".into())
5003            })
5004            .detach();
5005            cx.emit("the event".into());
5006            cx.subscribe(&cx.handle(), {
5007                move |this, _, _, _| this.events.push("after emit".into())
5008            })
5009            .detach();
5010            TestView { events: Vec::new() }
5011        });
5012
5013        assert_eq!(view.read(cx).events, ["before emit"]);
5014    }
5015
5016    #[crate::test(self)]
5017    fn test_observe_and_notify_from_view(cx: &mut TestAppContext) {
5018        #[derive(Default)]
5019        struct Model {
5020            state: String,
5021        }
5022
5023        impl Entity for Model {
5024            type Event = ();
5025        }
5026
5027        let (_, view) = cx.add_window(|_| TestView::default());
5028        let model = cx.add_model(|_| Model {
5029            state: "old-state".into(),
5030        });
5031
5032        view.update(cx, |_, c| {
5033            c.observe(&model, |me, observed, cx| {
5034                me.events.push(observed.read(cx).state.clone())
5035            })
5036            .detach();
5037        });
5038
5039        model.update(cx, |model, cx| {
5040            model.state = "new-state".into();
5041            cx.notify();
5042        });
5043        view.read_with(cx, |view, _| assert_eq!(view.events, ["new-state"]));
5044    }
5045
5046    #[crate::test(self)]
5047    fn test_view_notify_before_observe_in_same_update_cycle(cx: &mut AppContext) {
5048        let (_, view) = cx.add_window::<TestView, _>(Default::default(), |cx| {
5049            drop(cx.observe(&cx.handle(), {
5050                move |this, _, _| this.events.push("dropped before flush".into())
5051            }));
5052            cx.observe(&cx.handle(), {
5053                move |this, _, _| this.events.push("before notify".into())
5054            })
5055            .detach();
5056            cx.notify();
5057            cx.observe(&cx.handle(), {
5058                move |this, _, _| this.events.push("after notify".into())
5059            })
5060            .detach();
5061            TestView { events: Vec::new() }
5062        });
5063
5064        assert_eq!(view.read(cx).events, ["before notify"]);
5065    }
5066
5067    #[crate::test(self)]
5068    fn test_notify_and_drop_observe_subscription_in_same_update_cycle(cx: &mut TestAppContext) {
5069        struct Model;
5070        impl Entity for Model {
5071            type Event = ();
5072        }
5073
5074        let model = cx.add_model(|_| Model);
5075        let (_, view) = cx.add_window(|_| TestView::default());
5076
5077        view.update(cx, |_, cx| {
5078            model.update(cx, |_, cx| cx.notify());
5079            drop(cx.observe(&model, move |this, _, _| {
5080                this.events.push("model notified".into());
5081            }));
5082            model.update(cx, |_, cx| cx.notify());
5083        });
5084
5085        for _ in 0..3 {
5086            model.update(cx, |_, cx| cx.notify());
5087        }
5088        view.read_with(cx, |view, _| assert_eq!(view.events, Vec::<&str>::new()));
5089    }
5090
5091    #[crate::test(self)]
5092    fn test_dropping_observers(cx: &mut TestAppContext) {
5093        struct Model;
5094
5095        impl Entity for Model {
5096            type Event = ();
5097        }
5098
5099        let (_, root_view) = cx.add_window(|_| TestView::default());
5100        let observing_view = cx.add_view(&root_view, |_| TestView::default());
5101        let observing_model = cx.add_model(|_| Model);
5102        let observed_model = cx.add_model(|_| Model);
5103
5104        observing_view.update(cx, |_, cx| {
5105            cx.observe(&observed_model, |_, _, _| {}).detach();
5106        });
5107        observing_model.update(cx, |_, cx| {
5108            cx.observe(&observed_model, |_, _, _| {}).detach();
5109        });
5110
5111        cx.update(|_| {
5112            drop(observing_view);
5113            drop(observing_model);
5114        });
5115
5116        observed_model.update(cx, |_, cx| cx.notify());
5117    }
5118
5119    #[crate::test(self)]
5120    fn test_dropping_subscriptions_during_callback(cx: &mut TestAppContext) {
5121        struct Model;
5122
5123        impl Entity for Model {
5124            type Event = u64;
5125        }
5126
5127        // Events
5128        let observing_model = cx.add_model(|_| Model);
5129        let observed_model = cx.add_model(|_| Model);
5130
5131        let events = Rc::new(RefCell::new(Vec::new()));
5132
5133        observing_model.update(cx, |_, cx| {
5134            let events = events.clone();
5135            let subscription = Rc::new(RefCell::new(None));
5136            *subscription.borrow_mut() = Some(cx.subscribe(&observed_model, {
5137                let subscription = subscription.clone();
5138                move |_, _, e, _| {
5139                    subscription.borrow_mut().take();
5140                    events.borrow_mut().push(*e);
5141                }
5142            }));
5143        });
5144
5145        observed_model.update(cx, |_, cx| {
5146            cx.emit(1);
5147            cx.emit(2);
5148        });
5149
5150        assert_eq!(*events.borrow(), [1]);
5151
5152        // Global Events
5153        #[derive(Clone, Debug, Eq, PartialEq)]
5154        struct GlobalEvent(u64);
5155
5156        let events = Rc::new(RefCell::new(Vec::new()));
5157
5158        {
5159            let events = events.clone();
5160            let subscription = Rc::new(RefCell::new(None));
5161            *subscription.borrow_mut() = Some(cx.subscribe_global({
5162                let subscription = subscription.clone();
5163                move |e: &GlobalEvent, _| {
5164                    subscription.borrow_mut().take();
5165                    events.borrow_mut().push(e.clone());
5166                }
5167            }));
5168        }
5169
5170        cx.update(|cx| {
5171            cx.emit_global(GlobalEvent(1));
5172            cx.emit_global(GlobalEvent(2));
5173        });
5174
5175        assert_eq!(*events.borrow(), [GlobalEvent(1)]);
5176
5177        // Model Observation
5178        let observing_model = cx.add_model(|_| Model);
5179        let observed_model = cx.add_model(|_| Model);
5180
5181        let observation_count = Rc::new(RefCell::new(0));
5182
5183        observing_model.update(cx, |_, cx| {
5184            let observation_count = observation_count.clone();
5185            let subscription = Rc::new(RefCell::new(None));
5186            *subscription.borrow_mut() = Some(cx.observe(&observed_model, {
5187                let subscription = subscription.clone();
5188                move |_, _, _| {
5189                    subscription.borrow_mut().take();
5190                    *observation_count.borrow_mut() += 1;
5191                }
5192            }));
5193        });
5194
5195        observed_model.update(cx, |_, cx| {
5196            cx.notify();
5197        });
5198
5199        observed_model.update(cx, |_, cx| {
5200            cx.notify();
5201        });
5202
5203        assert_eq!(*observation_count.borrow(), 1);
5204
5205        // View Observation
5206        struct View;
5207
5208        impl Entity for View {
5209            type Event = ();
5210        }
5211
5212        impl super::View for View {
5213            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5214                Empty::new().into_any()
5215            }
5216
5217            fn ui_name() -> &'static str {
5218                "View"
5219            }
5220        }
5221
5222        let (_, root_view) = cx.add_window(|_| View);
5223        let observing_view = cx.add_view(&root_view, |_| View);
5224        let observed_view = cx.add_view(&root_view, |_| View);
5225
5226        let observation_count = Rc::new(RefCell::new(0));
5227        observing_view.update(cx, |_, cx| {
5228            let observation_count = observation_count.clone();
5229            let subscription = Rc::new(RefCell::new(None));
5230            *subscription.borrow_mut() = Some(cx.observe(&observed_view, {
5231                let subscription = subscription.clone();
5232                move |_, _, _| {
5233                    subscription.borrow_mut().take();
5234                    *observation_count.borrow_mut() += 1;
5235                }
5236            }));
5237        });
5238
5239        observed_view.update(cx, |_, cx| {
5240            cx.notify();
5241        });
5242
5243        observed_view.update(cx, |_, cx| {
5244            cx.notify();
5245        });
5246
5247        assert_eq!(*observation_count.borrow(), 1);
5248
5249        // Global Observation
5250        let observation_count = Rc::new(RefCell::new(0));
5251        let subscription = Rc::new(RefCell::new(None));
5252        *subscription.borrow_mut() = Some(cx.observe_global::<(), _>({
5253            let observation_count = observation_count.clone();
5254            let subscription = subscription.clone();
5255            move |_| {
5256                subscription.borrow_mut().take();
5257                *observation_count.borrow_mut() += 1;
5258            }
5259        }));
5260
5261        cx.update(|cx| {
5262            cx.default_global::<()>();
5263            cx.set_global(());
5264        });
5265        assert_eq!(*observation_count.borrow(), 1);
5266    }
5267
5268    #[crate::test(self)]
5269    fn test_focus(cx: &mut TestAppContext) {
5270        struct View {
5271            name: String,
5272            events: Arc<Mutex<Vec<String>>>,
5273        }
5274
5275        impl Entity for View {
5276            type Event = ();
5277        }
5278
5279        impl super::View for View {
5280            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5281                Empty::new().into_any()
5282            }
5283
5284            fn ui_name() -> &'static str {
5285                "View"
5286            }
5287
5288            fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
5289                if cx.handle().id() == focused.id() {
5290                    self.events.lock().push(format!("{} focused", &self.name));
5291                }
5292            }
5293
5294            fn focus_out(&mut self, blurred: AnyViewHandle, cx: &mut ViewContext<Self>) {
5295                if cx.handle().id() == blurred.id() {
5296                    self.events.lock().push(format!("{} blurred", &self.name));
5297                }
5298            }
5299        }
5300
5301        let view_events: Arc<Mutex<Vec<String>>> = Default::default();
5302        let (window_id, view_1) = cx.add_window(|_| View {
5303            events: view_events.clone(),
5304            name: "view 1".to_string(),
5305        });
5306        let view_2 = cx.add_view(&view_1, |_| View {
5307            events: view_events.clone(),
5308            name: "view 2".to_string(),
5309        });
5310
5311        let observed_events: Arc<Mutex<Vec<String>>> = Default::default();
5312        view_1.update(cx, |_, cx| {
5313            cx.observe_focus(&view_2, {
5314                let observed_events = observed_events.clone();
5315                move |this, view, focused, cx| {
5316                    let label = if focused { "focus" } else { "blur" };
5317                    observed_events.lock().push(format!(
5318                        "{} observed {}'s {}",
5319                        this.name,
5320                        view.read(cx).name,
5321                        label
5322                    ))
5323                }
5324            })
5325            .detach();
5326        });
5327        view_2.update(cx, |_, cx| {
5328            cx.observe_focus(&view_1, {
5329                let observed_events = observed_events.clone();
5330                move |this, view, focused, cx| {
5331                    let label = if focused { "focus" } else { "blur" };
5332                    observed_events.lock().push(format!(
5333                        "{} observed {}'s {}",
5334                        this.name,
5335                        view.read(cx).name,
5336                        label
5337                    ))
5338                }
5339            })
5340            .detach();
5341        });
5342        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5343        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5344
5345        view_1.update(cx, |_, cx| {
5346            // Ensure focus events are sent for all intermediate focuses
5347            cx.focus(&view_2);
5348            cx.focus(&view_1);
5349            cx.focus(&view_2);
5350        });
5351
5352        cx.read_window(window_id, |cx| {
5353            assert!(cx.is_child_focused(&view_1));
5354            assert!(!cx.is_child_focused(&view_2));
5355        });
5356        assert_eq!(
5357            mem::take(&mut *view_events.lock()),
5358            [
5359                "view 1 blurred",
5360                "view 2 focused",
5361                "view 2 blurred",
5362                "view 1 focused",
5363                "view 1 blurred",
5364                "view 2 focused"
5365            ],
5366        );
5367        assert_eq!(
5368            mem::take(&mut *observed_events.lock()),
5369            [
5370                "view 2 observed view 1's blur",
5371                "view 1 observed view 2's focus",
5372                "view 1 observed view 2's blur",
5373                "view 2 observed view 1's focus",
5374                "view 2 observed view 1's blur",
5375                "view 1 observed view 2's focus"
5376            ]
5377        );
5378
5379        view_1.update(cx, |_, cx| cx.focus(&view_1));
5380        cx.read_window(window_id, |cx| {
5381            assert!(!cx.is_child_focused(&view_1));
5382            assert!(!cx.is_child_focused(&view_2));
5383        });
5384        assert_eq!(
5385            mem::take(&mut *view_events.lock()),
5386            ["view 2 blurred", "view 1 focused"],
5387        );
5388        assert_eq!(
5389            mem::take(&mut *observed_events.lock()),
5390            [
5391                "view 1 observed view 2's blur",
5392                "view 2 observed view 1's focus"
5393            ]
5394        );
5395
5396        view_1.update(cx, |_, cx| cx.focus(&view_2));
5397        assert_eq!(
5398            mem::take(&mut *view_events.lock()),
5399            ["view 1 blurred", "view 2 focused"],
5400        );
5401        assert_eq!(
5402            mem::take(&mut *observed_events.lock()),
5403            [
5404                "view 2 observed view 1's blur",
5405                "view 1 observed view 2's focus"
5406            ]
5407        );
5408
5409        view_1.update(cx, |_, _| drop(view_2));
5410        assert_eq!(mem::take(&mut *view_events.lock()), ["view 1 focused"]);
5411        assert_eq!(mem::take(&mut *observed_events.lock()), Vec::<&str>::new());
5412    }
5413
5414    #[crate::test(self)]
5415    fn test_deserialize_actions(cx: &mut AppContext) {
5416        #[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
5417        pub struct ComplexAction {
5418            arg: String,
5419            count: usize,
5420        }
5421
5422        actions!(test::something, [SimpleAction]);
5423        impl_actions!(test::something, [ComplexAction]);
5424
5425        cx.add_global_action(move |_: &SimpleAction, _: &mut AppContext| {});
5426        cx.add_global_action(move |_: &ComplexAction, _: &mut AppContext| {});
5427
5428        let action1 = cx
5429            .deserialize_action(
5430                "test::something::ComplexAction",
5431                Some(r#"{"arg": "a", "count": 5}"#),
5432            )
5433            .unwrap();
5434        let action2 = cx
5435            .deserialize_action("test::something::SimpleAction", None)
5436            .unwrap();
5437        assert_eq!(
5438            action1.as_any().downcast_ref::<ComplexAction>().unwrap(),
5439            &ComplexAction {
5440                arg: "a".to_string(),
5441                count: 5,
5442            }
5443        );
5444        assert_eq!(
5445            action2.as_any().downcast_ref::<SimpleAction>().unwrap(),
5446            &SimpleAction
5447        );
5448    }
5449
5450    #[crate::test(self)]
5451    fn test_dispatch_action(cx: &mut AppContext) {
5452        struct ViewA {
5453            id: usize,
5454        }
5455
5456        impl Entity for ViewA {
5457            type Event = ();
5458        }
5459
5460        impl View for ViewA {
5461            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5462                Empty::new().into_any()
5463            }
5464
5465            fn ui_name() -> &'static str {
5466                "View"
5467            }
5468        }
5469
5470        struct ViewB {
5471            id: usize,
5472        }
5473
5474        impl Entity for ViewB {
5475            type Event = ();
5476        }
5477
5478        impl View for ViewB {
5479            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5480                Empty::new().into_any()
5481            }
5482
5483            fn ui_name() -> &'static str {
5484                "View"
5485            }
5486        }
5487
5488        #[derive(Clone, Default, Deserialize, PartialEq)]
5489        pub struct Action(pub String);
5490
5491        impl_actions!(test, [Action]);
5492
5493        let actions = Rc::new(RefCell::new(Vec::new()));
5494
5495        cx.add_global_action({
5496            let actions = actions.clone();
5497            move |_: &Action, _: &mut AppContext| {
5498                actions.borrow_mut().push("global".to_string());
5499            }
5500        });
5501
5502        cx.add_action({
5503            let actions = actions.clone();
5504            move |view: &mut ViewA, action: &Action, cx| {
5505                assert_eq!(action.0, "bar");
5506                cx.propagate_action();
5507                actions.borrow_mut().push(format!("{} a", view.id));
5508            }
5509        });
5510
5511        cx.add_action({
5512            let actions = actions.clone();
5513            move |view: &mut ViewA, _: &Action, cx| {
5514                if view.id != 1 {
5515                    cx.add_view(|cx| {
5516                        cx.propagate_action(); // Still works on a nested ViewContext
5517                        ViewB { id: 5 }
5518                    });
5519                }
5520                actions.borrow_mut().push(format!("{} b", view.id));
5521            }
5522        });
5523
5524        cx.add_action({
5525            let actions = actions.clone();
5526            move |view: &mut ViewB, _: &Action, cx| {
5527                cx.propagate_action();
5528                actions.borrow_mut().push(format!("{} c", view.id));
5529            }
5530        });
5531
5532        cx.add_action({
5533            let actions = actions.clone();
5534            move |view: &mut ViewB, _: &Action, cx| {
5535                cx.propagate_action();
5536                actions.borrow_mut().push(format!("{} d", view.id));
5537            }
5538        });
5539
5540        cx.capture_action({
5541            let actions = actions.clone();
5542            move |view: &mut ViewA, _: &Action, cx| {
5543                cx.propagate_action();
5544                actions.borrow_mut().push(format!("{} capture", view.id));
5545            }
5546        });
5547
5548        let observed_actions = Rc::new(RefCell::new(Vec::new()));
5549        cx.observe_actions({
5550            let observed_actions = observed_actions.clone();
5551            move |action_id, _| observed_actions.borrow_mut().push(action_id)
5552        })
5553        .detach();
5554
5555        let (window_id, view_1) = cx.add_window(Default::default(), |_| ViewA { id: 1 });
5556        let view_2 = cx.add_view(&view_1, |_| ViewB { id: 2 });
5557        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
5558        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
5559
5560        cx.update_window(window_id, |cx| {
5561            cx.handle_dispatch_action_from_effect(Some(view_4.id()), &Action("bar".to_string()))
5562        });
5563
5564        assert_eq!(
5565            *actions.borrow(),
5566            vec![
5567                "1 capture",
5568                "3 capture",
5569                "4 d",
5570                "4 c",
5571                "3 b",
5572                "3 a",
5573                "2 d",
5574                "2 c",
5575                "1 b"
5576            ]
5577        );
5578        assert_eq!(*observed_actions.borrow(), [Action::default().id()]);
5579
5580        // Remove view_1, which doesn't propagate the action
5581
5582        let (window_id, view_2) = cx.add_window(Default::default(), |_| ViewB { id: 2 });
5583        let view_3 = cx.add_view(&view_2, |_| ViewA { id: 3 });
5584        let view_4 = cx.add_view(&view_3, |_| ViewB { id: 4 });
5585
5586        actions.borrow_mut().clear();
5587        cx.update_window(window_id, |cx| {
5588            cx.handle_dispatch_action_from_effect(Some(view_4.id()), &Action("bar".to_string()))
5589        });
5590
5591        assert_eq!(
5592            *actions.borrow(),
5593            vec![
5594                "3 capture",
5595                "4 d",
5596                "4 c",
5597                "3 b",
5598                "3 a",
5599                "2 d",
5600                "2 c",
5601                "global"
5602            ]
5603        );
5604        assert_eq!(
5605            *observed_actions.borrow(),
5606            [Action::default().id(), Action::default().id()]
5607        );
5608    }
5609
5610    #[crate::test(self)]
5611    fn test_dispatch_keystroke(cx: &mut AppContext) {
5612        #[derive(Clone, Deserialize, PartialEq)]
5613        pub struct Action(String);
5614
5615        impl_actions!(test, [Action]);
5616
5617        struct View {
5618            id: usize,
5619            keymap_context: KeymapContext,
5620        }
5621
5622        impl Entity for View {
5623            type Event = ();
5624        }
5625
5626        impl super::View for View {
5627            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5628                Empty::new().into_any()
5629            }
5630
5631            fn ui_name() -> &'static str {
5632                "View"
5633            }
5634
5635            fn keymap_context(&self, _: &AppContext) -> KeymapContext {
5636                self.keymap_context.clone()
5637            }
5638        }
5639
5640        impl View {
5641            fn new(id: usize) -> Self {
5642                View {
5643                    id,
5644                    keymap_context: KeymapContext::default(),
5645                }
5646            }
5647        }
5648
5649        let mut view_1 = View::new(1);
5650        let mut view_2 = View::new(2);
5651        let mut view_3 = View::new(3);
5652        view_1.keymap_context.add_identifier("a");
5653        view_2.keymap_context.add_identifier("a");
5654        view_2.keymap_context.add_identifier("b");
5655        view_3.keymap_context.add_identifier("a");
5656        view_3.keymap_context.add_identifier("b");
5657        view_3.keymap_context.add_identifier("c");
5658
5659        let (window_id, view_1) = cx.add_window(Default::default(), |_| view_1);
5660        let view_2 = cx.add_view(&view_1, |_| view_2);
5661        let _view_3 = cx.add_view(&view_2, |cx| {
5662            cx.focus_self();
5663            view_3
5664        });
5665
5666        // This binding only dispatches an action on view 2 because that view will have
5667        // "a" and "b" in its context, but not "c".
5668        cx.add_bindings(vec![Binding::new(
5669            "a",
5670            Action("a".to_string()),
5671            Some("a && b && !c"),
5672        )]);
5673
5674        cx.add_bindings(vec![Binding::new("b", Action("b".to_string()), None)]);
5675
5676        // This binding only dispatches an action on views 2 and 3, because they have
5677        // a parent view with a in its context
5678        cx.add_bindings(vec![Binding::new(
5679            "c",
5680            Action("c".to_string()),
5681            Some("b > c"),
5682        )]);
5683
5684        // This binding only dispatches an action on view 2, because they have
5685        // a parent view with a in its context
5686        cx.add_bindings(vec![Binding::new(
5687            "d",
5688            Action("d".to_string()),
5689            Some("a && !b > b"),
5690        )]);
5691
5692        let actions = Rc::new(RefCell::new(Vec::new()));
5693        cx.add_action({
5694            let actions = actions.clone();
5695            move |view: &mut View, action: &Action, cx| {
5696                actions
5697                    .borrow_mut()
5698                    .push(format!("{} {}", view.id, action.0));
5699
5700                if action.0 == "b" {
5701                    cx.propagate_action();
5702                }
5703            }
5704        });
5705
5706        cx.add_global_action({
5707            let actions = actions.clone();
5708            move |action: &Action, _| {
5709                actions.borrow_mut().push(format!("global {}", action.0));
5710            }
5711        });
5712
5713        cx.update_window(window_id, |cx| {
5714            cx.dispatch_keystroke(&Keystroke::parse("a").unwrap())
5715        });
5716        assert_eq!(&*actions.borrow(), &["2 a"]);
5717        actions.borrow_mut().clear();
5718
5719        cx.update_window(window_id, |cx| {
5720            cx.dispatch_keystroke(&Keystroke::parse("b").unwrap());
5721        });
5722
5723        assert_eq!(&*actions.borrow(), &["3 b", "2 b", "1 b", "global b"]);
5724        actions.borrow_mut().clear();
5725
5726        cx.update_window(window_id, |cx| {
5727            cx.dispatch_keystroke(&Keystroke::parse("c").unwrap());
5728        });
5729        assert_eq!(&*actions.borrow(), &["3 c"]);
5730        actions.borrow_mut().clear();
5731
5732        cx.update_window(window_id, |cx| {
5733            cx.dispatch_keystroke(&Keystroke::parse("d").unwrap());
5734        });
5735        assert_eq!(&*actions.borrow(), &["2 d"]);
5736        actions.borrow_mut().clear();
5737    }
5738
5739    #[crate::test(self)]
5740    fn test_keystrokes_for_action(cx: &mut AppContext) {
5741        actions!(test, [Action1, Action2, GlobalAction]);
5742
5743        struct View1 {}
5744        struct View2 {}
5745
5746        impl Entity for View1 {
5747            type Event = ();
5748        }
5749        impl Entity for View2 {
5750            type Event = ();
5751        }
5752
5753        impl super::View for View1 {
5754            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5755                Empty::new().into_any()
5756            }
5757            fn ui_name() -> &'static str {
5758                "View1"
5759            }
5760        }
5761        impl super::View for View2 {
5762            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5763                Empty::new().into_any()
5764            }
5765            fn ui_name() -> &'static str {
5766                "View2"
5767            }
5768        }
5769
5770        let (window_id, view_1) = cx.add_window(Default::default(), |_| View1 {});
5771        let view_2 = cx.add_view(&view_1, |cx| {
5772            cx.focus_self();
5773            View2 {}
5774        });
5775
5776        cx.add_action(|_: &mut View1, _: &Action1, _cx| {});
5777        cx.add_action(|_: &mut View2, _: &Action2, _cx| {});
5778        cx.add_global_action(|_: &GlobalAction, _| {});
5779
5780        cx.add_bindings(vec![
5781            Binding::new("a", Action1, Some("View1")),
5782            Binding::new("b", Action2, Some("View1 > View2")),
5783            Binding::new("c", GlobalAction, Some("View3")), // View 3 does not exist
5784        ]);
5785
5786        cx.update_window(window_id, |cx| {
5787            // Sanity check
5788            assert_eq!(
5789                cx.keystrokes_for_action(view_1.id(), &Action1)
5790                    .unwrap()
5791                    .as_slice(),
5792                &[Keystroke::parse("a").unwrap()]
5793            );
5794            assert_eq!(
5795                cx.keystrokes_for_action(view_2.id(), &Action2)
5796                    .unwrap()
5797                    .as_slice(),
5798                &[Keystroke::parse("b").unwrap()]
5799            );
5800
5801            // The 'a' keystroke propagates up the view tree from view_2
5802            // to view_1. The action, Action1, is handled by view_1.
5803            assert_eq!(
5804                cx.keystrokes_for_action(view_2.id(), &Action1)
5805                    .unwrap()
5806                    .as_slice(),
5807                &[Keystroke::parse("a").unwrap()]
5808            );
5809
5810            // Actions that are handled below the current view don't have bindings
5811            assert_eq!(cx.keystrokes_for_action(view_1.id(), &Action2), None);
5812
5813            // Actions that are handled in other branches of the tree should not have a binding
5814            assert_eq!(cx.keystrokes_for_action(view_2.id(), &GlobalAction), None);
5815
5816            // Check that global actions do not have a binding, even if a binding does exist in another view
5817            assert_eq!(
5818                &available_actions(view_1.id(), cx),
5819                &[
5820                    ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
5821                    ("test::GlobalAction", vec![])
5822                ],
5823            );
5824
5825            // Check that view 1 actions and bindings are available even when called from view 2
5826            assert_eq!(
5827                &available_actions(view_2.id(), cx),
5828                &[
5829                    ("test::Action1", vec![Keystroke::parse("a").unwrap()]),
5830                    ("test::Action2", vec![Keystroke::parse("b").unwrap()]),
5831                    ("test::GlobalAction", vec![]),
5832                ],
5833            );
5834        });
5835
5836        // Produces a list of actions and key bindings
5837        fn available_actions(
5838            view_id: usize,
5839            cx: &WindowContext,
5840        ) -> Vec<(&'static str, Vec<Keystroke>)> {
5841            cx.available_actions(view_id)
5842                .map(|(action_name, _, bindings)| {
5843                    (
5844                        action_name,
5845                        bindings
5846                            .iter()
5847                            .map(|binding| binding.keystrokes()[0].clone())
5848                            .collect::<Vec<_>>(),
5849                    )
5850                })
5851                .sorted_by(|(name1, _), (name2, _)| name1.cmp(name2))
5852                .collect()
5853        }
5854    }
5855
5856    #[crate::test(self)]
5857    async fn test_model_condition(cx: &mut TestAppContext) {
5858        struct Counter(usize);
5859
5860        impl super::Entity for Counter {
5861            type Event = ();
5862        }
5863
5864        impl Counter {
5865            fn inc(&mut self, cx: &mut ModelContext<Self>) {
5866                self.0 += 1;
5867                cx.notify();
5868            }
5869        }
5870
5871        let model = cx.add_model(|_| Counter(0));
5872
5873        let condition1 = model.condition(cx, |model, _| model.0 == 2);
5874        let condition2 = model.condition(cx, |model, _| model.0 == 3);
5875        smol::pin!(condition1, condition2);
5876
5877        model.update(cx, |model, cx| model.inc(cx));
5878        assert_eq!(poll_once(&mut condition1).await, None);
5879        assert_eq!(poll_once(&mut condition2).await, None);
5880
5881        model.update(cx, |model, cx| model.inc(cx));
5882        assert_eq!(poll_once(&mut condition1).await, Some(()));
5883        assert_eq!(poll_once(&mut condition2).await, None);
5884
5885        model.update(cx, |model, cx| model.inc(cx));
5886        assert_eq!(poll_once(&mut condition2).await, Some(()));
5887
5888        model.update(cx, |_, cx| cx.notify());
5889    }
5890
5891    #[crate::test(self)]
5892    #[should_panic]
5893    async fn test_model_condition_timeout(cx: &mut TestAppContext) {
5894        struct Model;
5895
5896        impl super::Entity for Model {
5897            type Event = ();
5898        }
5899
5900        let model = cx.add_model(|_| Model);
5901        model.condition(cx, |_, _| false).await;
5902    }
5903
5904    #[crate::test(self)]
5905    #[should_panic(expected = "model dropped with pending condition")]
5906    async fn test_model_condition_panic_on_drop(cx: &mut TestAppContext) {
5907        struct Model;
5908
5909        impl super::Entity for Model {
5910            type Event = ();
5911        }
5912
5913        let model = cx.add_model(|_| Model);
5914        let condition = model.condition(cx, |_, _| false);
5915        cx.update(|_| drop(model));
5916        condition.await;
5917    }
5918
5919    #[crate::test(self)]
5920    async fn test_view_condition(cx: &mut TestAppContext) {
5921        struct Counter(usize);
5922
5923        impl super::Entity for Counter {
5924            type Event = ();
5925        }
5926
5927        impl super::View for Counter {
5928            fn ui_name() -> &'static str {
5929                "test view"
5930            }
5931
5932            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5933                Empty::new().into_any()
5934            }
5935        }
5936
5937        impl Counter {
5938            fn inc(&mut self, cx: &mut ViewContext<Self>) {
5939                self.0 += 1;
5940                cx.notify();
5941            }
5942        }
5943
5944        let (_, view) = cx.add_window(|_| Counter(0));
5945
5946        let condition1 = view.condition(cx, |view, _| view.0 == 2);
5947        let condition2 = view.condition(cx, |view, _| view.0 == 3);
5948        smol::pin!(condition1, condition2);
5949
5950        view.update(cx, |view, cx| view.inc(cx));
5951        assert_eq!(poll_once(&mut condition1).await, None);
5952        assert_eq!(poll_once(&mut condition2).await, None);
5953
5954        view.update(cx, |view, cx| view.inc(cx));
5955        assert_eq!(poll_once(&mut condition1).await, Some(()));
5956        assert_eq!(poll_once(&mut condition2).await, None);
5957
5958        view.update(cx, |view, cx| view.inc(cx));
5959        assert_eq!(poll_once(&mut condition2).await, Some(()));
5960        view.update(cx, |_, cx| cx.notify());
5961    }
5962
5963    #[crate::test(self)]
5964    #[should_panic]
5965    async fn test_view_condition_timeout(cx: &mut TestAppContext) {
5966        let (_, view) = cx.add_window(|_| TestView::default());
5967        view.condition(cx, |_, _| false).await;
5968    }
5969
5970    #[crate::test(self)]
5971    #[should_panic(expected = "view dropped with pending condition")]
5972    async fn test_view_condition_panic_on_drop(cx: &mut TestAppContext) {
5973        let (_, root_view) = cx.add_window(|_| TestView::default());
5974        let view = cx.add_view(&root_view, |_| TestView::default());
5975
5976        let condition = view.condition(cx, |_, _| false);
5977        cx.update(|_| drop(view));
5978        condition.await;
5979    }
5980
5981    #[crate::test(self)]
5982    fn test_refresh_windows(cx: &mut AppContext) {
5983        struct View(usize);
5984
5985        impl super::Entity for View {
5986            type Event = ();
5987        }
5988
5989        impl super::View for View {
5990            fn ui_name() -> &'static str {
5991                "test view"
5992            }
5993
5994            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
5995                Empty::new().into_any_named(format!("render count: {}", post_inc(&mut self.0)))
5996            }
5997        }
5998
5999        let (window_id, root_view) = cx.add_window(Default::default(), |_| View(0));
6000        cx.update_window(window_id, |cx| {
6001            assert_eq!(
6002                cx.window.rendered_views[&root_view.id()].name(),
6003                Some("render count: 0")
6004            );
6005        });
6006
6007        let view = cx.add_view(&root_view, |cx| {
6008            cx.refresh_windows();
6009            View(0)
6010        });
6011
6012        cx.update_window(window_id, |cx| {
6013            assert_eq!(
6014                cx.window.rendered_views[&root_view.id()].name(),
6015                Some("render count: 1")
6016            );
6017            assert_eq!(
6018                cx.window.rendered_views[&view.id()].name(),
6019                Some("render count: 0")
6020            );
6021        });
6022
6023        cx.update(|cx| cx.refresh_windows());
6024
6025        cx.update_window(window_id, |cx| {
6026            assert_eq!(
6027                cx.window.rendered_views[&root_view.id()].name(),
6028                Some("render count: 2")
6029            );
6030            assert_eq!(
6031                cx.window.rendered_views[&view.id()].name(),
6032                Some("render count: 1")
6033            );
6034        });
6035
6036        cx.update(|cx| {
6037            cx.refresh_windows();
6038            drop(view);
6039        });
6040
6041        cx.update_window(window_id, |cx| {
6042            assert_eq!(
6043                cx.window.rendered_views[&root_view.id()].name(),
6044                Some("render count: 3")
6045            );
6046            assert_eq!(cx.window.rendered_views.len(), 1);
6047        });
6048    }
6049
6050    #[crate::test(self)]
6051    async fn test_labeled_tasks(cx: &mut TestAppContext) {
6052        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6053        let (mut sender, mut reciever) = postage::oneshot::channel::<()>();
6054        let task = cx
6055            .update(|cx| cx.spawn_labeled("Test Label", |_| async move { reciever.recv().await }));
6056
6057        assert_eq!(
6058            Some("Test Label"),
6059            cx.update(|cx| cx.active_labeled_tasks().next())
6060        );
6061        sender
6062            .send(())
6063            .await
6064            .expect("Could not send message to complete task");
6065        task.await;
6066
6067        assert_eq!(None, cx.update(|cx| cx.active_labeled_tasks().next()));
6068    }
6069
6070    #[crate::test(self)]
6071    async fn test_window_activation(cx: &mut TestAppContext) {
6072        struct View(&'static str);
6073
6074        impl super::Entity for View {
6075            type Event = ();
6076        }
6077
6078        impl super::View for View {
6079            fn ui_name() -> &'static str {
6080                "test view"
6081            }
6082
6083            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6084                Empty::new().into_any()
6085            }
6086        }
6087
6088        let events = Rc::new(RefCell::new(Vec::new()));
6089        let (window_1, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6090            cx.observe_window_activation({
6091                let events = events.clone();
6092                move |this, active, _| events.borrow_mut().push((this.0, active))
6093            })
6094            .detach();
6095            View("window 1")
6096        });
6097        assert_eq!(mem::take(&mut *events.borrow_mut()), [("window 1", true)]);
6098
6099        let (window_2, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6100            cx.observe_window_activation({
6101                let events = events.clone();
6102                move |this, active, _| events.borrow_mut().push((this.0, active))
6103            })
6104            .detach();
6105            View("window 2")
6106        });
6107        assert_eq!(
6108            mem::take(&mut *events.borrow_mut()),
6109            [("window 1", false), ("window 2", true)]
6110        );
6111
6112        let (window_3, _) = cx.add_window(|cx: &mut ViewContext<View>| {
6113            cx.observe_window_activation({
6114                let events = events.clone();
6115                move |this, active, _| events.borrow_mut().push((this.0, active))
6116            })
6117            .detach();
6118            View("window 3")
6119        });
6120        assert_eq!(
6121            mem::take(&mut *events.borrow_mut()),
6122            [("window 2", false), ("window 3", true)]
6123        );
6124
6125        cx.simulate_window_activation(Some(window_2));
6126        assert_eq!(
6127            mem::take(&mut *events.borrow_mut()),
6128            [("window 3", false), ("window 2", true)]
6129        );
6130
6131        cx.simulate_window_activation(Some(window_1));
6132        assert_eq!(
6133            mem::take(&mut *events.borrow_mut()),
6134            [("window 2", false), ("window 1", true)]
6135        );
6136
6137        cx.simulate_window_activation(Some(window_3));
6138        assert_eq!(
6139            mem::take(&mut *events.borrow_mut()),
6140            [("window 1", false), ("window 3", true)]
6141        );
6142
6143        cx.simulate_window_activation(Some(window_3));
6144        assert_eq!(mem::take(&mut *events.borrow_mut()), []);
6145    }
6146
6147    #[crate::test(self)]
6148    fn test_child_view(cx: &mut TestAppContext) {
6149        struct Child {
6150            rendered: Rc<Cell<bool>>,
6151            dropped: Rc<Cell<bool>>,
6152        }
6153
6154        impl super::Entity for Child {
6155            type Event = ();
6156        }
6157
6158        impl super::View for Child {
6159            fn ui_name() -> &'static str {
6160                "child view"
6161            }
6162
6163            fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6164                self.rendered.set(true);
6165                Empty::new().into_any()
6166            }
6167        }
6168
6169        impl Drop for Child {
6170            fn drop(&mut self) {
6171                self.dropped.set(true);
6172            }
6173        }
6174
6175        struct Parent {
6176            child: Option<ViewHandle<Child>>,
6177        }
6178
6179        impl super::Entity for Parent {
6180            type Event = ();
6181        }
6182
6183        impl super::View for Parent {
6184            fn ui_name() -> &'static str {
6185                "parent view"
6186            }
6187
6188            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
6189                if let Some(child) = self.child.as_ref() {
6190                    ChildView::new(child, cx).into_any()
6191                } else {
6192                    Empty::new().into_any()
6193                }
6194            }
6195        }
6196
6197        let child_rendered = Rc::new(Cell::new(false));
6198        let child_dropped = Rc::new(Cell::new(false));
6199        let (_, root_view) = cx.add_window(|cx| Parent {
6200            child: Some(cx.add_view(|_| Child {
6201                rendered: child_rendered.clone(),
6202                dropped: child_dropped.clone(),
6203            })),
6204        });
6205        assert!(child_rendered.take());
6206        assert!(!child_dropped.take());
6207
6208        root_view.update(cx, |view, cx| {
6209            view.child.take();
6210            cx.notify();
6211        });
6212        assert!(!child_rendered.take());
6213        assert!(child_dropped.take());
6214    }
6215
6216    #[derive(Default)]
6217    struct TestView {
6218        events: Vec<String>,
6219    }
6220
6221    impl Entity for TestView {
6222        type Event = String;
6223    }
6224
6225    impl View for TestView {
6226        fn ui_name() -> &'static str {
6227            "TestView"
6228        }
6229
6230        fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
6231            Empty::new().into_any()
6232        }
6233    }
6234}