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