app.rs

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