app.rs

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