app.rs

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