app.rs

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