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