app.rs

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