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