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