app.rs

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