app.rs

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