window.rs

   1use crate::{
   2    px, transparent_black, Action, AnyDrag, AnyView, AppContext, Arena, AsyncWindowContext, Bounds,
   3    Context, Corners, CursorStyle, DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId,
   4    Edges, Effect, Entity, EntityId, EventEmitter, FileDropEvent, Flatten, Global, GlobalElementId,
   5    Hsla, KeyBinding, KeyDownEvent, KeyMatch, KeymatchResult, Keystroke, KeystrokeEvent, Model,
   6    ModelContext, Modifiers, MouseButton, MouseMoveEvent, MouseUpEvent, Pixels, PlatformAtlas,
   7    PlatformDisplay, PlatformInput, PlatformWindow, Point, PromptLevel, Render, ScaledPixels,
   8    SharedString, Size, SubscriberSet, Subscription, TaffyLayoutEngine, Task, TextStyle,
   9    TextStyleRefinement, View, VisualContext, WeakView, WindowAppearance, WindowBounds,
  10    WindowOptions, WindowTextSystem,
  11};
  12use anyhow::{anyhow, Context as _, Result};
  13use collections::FxHashSet;
  14use derive_more::{Deref, DerefMut};
  15use futures::channel::oneshot;
  16use parking_lot::RwLock;
  17use refineable::Refineable;
  18use slotmap::SlotMap;
  19use smallvec::SmallVec;
  20use std::{
  21    any::{Any, TypeId},
  22    borrow::{Borrow, BorrowMut},
  23    cell::{Cell, RefCell},
  24    fmt::{Debug, Display},
  25    future::Future,
  26    hash::{Hash, Hasher},
  27    marker::PhantomData,
  28    mem,
  29    rc::Rc,
  30    sync::{
  31        atomic::{AtomicUsize, Ordering::SeqCst},
  32        Arc,
  33    },
  34    time::{Duration, Instant},
  35};
  36use util::{measure, ResultExt};
  37
  38mod element_cx;
  39mod prompts;
  40
  41pub use element_cx::*;
  42pub use prompts::*;
  43
  44/// Represents the two different phases when dispatching events.
  45#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
  46pub enum DispatchPhase {
  47    /// After the capture phase comes the bubble phase, in which mouse event listeners are
  48    /// invoked front to back and keyboard event listeners are invoked from the focused element
  49    /// to the root of the element tree. This is the phase you'll most commonly want to use when
  50    /// registering event listeners.
  51    #[default]
  52    Bubble,
  53    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
  54    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
  55    /// is used for special purposes such as clearing the "pressed" state for click events. If
  56    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
  57    /// outside of the immediate region may rely on detecting non-local events during this phase.
  58    Capture,
  59}
  60
  61impl DispatchPhase {
  62    /// Returns true if this represents the "bubble" phase.
  63    pub fn bubble(self) -> bool {
  64        self == DispatchPhase::Bubble
  65    }
  66
  67    /// Returns true if this represents the "capture" phase.
  68    pub fn capture(self) -> bool {
  69        self == DispatchPhase::Capture
  70    }
  71}
  72
  73type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
  74
  75type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
  76
  77struct FocusEvent {
  78    previous_focus_path: SmallVec<[FocusId; 8]>,
  79    current_focus_path: SmallVec<[FocusId; 8]>,
  80}
  81
  82slotmap::new_key_type! {
  83    /// A globally unique identifier for a focusable element.
  84    pub struct FocusId;
  85}
  86
  87thread_local! {
  88    pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(8 * 1024 * 1024));
  89}
  90
  91impl FocusId {
  92    /// Obtains whether the element associated with this handle is currently focused.
  93    pub fn is_focused(&self, cx: &WindowContext) -> bool {
  94        cx.window.focus == Some(*self)
  95    }
  96
  97    /// Obtains whether the element associated with this handle contains the focused
  98    /// element or is itself focused.
  99    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 100        cx.focused()
 101            .map_or(false, |focused| self.contains(focused.id, cx))
 102    }
 103
 104    /// Obtains whether the element associated with this handle is contained within the
 105    /// focused element or is itself focused.
 106    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 107        let focused = cx.focused();
 108        focused.map_or(false, |focused| focused.id.contains(*self, cx))
 109    }
 110
 111    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 112    pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
 113        cx.window
 114            .rendered_frame
 115            .dispatch_tree
 116            .focus_contains(*self, other)
 117    }
 118}
 119
 120/// A handle which can be used to track and manipulate the focused element in a window.
 121pub struct FocusHandle {
 122    pub(crate) id: FocusId,
 123    handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 124}
 125
 126impl std::fmt::Debug for FocusHandle {
 127    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 128        f.write_fmt(format_args!("FocusHandle({:?})", self.id))
 129    }
 130}
 131
 132impl FocusHandle {
 133    pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
 134        let id = handles.write().insert(AtomicUsize::new(1));
 135        Self {
 136            id,
 137            handles: handles.clone(),
 138        }
 139    }
 140
 141    pub(crate) fn for_id(
 142        id: FocusId,
 143        handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 144    ) -> Option<Self> {
 145        let lock = handles.read();
 146        let ref_count = lock.get(id)?;
 147        if ref_count.load(SeqCst) == 0 {
 148            None
 149        } else {
 150            ref_count.fetch_add(1, SeqCst);
 151            Some(Self {
 152                id,
 153                handles: handles.clone(),
 154            })
 155        }
 156    }
 157
 158    /// Moves the focus to the element associated with this handle.
 159    pub fn focus(&self, cx: &mut WindowContext) {
 160        cx.focus(self)
 161    }
 162
 163    /// Obtains whether the element associated with this handle is currently focused.
 164    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 165        self.id.is_focused(cx)
 166    }
 167
 168    /// Obtains whether the element associated with this handle contains the focused
 169    /// element or is itself focused.
 170    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 171        self.id.contains_focused(cx)
 172    }
 173
 174    /// Obtains whether the element associated with this handle is contained within the
 175    /// focused element or is itself focused.
 176    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 177        self.id.within_focused(cx)
 178    }
 179
 180    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 181    pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
 182        self.id.contains(other.id, cx)
 183    }
 184}
 185
 186impl Clone for FocusHandle {
 187    fn clone(&self) -> Self {
 188        Self::for_id(self.id, &self.handles).unwrap()
 189    }
 190}
 191
 192impl PartialEq for FocusHandle {
 193    fn eq(&self, other: &Self) -> bool {
 194        self.id == other.id
 195    }
 196}
 197
 198impl Eq for FocusHandle {}
 199
 200impl Drop for FocusHandle {
 201    fn drop(&mut self) {
 202        self.handles
 203            .read()
 204            .get(self.id)
 205            .unwrap()
 206            .fetch_sub(1, SeqCst);
 207    }
 208}
 209
 210/// FocusableView allows users of your view to easily
 211/// focus it (using cx.focus_view(view))
 212pub trait FocusableView: 'static + Render {
 213    /// Returns the focus handle associated with this view.
 214    fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
 215}
 216
 217/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
 218/// where the lifecycle of the view is handled by another view.
 219pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
 220
 221impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
 222
 223/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
 224pub struct DismissEvent;
 225
 226type FrameCallback = Box<dyn FnOnce(&mut WindowContext)>;
 227
 228// Holds the state for a specific window.
 229#[doc(hidden)]
 230pub struct Window {
 231    pub(crate) handle: AnyWindowHandle,
 232    pub(crate) removed: bool,
 233    pub(crate) platform_window: Box<dyn PlatformWindow>,
 234    display_id: DisplayId,
 235    sprite_atlas: Arc<dyn PlatformAtlas>,
 236    text_system: Arc<WindowTextSystem>,
 237    pub(crate) rem_size: Pixels,
 238    pub(crate) viewport_size: Size<Pixels>,
 239    layout_engine: Option<TaffyLayoutEngine>,
 240    pub(crate) root_view: Option<AnyView>,
 241    pub(crate) element_id_stack: GlobalElementId,
 242    pub(crate) text_style_stack: Vec<TextStyleRefinement>,
 243    pub(crate) rendered_frame: Frame,
 244    pub(crate) next_frame: Frame,
 245    pub(crate) next_hitbox_id: HitboxId,
 246    next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
 247    pub(crate) dirty_views: FxHashSet<EntityId>,
 248    pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 249    focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
 250    focus_lost_listeners: SubscriberSet<(), AnyObserver>,
 251    default_prevented: bool,
 252    mouse_position: Point<Pixels>,
 253    mouse_hit_test: HitTest,
 254    modifiers: Modifiers,
 255    scale_factor: f32,
 256    bounds: WindowBounds,
 257    bounds_observers: SubscriberSet<(), AnyObserver>,
 258    appearance: WindowAppearance,
 259    appearance_observers: SubscriberSet<(), AnyObserver>,
 260    active: Rc<Cell<bool>>,
 261    pub(crate) dirty: Rc<Cell<bool>>,
 262    pub(crate) needs_present: Rc<Cell<bool>>,
 263    pub(crate) last_input_timestamp: Rc<Cell<Instant>>,
 264    pub(crate) refreshing: bool,
 265    pub(crate) draw_phase: DrawPhase,
 266    activation_observers: SubscriberSet<(), AnyObserver>,
 267    pub(crate) focus: Option<FocusId>,
 268    focus_enabled: bool,
 269    pending_input: Option<PendingInput>,
 270    prompt: Option<RenderablePromptHandle>,
 271}
 272
 273#[derive(Clone, Copy, Debug, Eq, PartialEq)]
 274pub(crate) enum DrawPhase {
 275    None,
 276    Layout,
 277    Paint,
 278    Focus,
 279}
 280
 281#[derive(Default, Debug)]
 282struct PendingInput {
 283    keystrokes: SmallVec<[Keystroke; 1]>,
 284    bindings: SmallVec<[KeyBinding; 1]>,
 285    focus: Option<FocusId>,
 286    timer: Option<Task<()>>,
 287}
 288
 289impl PendingInput {
 290    fn input(&self) -> String {
 291        self.keystrokes
 292            .iter()
 293            .flat_map(|k| k.ime_key.clone())
 294            .collect::<Vec<String>>()
 295            .join("")
 296    }
 297
 298    fn used_by_binding(&self, binding: &KeyBinding) -> bool {
 299        if self.keystrokes.is_empty() {
 300            return true;
 301        }
 302        let keystroke = &self.keystrokes[0];
 303        for candidate in keystroke.match_candidates() {
 304            if binding.match_keystrokes(&[candidate]) == KeyMatch::Pending {
 305                return true;
 306            }
 307        }
 308        false
 309    }
 310}
 311
 312pub(crate) struct ElementStateBox {
 313    pub(crate) inner: Box<dyn Any>,
 314    #[cfg(debug_assertions)]
 315    pub(crate) type_name: &'static str,
 316}
 317
 318impl Window {
 319    pub(crate) fn new(
 320        handle: AnyWindowHandle,
 321        options: WindowOptions,
 322        cx: &mut AppContext,
 323    ) -> Self {
 324        let platform_window = cx.platform.open_window(handle, options);
 325        let display_id = platform_window.display().id();
 326        let sprite_atlas = platform_window.sprite_atlas();
 327        let mouse_position = platform_window.mouse_position();
 328        let modifiers = platform_window.modifiers();
 329        let content_size = platform_window.content_size();
 330        let scale_factor = platform_window.scale_factor();
 331        let bounds = platform_window.bounds();
 332        let appearance = platform_window.appearance();
 333        let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
 334        let dirty = Rc::new(Cell::new(true));
 335        let active = Rc::new(Cell::new(false));
 336        let needs_present = Rc::new(Cell::new(false));
 337        let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
 338        let last_input_timestamp = Rc::new(Cell::new(Instant::now()));
 339
 340        platform_window.on_close(Box::new({
 341            let mut cx = cx.to_async();
 342            move || {
 343                let _ = handle.update(&mut cx, |_, cx| cx.remove_window());
 344            }
 345        }));
 346        platform_window.on_request_frame(Box::new({
 347            let mut cx = cx.to_async();
 348            let dirty = dirty.clone();
 349            let active = active.clone();
 350            let needs_present = needs_present.clone();
 351            let next_frame_callbacks = next_frame_callbacks.clone();
 352            let last_input_timestamp = last_input_timestamp.clone();
 353            move || {
 354                let next_frame_callbacks = next_frame_callbacks.take();
 355                if !next_frame_callbacks.is_empty() {
 356                    handle
 357                        .update(&mut cx, |_, cx| {
 358                            for callback in next_frame_callbacks {
 359                                callback(cx);
 360                            }
 361                        })
 362                        .log_err();
 363                }
 364
 365                // Keep presenting the current scene for 1 extra second since the
 366                // last input to prevent the display from underclocking the refresh rate.
 367                let needs_present = needs_present.get()
 368                    || (active.get()
 369                        && last_input_timestamp.get().elapsed() < Duration::from_secs(1));
 370
 371                if dirty.get() {
 372                    measure("frame duration", || {
 373                        handle
 374                            .update(&mut cx, |_, cx| {
 375                                cx.draw();
 376                                cx.present();
 377                            })
 378                            .log_err();
 379                    })
 380                } else if needs_present {
 381                    handle.update(&mut cx, |_, cx| cx.present()).log_err();
 382                }
 383            }
 384        }));
 385        platform_window.on_resize(Box::new({
 386            let mut cx = cx.to_async();
 387            move |_, _| {
 388                handle
 389                    .update(&mut cx, |_, cx| cx.window_bounds_changed())
 390                    .log_err();
 391            }
 392        }));
 393        platform_window.on_moved(Box::new({
 394            let mut cx = cx.to_async();
 395            move || {
 396                handle
 397                    .update(&mut cx, |_, cx| cx.window_bounds_changed())
 398                    .log_err();
 399            }
 400        }));
 401        platform_window.on_appearance_changed(Box::new({
 402            let mut cx = cx.to_async();
 403            move || {
 404                handle
 405                    .update(&mut cx, |_, cx| cx.appearance_changed())
 406                    .log_err();
 407            }
 408        }));
 409        platform_window.on_active_status_change(Box::new({
 410            let mut cx = cx.to_async();
 411            move |active| {
 412                handle
 413                    .update(&mut cx, |_, cx| {
 414                        cx.window.active.set(active);
 415                        cx.window
 416                            .activation_observers
 417                            .clone()
 418                            .retain(&(), |callback| callback(cx));
 419                    })
 420                    .log_err();
 421            }
 422        }));
 423
 424        platform_window.on_input({
 425            let mut cx = cx.to_async();
 426            Box::new(move |event| {
 427                handle
 428                    .update(&mut cx, |_, cx| cx.dispatch_event(event))
 429                    .log_err()
 430                    .unwrap_or(false)
 431            })
 432        });
 433
 434        Window {
 435            handle,
 436            removed: false,
 437            platform_window,
 438            display_id,
 439            sprite_atlas,
 440            text_system,
 441            rem_size: px(16.),
 442            viewport_size: content_size,
 443            layout_engine: Some(TaffyLayoutEngine::new()),
 444            root_view: None,
 445            element_id_stack: GlobalElementId::default(),
 446            text_style_stack: Vec::new(),
 447            rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 448            next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 449            next_frame_callbacks,
 450            next_hitbox_id: HitboxId::default(),
 451            dirty_views: FxHashSet::default(),
 452            focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
 453            focus_listeners: SubscriberSet::new(),
 454            focus_lost_listeners: SubscriberSet::new(),
 455            default_prevented: true,
 456            mouse_position,
 457            mouse_hit_test: HitTest::default(),
 458            modifiers,
 459            scale_factor,
 460            bounds,
 461            bounds_observers: SubscriberSet::new(),
 462            appearance,
 463            appearance_observers: SubscriberSet::new(),
 464            active,
 465            dirty,
 466            needs_present,
 467            last_input_timestamp,
 468            refreshing: false,
 469            draw_phase: DrawPhase::None,
 470            activation_observers: SubscriberSet::new(),
 471            focus: None,
 472            focus_enabled: true,
 473            pending_input: None,
 474            prompt: None,
 475        }
 476    }
 477    fn new_focus_listener(
 478        &mut self,
 479        value: AnyWindowFocusListener,
 480    ) -> (Subscription, impl FnOnce()) {
 481        self.focus_listeners.insert((), value)
 482    }
 483}
 484
 485/// Indicates which region of the window is visible. Content falling outside of this mask will not be
 486/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
 487/// to leave room to support more complex shapes in the future.
 488#[derive(Clone, Debug, Default, PartialEq, Eq)]
 489#[repr(C)]
 490pub struct ContentMask<P: Clone + Default + Debug> {
 491    /// The bounds
 492    pub bounds: Bounds<P>,
 493}
 494
 495impl ContentMask<Pixels> {
 496    /// Scale the content mask's pixel units by the given scaling factor.
 497    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
 498        ContentMask {
 499            bounds: self.bounds.scale(factor),
 500        }
 501    }
 502
 503    /// Intersect the content mask with the given content mask.
 504    pub fn intersect(&self, other: &Self) -> Self {
 505        let bounds = self.bounds.intersect(&other.bounds);
 506        ContentMask { bounds }
 507    }
 508}
 509
 510/// Provides access to application state in the context of a single window. Derefs
 511/// to an [`AppContext`], so you can also pass a [`WindowContext`] to any method that takes
 512/// an [`AppContext`] and call any [`AppContext`] methods.
 513pub struct WindowContext<'a> {
 514    pub(crate) app: &'a mut AppContext,
 515    pub(crate) window: &'a mut Window,
 516}
 517
 518impl<'a> WindowContext<'a> {
 519    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
 520        Self { app, window }
 521    }
 522
 523    /// Obtain a handle to the window that belongs to this context.
 524    pub fn window_handle(&self) -> AnyWindowHandle {
 525        self.window.handle
 526    }
 527
 528    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
 529    pub fn refresh(&mut self) {
 530        if self.window.draw_phase == DrawPhase::None {
 531            self.window.refreshing = true;
 532            self.window.dirty.set(true);
 533        }
 534    }
 535
 536    /// Close this window.
 537    pub fn remove_window(&mut self) {
 538        self.window.removed = true;
 539    }
 540
 541    /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
 542    /// for elements rendered within this window.
 543    pub fn focus_handle(&mut self) -> FocusHandle {
 544        FocusHandle::new(&self.window.focus_handles)
 545    }
 546
 547    /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
 548    pub fn focused(&self) -> Option<FocusHandle> {
 549        self.window
 550            .focus
 551            .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
 552    }
 553
 554    /// Move focus to the element associated with the given [`FocusHandle`].
 555    pub fn focus(&mut self, handle: &FocusHandle) {
 556        if !self.window.focus_enabled || self.window.focus == Some(handle.id) {
 557            return;
 558        }
 559
 560        self.window.focus = Some(handle.id);
 561        self.window
 562            .rendered_frame
 563            .dispatch_tree
 564            .clear_pending_keystrokes();
 565        self.refresh();
 566    }
 567
 568    /// Remove focus from all elements within this context's window.
 569    pub fn blur(&mut self) {
 570        if !self.window.focus_enabled {
 571            return;
 572        }
 573
 574        self.window.focus = None;
 575        self.refresh();
 576    }
 577
 578    /// Blur the window and don't allow anything in it to be focused again.
 579    pub fn disable_focus(&mut self) {
 580        self.blur();
 581        self.window.focus_enabled = false;
 582    }
 583
 584    /// Accessor for the text system.
 585    pub fn text_system(&self) -> &Arc<WindowTextSystem> {
 586        &self.window.text_system
 587    }
 588
 589    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
 590    pub fn text_style(&self) -> TextStyle {
 591        let mut style = TextStyle::default();
 592        for refinement in &self.window.text_style_stack {
 593            style.refine(refinement);
 594        }
 595        style
 596    }
 597
 598    /// Dispatch the given action on the currently focused element.
 599    pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
 600        let focus_handle = self.focused();
 601
 602        let window = self.window.handle;
 603        self.app.defer(move |cx| {
 604            cx.propagate_event = true;
 605            window
 606                .update(cx, |_, cx| {
 607                    let node_id = focus_handle
 608                        .and_then(|handle| {
 609                            cx.window
 610                                .rendered_frame
 611                                .dispatch_tree
 612                                .focusable_node_id(handle.id)
 613                        })
 614                        .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
 615
 616                    cx.dispatch_action_on_node(node_id, action.as_ref());
 617                })
 618                .log_err();
 619            if cx.propagate_event {
 620                cx.dispatch_global_action(action.as_ref());
 621            }
 622        })
 623    }
 624
 625    pub(crate) fn dispatch_keystroke_observers(
 626        &mut self,
 627        event: &dyn Any,
 628        action: Option<Box<dyn Action>>,
 629    ) {
 630        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
 631            return;
 632        };
 633
 634        self.keystroke_observers
 635            .clone()
 636            .retain(&(), move |callback| {
 637                (callback)(
 638                    &KeystrokeEvent {
 639                        keystroke: key_down_event.keystroke.clone(),
 640                        action: action.as_ref().map(|action| action.boxed_clone()),
 641                    },
 642                    self,
 643                );
 644                true
 645            });
 646    }
 647
 648    pub(crate) fn clear_pending_keystrokes(&mut self) {
 649        self.window
 650            .rendered_frame
 651            .dispatch_tree
 652            .clear_pending_keystrokes();
 653        self.window
 654            .next_frame
 655            .dispatch_tree
 656            .clear_pending_keystrokes();
 657    }
 658
 659    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
 660    /// that are currently on the stack to be returned to the app.
 661    pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
 662        let handle = self.window.handle;
 663        self.app.defer(move |cx| {
 664            handle.update(cx, |_, cx| f(cx)).ok();
 665        });
 666    }
 667
 668    /// Subscribe to events emitted by a model or view.
 669    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
 670    /// The callback will be invoked a handle to the emitting entity (either a [`View`] or [`Model`]), the event, and a window context for the current window.
 671    pub fn subscribe<Emitter, E, Evt>(
 672        &mut self,
 673        entity: &E,
 674        mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
 675    ) -> Subscription
 676    where
 677        Emitter: EventEmitter<Evt>,
 678        E: Entity<Emitter>,
 679        Evt: 'static,
 680    {
 681        let entity_id = entity.entity_id();
 682        let entity = entity.downgrade();
 683        let window_handle = self.window.handle;
 684        self.app.new_subscription(
 685            entity_id,
 686            (
 687                TypeId::of::<Evt>(),
 688                Box::new(move |event, cx| {
 689                    window_handle
 690                        .update(cx, |_, cx| {
 691                            if let Some(handle) = E::upgrade_from(&entity) {
 692                                let event = event.downcast_ref().expect("invalid event type");
 693                                on_event(handle, event, cx);
 694                                true
 695                            } else {
 696                                false
 697                            }
 698                        })
 699                        .unwrap_or(false)
 700                }),
 701            ),
 702        )
 703    }
 704
 705    /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
 706    /// await points in async code.
 707    pub fn to_async(&self) -> AsyncWindowContext {
 708        AsyncWindowContext::new(self.app.to_async(), self.window.handle)
 709    }
 710
 711    /// Schedule the given closure to be run directly after the current frame is rendered.
 712    pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
 713        RefCell::borrow_mut(&self.window.next_frame_callbacks).push(Box::new(callback));
 714    }
 715
 716    /// Spawn the future returned by the given closure on the application thread pool.
 717    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
 718    /// use within your future.
 719    pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
 720    where
 721        R: 'static,
 722        Fut: Future<Output = R> + 'static,
 723    {
 724        self.app
 725            .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
 726    }
 727
 728    /// Updates the global of the given type. The given closure is given simultaneous mutable
 729    /// access both to the global and the context.
 730    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
 731    where
 732        G: Global,
 733    {
 734        let mut global = self.app.lease_global::<G>();
 735        let result = f(&mut global, self);
 736        self.app.end_global_lease(global);
 737        result
 738    }
 739
 740    fn window_bounds_changed(&mut self) {
 741        self.window.scale_factor = self.window.platform_window.scale_factor();
 742        self.window.viewport_size = self.window.platform_window.content_size();
 743        self.window.bounds = self.window.platform_window.bounds();
 744        self.window.display_id = self.window.platform_window.display().id();
 745        self.refresh();
 746
 747        self.window
 748            .bounds_observers
 749            .clone()
 750            .retain(&(), |callback| callback(self));
 751    }
 752
 753    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
 754    pub fn window_bounds(&self) -> WindowBounds {
 755        self.window.bounds
 756    }
 757
 758    fn appearance_changed(&mut self) {
 759        self.window.appearance = self.window.platform_window.appearance();
 760
 761        self.window
 762            .appearance_observers
 763            .clone()
 764            .retain(&(), |callback| callback(self));
 765    }
 766
 767    /// Returns the appearance of the current window.
 768    pub fn appearance(&self) -> WindowAppearance {
 769        self.window.appearance
 770    }
 771
 772    /// Returns the size of the drawable area within the window.
 773    pub fn viewport_size(&self) -> Size<Pixels> {
 774        self.window.viewport_size
 775    }
 776
 777    /// Returns whether this window is focused by the operating system (receiving key events).
 778    pub fn is_window_active(&self) -> bool {
 779        self.window.active.get()
 780    }
 781
 782    /// Toggle zoom on the window.
 783    pub fn zoom_window(&self) {
 784        self.window.platform_window.zoom();
 785    }
 786
 787    /// Updates the window's title at the platform level.
 788    pub fn set_window_title(&mut self, title: &str) {
 789        self.window.platform_window.set_title(title);
 790    }
 791
 792    /// Mark the window as dirty at the platform level.
 793    pub fn set_window_edited(&mut self, edited: bool) {
 794        self.window.platform_window.set_edited(edited);
 795    }
 796
 797    /// Determine the display on which the window is visible.
 798    pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 799        self.platform
 800            .displays()
 801            .into_iter()
 802            .find(|display| display.id() == self.window.display_id)
 803    }
 804
 805    /// Show the platform character palette.
 806    pub fn show_character_palette(&self) {
 807        self.window.platform_window.show_character_palette();
 808    }
 809
 810    /// The scale factor of the display associated with the window. For example, it could
 811    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
 812    /// be rendered as two pixels on screen.
 813    pub fn scale_factor(&self) -> f32 {
 814        self.window.scale_factor
 815    }
 816
 817    /// The size of an em for the base font of the application. Adjusting this value allows the
 818    /// UI to scale, just like zooming a web page.
 819    pub fn rem_size(&self) -> Pixels {
 820        self.window.rem_size
 821    }
 822
 823    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
 824    /// UI to scale, just like zooming a web page.
 825    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
 826        self.window.rem_size = rem_size.into();
 827    }
 828
 829    /// The line height associated with the current text style.
 830    pub fn line_height(&self) -> Pixels {
 831        let rem_size = self.rem_size();
 832        let text_style = self.text_style();
 833        text_style
 834            .line_height
 835            .to_pixels(text_style.font_size, rem_size)
 836    }
 837
 838    /// Call to prevent the default action of an event. Currently only used to prevent
 839    /// parent elements from becoming focused on mouse down.
 840    pub fn prevent_default(&mut self) {
 841        self.window.default_prevented = true;
 842    }
 843
 844    /// Obtain whether default has been prevented for the event currently being dispatched.
 845    pub fn default_prevented(&self) -> bool {
 846        self.window.default_prevented
 847    }
 848
 849    /// Determine whether the given action is available along the dispatch path to the currently focused element.
 850    pub fn is_action_available(&self, action: &dyn Action) -> bool {
 851        let target = self
 852            .focused()
 853            .and_then(|focused_handle| {
 854                self.window
 855                    .rendered_frame
 856                    .dispatch_tree
 857                    .focusable_node_id(focused_handle.id)
 858            })
 859            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
 860        self.window
 861            .rendered_frame
 862            .dispatch_tree
 863            .is_action_available(action, target)
 864    }
 865
 866    /// The position of the mouse relative to the window.
 867    pub fn mouse_position(&self) -> Point<Pixels> {
 868        self.window.mouse_position
 869    }
 870
 871    /// The current state of the keyboard's modifiers
 872    pub fn modifiers(&self) -> Modifiers {
 873        self.window.modifiers
 874    }
 875
 876    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
 877    /// the contents of the new [Scene], use [present].
 878    #[profiling::function]
 879    pub fn draw(&mut self) {
 880        self.window.dirty.set(false);
 881
 882        // Restore the previously-used input handler.
 883        if let Some(input_handler) = self.window.platform_window.take_input_handler() {
 884            self.window
 885                .rendered_frame
 886                .input_handlers
 887                .push(Some(input_handler));
 888        }
 889
 890        self.with_element_context(|cx| cx.draw_roots());
 891        self.window.dirty_views.clear();
 892
 893        self.window
 894            .next_frame
 895            .dispatch_tree
 896            .preserve_pending_keystrokes(
 897                &mut self.window.rendered_frame.dispatch_tree,
 898                self.window.focus,
 899            );
 900        self.window.next_frame.focus = self.window.focus;
 901        self.window.next_frame.window_active = self.window.active.get();
 902
 903        // Set the cursor only if we're the active window.
 904        if self.is_window_active() {
 905            let cursor_style = self.compute_cursor_style().unwrap_or(CursorStyle::Arrow);
 906            self.platform.set_cursor_style(cursor_style);
 907        }
 908
 909        // Register requested input handler with the platform window.
 910        if let Some(input_handler) = self.window.next_frame.input_handlers.pop() {
 911            self.window
 912                .platform_window
 913                .set_input_handler(input_handler.unwrap());
 914        }
 915
 916        self.window.layout_engine.as_mut().unwrap().clear();
 917        self.text_system().finish_frame();
 918        self.window
 919            .next_frame
 920            .finish(&mut self.window.rendered_frame);
 921        ELEMENT_ARENA.with_borrow_mut(|element_arena| {
 922            let percentage = (element_arena.len() as f32 / element_arena.capacity() as f32) * 100.;
 923            if percentage >= 80. {
 924                log::warn!("elevated element arena occupation: {}.", percentage);
 925            }
 926            element_arena.clear();
 927        });
 928
 929        self.window.draw_phase = DrawPhase::Focus;
 930        let previous_focus_path = self.window.rendered_frame.focus_path();
 931        let previous_window_active = self.window.rendered_frame.window_active;
 932        mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
 933        self.window.next_frame.clear();
 934        let current_focus_path = self.window.rendered_frame.focus_path();
 935        let current_window_active = self.window.rendered_frame.window_active;
 936
 937        if previous_focus_path != current_focus_path
 938            || previous_window_active != current_window_active
 939        {
 940            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
 941                self.window
 942                    .focus_lost_listeners
 943                    .clone()
 944                    .retain(&(), |listener| listener(self));
 945            }
 946
 947            let event = FocusEvent {
 948                previous_focus_path: if previous_window_active {
 949                    previous_focus_path
 950                } else {
 951                    Default::default()
 952                },
 953                current_focus_path: if current_window_active {
 954                    current_focus_path
 955                } else {
 956                    Default::default()
 957                },
 958            };
 959            self.window
 960                .focus_listeners
 961                .clone()
 962                .retain(&(), |listener| listener(&event, self));
 963        }
 964        self.window.refreshing = false;
 965        self.window.draw_phase = DrawPhase::None;
 966        self.window.needs_present.set(true);
 967    }
 968
 969    #[profiling::function]
 970    fn present(&self) {
 971        self.window
 972            .platform_window
 973            .draw(&self.window.rendered_frame.scene);
 974        self.window.needs_present.set(false);
 975        profiling::finish_frame!();
 976    }
 977
 978    fn compute_cursor_style(&mut self) -> Option<CursorStyle> {
 979        // TODO: maybe we should have a HashMap keyed by HitboxId.
 980        let request = self
 981            .window
 982            .next_frame
 983            .cursor_styles
 984            .iter()
 985            .rev()
 986            .find(|request| request.hitbox_id.is_hovered(self))?;
 987        Some(request.style)
 988    }
 989
 990    /// Dispatch a given keystroke as though the user had typed it.
 991    /// You can create a keystroke with Keystroke::parse("").
 992    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke) -> bool {
 993        let keystroke = keystroke.with_simulated_ime();
 994        if self.dispatch_event(PlatformInput::KeyDown(KeyDownEvent {
 995            keystroke: keystroke.clone(),
 996            is_held: false,
 997        })) {
 998            return true;
 999        }
1000
1001        if let Some(input) = keystroke.ime_key {
1002            if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
1003                input_handler.dispatch_input(&input, self);
1004                self.window.platform_window.set_input_handler(input_handler);
1005                return true;
1006            }
1007        }
1008
1009        false
1010    }
1011
1012    /// Represent this action as a key binding string, to display in the UI.
1013    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
1014        self.bindings_for_action(action)
1015            .into_iter()
1016            .next()
1017            .map(|binding| {
1018                binding
1019                    .keystrokes()
1020                    .iter()
1021                    .map(ToString::to_string)
1022                    .collect::<Vec<_>>()
1023                    .join(" ")
1024            })
1025            .unwrap_or_else(|| action.name().to_string())
1026    }
1027
1028    /// Dispatch a mouse or keyboard event on the window.
1029    #[profiling::function]
1030    pub fn dispatch_event(&mut self, event: PlatformInput) -> bool {
1031        self.window.last_input_timestamp.set(Instant::now());
1032        // Handlers may set this to false by calling `stop_propagation`.
1033        self.app.propagate_event = true;
1034        // Handlers may set this to true by calling `prevent_default`.
1035        self.window.default_prevented = false;
1036
1037        let event = match event {
1038            // Track the mouse position with our own state, since accessing the platform
1039            // API for the mouse position can only occur on the main thread.
1040            PlatformInput::MouseMove(mouse_move) => {
1041                self.window.mouse_position = mouse_move.position;
1042                self.window.modifiers = mouse_move.modifiers;
1043                PlatformInput::MouseMove(mouse_move)
1044            }
1045            PlatformInput::MouseDown(mouse_down) => {
1046                self.window.mouse_position = mouse_down.position;
1047                self.window.modifiers = mouse_down.modifiers;
1048                PlatformInput::MouseDown(mouse_down)
1049            }
1050            PlatformInput::MouseUp(mouse_up) => {
1051                self.window.mouse_position = mouse_up.position;
1052                self.window.modifiers = mouse_up.modifiers;
1053                PlatformInput::MouseUp(mouse_up)
1054            }
1055            PlatformInput::MouseExited(mouse_exited) => {
1056                self.window.modifiers = mouse_exited.modifiers;
1057                PlatformInput::MouseExited(mouse_exited)
1058            }
1059            PlatformInput::ModifiersChanged(modifiers_changed) => {
1060                self.window.modifiers = modifiers_changed.modifiers;
1061                PlatformInput::ModifiersChanged(modifiers_changed)
1062            }
1063            PlatformInput::ScrollWheel(scroll_wheel) => {
1064                self.window.mouse_position = scroll_wheel.position;
1065                self.window.modifiers = scroll_wheel.modifiers;
1066                PlatformInput::ScrollWheel(scroll_wheel)
1067            }
1068            // Translate dragging and dropping of external files from the operating system
1069            // to internal drag and drop events.
1070            PlatformInput::FileDrop(file_drop) => match file_drop {
1071                FileDropEvent::Entered { position, paths } => {
1072                    self.window.mouse_position = position;
1073                    if self.active_drag.is_none() {
1074                        self.active_drag = Some(AnyDrag {
1075                            value: Box::new(paths.clone()),
1076                            view: self.new_view(|_| paths).into(),
1077                            cursor_offset: position,
1078                        });
1079                    }
1080                    PlatformInput::MouseMove(MouseMoveEvent {
1081                        position,
1082                        pressed_button: Some(MouseButton::Left),
1083                        modifiers: Modifiers::default(),
1084                    })
1085                }
1086                FileDropEvent::Pending { position } => {
1087                    self.window.mouse_position = position;
1088                    PlatformInput::MouseMove(MouseMoveEvent {
1089                        position,
1090                        pressed_button: Some(MouseButton::Left),
1091                        modifiers: Modifiers::default(),
1092                    })
1093                }
1094                FileDropEvent::Submit { position } => {
1095                    self.activate(true);
1096                    self.window.mouse_position = position;
1097                    PlatformInput::MouseUp(MouseUpEvent {
1098                        button: MouseButton::Left,
1099                        position,
1100                        modifiers: Modifiers::default(),
1101                        click_count: 1,
1102                    })
1103                }
1104                FileDropEvent::Exited => PlatformInput::MouseUp(MouseUpEvent {
1105                    button: MouseButton::Left,
1106                    position: Point::default(),
1107                    modifiers: Modifiers::default(),
1108                    click_count: 1,
1109                }),
1110            },
1111            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
1112        };
1113
1114        if let Some(any_mouse_event) = event.mouse_event() {
1115            self.dispatch_mouse_event(any_mouse_event);
1116        } else if let Some(any_key_event) = event.keyboard_event() {
1117            self.dispatch_key_event(any_key_event);
1118        }
1119
1120        !self.app.propagate_event
1121    }
1122
1123    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1124        self.window.mouse_hit_test = self.window.rendered_frame.hit_test(self.mouse_position());
1125
1126        let mut mouse_listeners = mem::take(&mut self.window.rendered_frame.mouse_listeners);
1127        self.with_element_context(|cx| {
1128            // Capture phase, events bubble from back to front. Handlers for this phase are used for
1129            // special purposes, such as detecting events outside of a given Bounds.
1130            for listener in &mut mouse_listeners {
1131                let listener = listener.as_mut().unwrap();
1132                listener(event, DispatchPhase::Capture, cx);
1133                if !cx.app.propagate_event {
1134                    break;
1135                }
1136            }
1137
1138            // Bubble phase, where most normal handlers do their work.
1139            if cx.app.propagate_event {
1140                for listener in mouse_listeners.iter_mut().rev() {
1141                    let listener = listener.as_mut().unwrap();
1142                    listener(event, DispatchPhase::Bubble, cx);
1143                    if !cx.app.propagate_event {
1144                        break;
1145                    }
1146                }
1147            }
1148        });
1149        self.window.rendered_frame.mouse_listeners = mouse_listeners;
1150
1151        if self.app.propagate_event && self.has_active_drag() {
1152            if event.is::<MouseMoveEvent>() {
1153                // If this was a mouse move event, redraw the window so that the
1154                // active drag can follow the mouse cursor.
1155                self.refresh();
1156            } else if event.is::<MouseUpEvent>() {
1157                // If this was a mouse up event, cancel the active drag and redraw
1158                // the window.
1159                self.active_drag = None;
1160                self.refresh();
1161            }
1162        }
1163    }
1164
1165    fn dispatch_key_event(&mut self, event: &dyn Any) {
1166        if self.window.dirty.get() {
1167            self.draw();
1168        }
1169
1170        let node_id = self
1171            .window
1172            .focus
1173            .and_then(|focus_id| {
1174                self.window
1175                    .rendered_frame
1176                    .dispatch_tree
1177                    .focusable_node_id(focus_id)
1178            })
1179            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1180
1181        let dispatch_path = self
1182            .window
1183            .rendered_frame
1184            .dispatch_tree
1185            .dispatch_path(node_id);
1186
1187        if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1188            let KeymatchResult { bindings, pending } = self
1189                .window
1190                .rendered_frame
1191                .dispatch_tree
1192                .dispatch_key(&key_down_event.keystroke, &dispatch_path);
1193
1194            if pending {
1195                let mut currently_pending = self.window.pending_input.take().unwrap_or_default();
1196                if currently_pending.focus.is_some() && currently_pending.focus != self.window.focus
1197                {
1198                    currently_pending = PendingInput::default();
1199                }
1200                currently_pending.focus = self.window.focus;
1201                currently_pending
1202                    .keystrokes
1203                    .push(key_down_event.keystroke.clone());
1204                for binding in bindings {
1205                    currently_pending.bindings.push(binding);
1206                }
1207
1208                currently_pending.timer = Some(self.spawn(|mut cx| async move {
1209                    cx.background_executor.timer(Duration::from_secs(1)).await;
1210                    cx.update(move |cx| {
1211                        cx.clear_pending_keystrokes();
1212                        let Some(currently_pending) = cx.window.pending_input.take() else {
1213                            return;
1214                        };
1215                        cx.replay_pending_input(currently_pending)
1216                    })
1217                    .log_err();
1218                }));
1219
1220                self.window.pending_input = Some(currently_pending);
1221
1222                self.propagate_event = false;
1223                return;
1224            } else if let Some(currently_pending) = self.window.pending_input.take() {
1225                if bindings
1226                    .iter()
1227                    .all(|binding| !currently_pending.used_by_binding(binding))
1228                {
1229                    self.replay_pending_input(currently_pending)
1230                }
1231            }
1232
1233            if !bindings.is_empty() {
1234                self.clear_pending_keystrokes();
1235            }
1236
1237            self.propagate_event = true;
1238            for binding in bindings {
1239                self.dispatch_action_on_node(node_id, binding.action.as_ref());
1240                if !self.propagate_event {
1241                    self.dispatch_keystroke_observers(event, Some(binding.action));
1242                    return;
1243                }
1244            }
1245        }
1246
1247        self.dispatch_key_down_up_event(event, &dispatch_path);
1248        if !self.propagate_event {
1249            return;
1250        }
1251
1252        self.dispatch_keystroke_observers(event, None);
1253    }
1254
1255    fn dispatch_key_down_up_event(
1256        &mut self,
1257        event: &dyn Any,
1258        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
1259    ) {
1260        // Capture phase
1261        for node_id in dispatch_path {
1262            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1263
1264            for key_listener in node.key_listeners.clone() {
1265                self.with_element_context(|cx| {
1266                    key_listener(event, DispatchPhase::Capture, cx);
1267                });
1268                if !self.propagate_event {
1269                    return;
1270                }
1271            }
1272        }
1273
1274        // Bubble phase
1275        for node_id in dispatch_path.iter().rev() {
1276            // Handle low level key events
1277            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1278            for key_listener in node.key_listeners.clone() {
1279                self.with_element_context(|cx| {
1280                    key_listener(event, DispatchPhase::Bubble, cx);
1281                });
1282                if !self.propagate_event {
1283                    return;
1284                }
1285            }
1286        }
1287    }
1288
1289    /// Determine whether a potential multi-stroke key binding is in progress on this window.
1290    pub fn has_pending_keystrokes(&self) -> bool {
1291        self.window
1292            .rendered_frame
1293            .dispatch_tree
1294            .has_pending_keystrokes()
1295    }
1296
1297    fn replay_pending_input(&mut self, currently_pending: PendingInput) {
1298        let node_id = self
1299            .window
1300            .focus
1301            .and_then(|focus_id| {
1302                self.window
1303                    .rendered_frame
1304                    .dispatch_tree
1305                    .focusable_node_id(focus_id)
1306            })
1307            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1308
1309        if self.window.focus != currently_pending.focus {
1310            return;
1311        }
1312
1313        let input = currently_pending.input();
1314
1315        self.propagate_event = true;
1316        for binding in currently_pending.bindings {
1317            self.dispatch_action_on_node(node_id, binding.action.as_ref());
1318            if !self.propagate_event {
1319                return;
1320            }
1321        }
1322
1323        let dispatch_path = self
1324            .window
1325            .rendered_frame
1326            .dispatch_tree
1327            .dispatch_path(node_id);
1328
1329        for keystroke in currently_pending.keystrokes {
1330            let event = KeyDownEvent {
1331                keystroke,
1332                is_held: false,
1333            };
1334
1335            self.dispatch_key_down_up_event(&event, &dispatch_path);
1336            if !self.propagate_event {
1337                return;
1338            }
1339        }
1340
1341        if !input.is_empty() {
1342            if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
1343                input_handler.dispatch_input(&input, self);
1344                self.window.platform_window.set_input_handler(input_handler)
1345            }
1346        }
1347    }
1348
1349    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: &dyn Action) {
1350        let dispatch_path = self
1351            .window
1352            .rendered_frame
1353            .dispatch_tree
1354            .dispatch_path(node_id);
1355
1356        // Capture phase
1357        for node_id in &dispatch_path {
1358            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1359            for DispatchActionListener {
1360                action_type,
1361                listener,
1362            } in node.action_listeners.clone()
1363            {
1364                let any_action = action.as_any();
1365                if action_type == any_action.type_id() {
1366                    self.with_element_context(|cx| {
1367                        listener(any_action, DispatchPhase::Capture, cx);
1368                    });
1369
1370                    if !self.propagate_event {
1371                        return;
1372                    }
1373                }
1374            }
1375        }
1376        // Bubble phase
1377        for node_id in dispatch_path.iter().rev() {
1378            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1379            for DispatchActionListener {
1380                action_type,
1381                listener,
1382            } in node.action_listeners.clone()
1383            {
1384                let any_action = action.as_any();
1385                if action_type == any_action.type_id() {
1386                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1387
1388                    self.with_element_context(|cx| {
1389                        listener(any_action, DispatchPhase::Bubble, cx);
1390                    });
1391
1392                    if !self.propagate_event {
1393                        return;
1394                    }
1395                }
1396            }
1397        }
1398    }
1399
1400    /// Register the given handler to be invoked whenever the global of the given type
1401    /// is updated.
1402    pub fn observe_global<G: Global>(
1403        &mut self,
1404        f: impl Fn(&mut WindowContext<'_>) + 'static,
1405    ) -> Subscription {
1406        let window_handle = self.window.handle;
1407        let (subscription, activate) = self.global_observers.insert(
1408            TypeId::of::<G>(),
1409            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1410        );
1411        self.app.defer(move |_| activate());
1412        subscription
1413    }
1414
1415    /// Focus the current window and bring it to the foreground at the platform level.
1416    pub fn activate_window(&self) {
1417        self.window.platform_window.activate();
1418    }
1419
1420    /// Minimize the current window at the platform level.
1421    pub fn minimize_window(&self) {
1422        self.window.platform_window.minimize();
1423    }
1424
1425    /// Toggle full screen status on the current window at the platform level.
1426    pub fn toggle_full_screen(&self) {
1427        self.window.platform_window.toggle_full_screen();
1428    }
1429
1430    /// Present a platform dialog.
1431    /// The provided message will be presented, along with buttons for each answer.
1432    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
1433    pub fn prompt(
1434        &mut self,
1435        level: PromptLevel,
1436        message: &str,
1437        detail: Option<&str>,
1438        answers: &[&str],
1439    ) -> oneshot::Receiver<usize> {
1440        let prompt_builder = self.app.prompt_builder.take();
1441        let Some(prompt_builder) = prompt_builder else {
1442            unreachable!("Re-entrant window prompting is not supported by GPUI");
1443        };
1444
1445        let receiver = match &prompt_builder {
1446            PromptBuilder::Default => self
1447                .window
1448                .platform_window
1449                .prompt(level, message, detail, answers)
1450                .unwrap_or_else(|| {
1451                    self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
1452                }),
1453            PromptBuilder::Custom(_) => {
1454                self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
1455            }
1456        };
1457
1458        self.app.prompt_builder = Some(prompt_builder);
1459
1460        receiver
1461    }
1462
1463    fn build_custom_prompt(
1464        &mut self,
1465        prompt_builder: &PromptBuilder,
1466        level: PromptLevel,
1467        message: &str,
1468        detail: Option<&str>,
1469        answers: &[&str],
1470    ) -> oneshot::Receiver<usize> {
1471        let (sender, receiver) = oneshot::channel();
1472        let handle = PromptHandle::new(sender);
1473        let handle = (prompt_builder)(level, message, detail, answers, handle, self);
1474        self.window.prompt = Some(handle);
1475        receiver
1476    }
1477
1478    /// Returns all available actions for the focused element.
1479    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1480        let node_id = self
1481            .window
1482            .focus
1483            .and_then(|focus_id| {
1484                self.window
1485                    .rendered_frame
1486                    .dispatch_tree
1487                    .focusable_node_id(focus_id)
1488            })
1489            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1490
1491        let mut actions = self
1492            .window
1493            .rendered_frame
1494            .dispatch_tree
1495            .available_actions(node_id);
1496        for action_type in self.global_action_listeners.keys() {
1497            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
1498                let action = self.actions.build_action_type(action_type).ok();
1499                if let Some(action) = action {
1500                    actions.insert(ix, action);
1501                }
1502            }
1503        }
1504        actions
1505    }
1506
1507    /// Returns key bindings that invoke the given action on the currently focused element.
1508    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1509        self.window
1510            .rendered_frame
1511            .dispatch_tree
1512            .bindings_for_action(
1513                action,
1514                &self.window.rendered_frame.dispatch_tree.context_stack,
1515            )
1516    }
1517
1518    /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
1519    pub fn bindings_for_action_in(
1520        &self,
1521        action: &dyn Action,
1522        focus_handle: &FocusHandle,
1523    ) -> Vec<KeyBinding> {
1524        let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1525
1526        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1527            return vec![];
1528        };
1529        let context_stack: Vec<_> = dispatch_tree
1530            .dispatch_path(node_id)
1531            .into_iter()
1532            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1533            .collect();
1534        dispatch_tree.bindings_for_action(action, &context_stack)
1535    }
1536
1537    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
1538    pub fn listener_for<V: Render, E>(
1539        &self,
1540        view: &View<V>,
1541        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1542    ) -> impl Fn(&E, &mut WindowContext) + 'static {
1543        let view = view.downgrade();
1544        move |e: &E, cx: &mut WindowContext| {
1545            view.update(cx, |view, cx| f(view, e, cx)).ok();
1546        }
1547    }
1548
1549    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
1550    pub fn handler_for<V: Render>(
1551        &self,
1552        view: &View<V>,
1553        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1554    ) -> impl Fn(&mut WindowContext) {
1555        let view = view.downgrade();
1556        move |cx: &mut WindowContext| {
1557            view.update(cx, |view, cx| f(view, cx)).ok();
1558        }
1559    }
1560
1561    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
1562    /// If the callback returns false, the window won't be closed.
1563    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1564        let mut this = self.to_async();
1565        self.window
1566            .platform_window
1567            .on_should_close(Box::new(move || this.update(|cx| f(cx)).unwrap_or(true)))
1568    }
1569
1570    /// Register an action listener on the window for the next frame. The type of action
1571    /// is determined by the first parameter of the given listener. When the next frame is rendered
1572    /// the listener will be cleared.
1573    ///
1574    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
1575    /// a specific need to register a global listener.
1576    pub fn on_action(
1577        &mut self,
1578        action_type: TypeId,
1579        listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
1580    ) {
1581        self.window
1582            .next_frame
1583            .dispatch_tree
1584            .on_action(action_type, Rc::new(listener));
1585    }
1586}
1587
1588impl Context for WindowContext<'_> {
1589    type Result<T> = T;
1590
1591    fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
1592    where
1593        T: 'static,
1594    {
1595        let slot = self.app.entities.reserve();
1596        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1597        self.entities.insert(slot, model)
1598    }
1599
1600    fn update_model<T: 'static, R>(
1601        &mut self,
1602        model: &Model<T>,
1603        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1604    ) -> R {
1605        let mut entity = self.entities.lease(model);
1606        let result = update(
1607            &mut *entity,
1608            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1609        );
1610        self.entities.end_lease(entity);
1611        result
1612    }
1613
1614    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1615    where
1616        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1617    {
1618        if window == self.window.handle {
1619            let root_view = self.window.root_view.clone().unwrap();
1620            Ok(update(root_view, self))
1621        } else {
1622            window.update(self.app, update)
1623        }
1624    }
1625
1626    fn read_model<T, R>(
1627        &self,
1628        handle: &Model<T>,
1629        read: impl FnOnce(&T, &AppContext) -> R,
1630    ) -> Self::Result<R>
1631    where
1632        T: 'static,
1633    {
1634        let entity = self.entities.read(handle);
1635        read(entity, &*self.app)
1636    }
1637
1638    fn read_window<T, R>(
1639        &self,
1640        window: &WindowHandle<T>,
1641        read: impl FnOnce(View<T>, &AppContext) -> R,
1642    ) -> Result<R>
1643    where
1644        T: 'static,
1645    {
1646        if window.any_handle == self.window.handle {
1647            let root_view = self
1648                .window
1649                .root_view
1650                .clone()
1651                .unwrap()
1652                .downcast::<T>()
1653                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1654            Ok(read(root_view, self))
1655        } else {
1656            self.app.read_window(window, read)
1657        }
1658    }
1659}
1660
1661impl VisualContext for WindowContext<'_> {
1662    fn new_view<V>(
1663        &mut self,
1664        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1665    ) -> Self::Result<View<V>>
1666    where
1667        V: 'static + Render,
1668    {
1669        let slot = self.app.entities.reserve();
1670        let view = View {
1671            model: slot.clone(),
1672        };
1673        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1674        let entity = build_view_state(&mut cx);
1675        cx.entities.insert(slot, entity);
1676
1677        // Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
1678        fn notify_observers(cx: &mut WindowContext, tid: TypeId, view: AnyView) {
1679            cx.new_view_observers.clone().retain(&tid, |observer| {
1680                let any_view = view.clone();
1681                (observer)(any_view, cx);
1682                true
1683            });
1684        }
1685        notify_observers(self, TypeId::of::<V>(), AnyView::from(view.clone()));
1686
1687        view
1688    }
1689
1690    /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
1691    fn update_view<T: 'static, R>(
1692        &mut self,
1693        view: &View<T>,
1694        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1695    ) -> Self::Result<R> {
1696        let mut lease = self.app.entities.lease(&view.model);
1697        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
1698        let result = update(&mut *lease, &mut cx);
1699        cx.app.entities.end_lease(lease);
1700        result
1701    }
1702
1703    fn replace_root_view<V>(
1704        &mut self,
1705        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1706    ) -> Self::Result<View<V>>
1707    where
1708        V: 'static + Render,
1709    {
1710        let view = self.new_view(build_view);
1711        self.window.root_view = Some(view.clone().into());
1712        self.refresh();
1713        view
1714    }
1715
1716    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1717        self.update_view(view, |view, cx| {
1718            view.focus_handle(cx).clone().focus(cx);
1719        })
1720    }
1721
1722    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1723    where
1724        V: ManagedView,
1725    {
1726        self.update_view(view, |_, cx| cx.emit(DismissEvent))
1727    }
1728}
1729
1730impl<'a> std::ops::Deref for WindowContext<'a> {
1731    type Target = AppContext;
1732
1733    fn deref(&self) -> &Self::Target {
1734        self.app
1735    }
1736}
1737
1738impl<'a> std::ops::DerefMut for WindowContext<'a> {
1739    fn deref_mut(&mut self) -> &mut Self::Target {
1740        self.app
1741    }
1742}
1743
1744impl<'a> Borrow<AppContext> for WindowContext<'a> {
1745    fn borrow(&self) -> &AppContext {
1746        self.app
1747    }
1748}
1749
1750impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1751    fn borrow_mut(&mut self) -> &mut AppContext {
1752        self.app
1753    }
1754}
1755
1756/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
1757pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1758    #[doc(hidden)]
1759    fn app_mut(&mut self) -> &mut AppContext {
1760        self.borrow_mut()
1761    }
1762
1763    #[doc(hidden)]
1764    fn app(&self) -> &AppContext {
1765        self.borrow()
1766    }
1767
1768    #[doc(hidden)]
1769    fn window(&self) -> &Window {
1770        self.borrow()
1771    }
1772
1773    #[doc(hidden)]
1774    fn window_mut(&mut self) -> &mut Window {
1775        self.borrow_mut()
1776    }
1777}
1778
1779impl Borrow<Window> for WindowContext<'_> {
1780    fn borrow(&self) -> &Window {
1781        self.window
1782    }
1783}
1784
1785impl BorrowMut<Window> for WindowContext<'_> {
1786    fn borrow_mut(&mut self) -> &mut Window {
1787        self.window
1788    }
1789}
1790
1791impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1792
1793/// Provides access to application state that is specialized for a particular [`View`].
1794/// Allows you to interact with focus, emit events, etc.
1795/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
1796/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
1797pub struct ViewContext<'a, V> {
1798    window_cx: WindowContext<'a>,
1799    view: &'a View<V>,
1800}
1801
1802impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1803    fn borrow(&self) -> &AppContext {
1804        &*self.window_cx.app
1805    }
1806}
1807
1808impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1809    fn borrow_mut(&mut self) -> &mut AppContext {
1810        &mut *self.window_cx.app
1811    }
1812}
1813
1814impl<V> Borrow<Window> for ViewContext<'_, V> {
1815    fn borrow(&self) -> &Window {
1816        &*self.window_cx.window
1817    }
1818}
1819
1820impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1821    fn borrow_mut(&mut self) -> &mut Window {
1822        &mut *self.window_cx.window
1823    }
1824}
1825
1826impl<'a, V: 'static> ViewContext<'a, V> {
1827    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1828        Self {
1829            window_cx: WindowContext::new(app, window),
1830            view,
1831        }
1832    }
1833
1834    /// Get the entity_id of this view.
1835    pub fn entity_id(&self) -> EntityId {
1836        self.view.entity_id()
1837    }
1838
1839    /// Get the view pointer underlying this context.
1840    pub fn view(&self) -> &View<V> {
1841        self.view
1842    }
1843
1844    /// Get the model underlying this view.
1845    pub fn model(&self) -> &Model<V> {
1846        &self.view.model
1847    }
1848
1849    /// Access the underlying window context.
1850    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1851        &mut self.window_cx
1852    }
1853
1854    /// Sets a given callback to be run on the next frame.
1855    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1856    where
1857        V: 'static,
1858    {
1859        let view = self.view().clone();
1860        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1861    }
1862
1863    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1864    /// that are currently on the stack to be returned to the app.
1865    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1866        let view = self.view().downgrade();
1867        self.window_cx.defer(move |cx| {
1868            view.update(cx, f).ok();
1869        });
1870    }
1871
1872    /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
1873    pub fn observe<V2, E>(
1874        &mut self,
1875        entity: &E,
1876        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1877    ) -> Subscription
1878    where
1879        V2: 'static,
1880        V: 'static,
1881        E: Entity<V2>,
1882    {
1883        let view = self.view().downgrade();
1884        let entity_id = entity.entity_id();
1885        let entity = entity.downgrade();
1886        let window_handle = self.window.handle;
1887        self.app.new_observer(
1888            entity_id,
1889            Box::new(move |cx| {
1890                window_handle
1891                    .update(cx, |_, cx| {
1892                        if let Some(handle) = E::upgrade_from(&entity) {
1893                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1894                                .is_ok()
1895                        } else {
1896                            false
1897                        }
1898                    })
1899                    .unwrap_or(false)
1900            }),
1901        )
1902    }
1903
1904    /// Subscribe to events emitted by another model or view.
1905    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1906    /// The callback will be invoked with a reference to the current view, a handle to the emitting entity (either a [`View`] or [`Model`]), the event, and a view context for the current view.
1907    pub fn subscribe<V2, E, Evt>(
1908        &mut self,
1909        entity: &E,
1910        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
1911    ) -> Subscription
1912    where
1913        V2: EventEmitter<Evt>,
1914        E: Entity<V2>,
1915        Evt: 'static,
1916    {
1917        let view = self.view().downgrade();
1918        let entity_id = entity.entity_id();
1919        let handle = entity.downgrade();
1920        let window_handle = self.window.handle;
1921        self.app.new_subscription(
1922            entity_id,
1923            (
1924                TypeId::of::<Evt>(),
1925                Box::new(move |event, cx| {
1926                    window_handle
1927                        .update(cx, |_, cx| {
1928                            if let Some(handle) = E::upgrade_from(&handle) {
1929                                let event = event.downcast_ref().expect("invalid event type");
1930                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
1931                                    .is_ok()
1932                            } else {
1933                                false
1934                            }
1935                        })
1936                        .unwrap_or(false)
1937                }),
1938            ),
1939        )
1940    }
1941
1942    /// Register a callback to be invoked when the view is released.
1943    ///
1944    /// The callback receives a handle to the view's window. This handle may be
1945    /// invalid, if the window was closed before the view was released.
1946    pub fn on_release(
1947        &mut self,
1948        on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
1949    ) -> Subscription {
1950        let window_handle = self.window.handle;
1951        let (subscription, activate) = self.app.release_listeners.insert(
1952            self.view.model.entity_id,
1953            Box::new(move |this, cx| {
1954                let this = this.downcast_mut().expect("invalid entity type");
1955                on_release(this, window_handle, cx)
1956            }),
1957        );
1958        activate();
1959        subscription
1960    }
1961
1962    /// Register a callback to be invoked when the given Model or View is released.
1963    pub fn observe_release<V2, E>(
1964        &mut self,
1965        entity: &E,
1966        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
1967    ) -> Subscription
1968    where
1969        V: 'static,
1970        V2: 'static,
1971        E: Entity<V2>,
1972    {
1973        let view = self.view().downgrade();
1974        let entity_id = entity.entity_id();
1975        let window_handle = self.window.handle;
1976        let (subscription, activate) = self.app.release_listeners.insert(
1977            entity_id,
1978            Box::new(move |entity, cx| {
1979                let entity = entity.downcast_mut().expect("invalid entity type");
1980                let _ = window_handle.update(cx, |_, cx| {
1981                    view.update(cx, |this, cx| on_release(this, entity, cx))
1982                });
1983            }),
1984        );
1985        activate();
1986        subscription
1987    }
1988
1989    /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
1990    /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
1991    pub fn notify(&mut self) {
1992        for view_id in self
1993            .window
1994            .rendered_frame
1995            .dispatch_tree
1996            .view_path(self.view.entity_id())
1997            .into_iter()
1998            .rev()
1999        {
2000            if !self.window.dirty_views.insert(view_id) {
2001                break;
2002            }
2003        }
2004
2005        if self.window.draw_phase == DrawPhase::None {
2006            self.window_cx.window.dirty.set(true);
2007            self.window_cx.app.push_effect(Effect::Notify {
2008                emitter: self.view.model.entity_id,
2009            });
2010        }
2011    }
2012
2013    /// Register a callback to be invoked when the window is resized.
2014    pub fn observe_window_bounds(
2015        &mut self,
2016        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2017    ) -> Subscription {
2018        let view = self.view.downgrade();
2019        let (subscription, activate) = self.window.bounds_observers.insert(
2020            (),
2021            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2022        );
2023        activate();
2024        subscription
2025    }
2026
2027    /// Register a callback to be invoked when the window is activated or deactivated.
2028    pub fn observe_window_activation(
2029        &mut self,
2030        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2031    ) -> Subscription {
2032        let view = self.view.downgrade();
2033        let (subscription, activate) = self.window.activation_observers.insert(
2034            (),
2035            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2036        );
2037        activate();
2038        subscription
2039    }
2040
2041    /// Registers a callback to be invoked when the window appearance changes.
2042    pub fn observe_window_appearance(
2043        &mut self,
2044        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2045    ) -> Subscription {
2046        let view = self.view.downgrade();
2047        let (subscription, activate) = self.window.appearance_observers.insert(
2048            (),
2049            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2050        );
2051        activate();
2052        subscription
2053    }
2054
2055    /// Register a listener to be called when the given focus handle receives focus.
2056    /// Returns a subscription and persists until the subscription is dropped.
2057    pub fn on_focus(
2058        &mut self,
2059        handle: &FocusHandle,
2060        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2061    ) -> Subscription {
2062        let view = self.view.downgrade();
2063        let focus_id = handle.id;
2064        let (subscription, activate) =
2065            self.window.new_focus_listener(Box::new(move |event, cx| {
2066                view.update(cx, |view, cx| {
2067                    if event.previous_focus_path.last() != Some(&focus_id)
2068                        && event.current_focus_path.last() == Some(&focus_id)
2069                    {
2070                        listener(view, cx)
2071                    }
2072                })
2073                .is_ok()
2074            }));
2075        self.app.defer(|_| activate());
2076        subscription
2077    }
2078
2079    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2080    /// Returns a subscription and persists until the subscription is dropped.
2081    pub fn on_focus_in(
2082        &mut self,
2083        handle: &FocusHandle,
2084        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2085    ) -> Subscription {
2086        let view = self.view.downgrade();
2087        let focus_id = handle.id;
2088        let (subscription, activate) =
2089            self.window.new_focus_listener(Box::new(move |event, cx| {
2090                view.update(cx, |view, cx| {
2091                    if !event.previous_focus_path.contains(&focus_id)
2092                        && event.current_focus_path.contains(&focus_id)
2093                    {
2094                        listener(view, cx)
2095                    }
2096                })
2097                .is_ok()
2098            }));
2099        self.app.defer(move |_| activate());
2100        subscription
2101    }
2102
2103    /// Register a listener to be called when the given focus handle loses focus.
2104    /// Returns a subscription and persists until the subscription is dropped.
2105    pub fn on_blur(
2106        &mut self,
2107        handle: &FocusHandle,
2108        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2109    ) -> Subscription {
2110        let view = self.view.downgrade();
2111        let focus_id = handle.id;
2112        let (subscription, activate) =
2113            self.window.new_focus_listener(Box::new(move |event, cx| {
2114                view.update(cx, |view, cx| {
2115                    if event.previous_focus_path.last() == Some(&focus_id)
2116                        && event.current_focus_path.last() != Some(&focus_id)
2117                    {
2118                        listener(view, cx)
2119                    }
2120                })
2121                .is_ok()
2122            }));
2123        self.app.defer(move |_| activate());
2124        subscription
2125    }
2126
2127    /// Register a listener to be called when nothing in the window has focus.
2128    /// This typically happens when the node that was focused is removed from the tree,
2129    /// and this callback lets you chose a default place to restore the users focus.
2130    /// Returns a subscription and persists until the subscription is dropped.
2131    pub fn on_focus_lost(
2132        &mut self,
2133        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2134    ) -> Subscription {
2135        let view = self.view.downgrade();
2136        let (subscription, activate) = self.window.focus_lost_listeners.insert(
2137            (),
2138            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2139        );
2140        activate();
2141        subscription
2142    }
2143
2144    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2145    /// Returns a subscription and persists until the subscription is dropped.
2146    pub fn on_focus_out(
2147        &mut self,
2148        handle: &FocusHandle,
2149        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2150    ) -> Subscription {
2151        let view = self.view.downgrade();
2152        let focus_id = handle.id;
2153        let (subscription, activate) =
2154            self.window.new_focus_listener(Box::new(move |event, cx| {
2155                view.update(cx, |view, cx| {
2156                    if event.previous_focus_path.contains(&focus_id)
2157                        && !event.current_focus_path.contains(&focus_id)
2158                    {
2159                        listener(view, cx)
2160                    }
2161                })
2162                .is_ok()
2163            }));
2164        self.app.defer(move |_| activate());
2165        subscription
2166    }
2167
2168    /// Schedule a future to be run asynchronously.
2169    /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
2170    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
2171    /// The returned future will be polled on the main thread.
2172    pub fn spawn<Fut, R>(
2173        &mut self,
2174        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2175    ) -> Task<R>
2176    where
2177        R: 'static,
2178        Fut: Future<Output = R> + 'static,
2179    {
2180        let view = self.view().downgrade();
2181        self.window_cx.spawn(|cx| f(view, cx))
2182    }
2183
2184    /// Updates the global state of the given type.
2185    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2186    where
2187        G: Global,
2188    {
2189        let mut global = self.app.lease_global::<G>();
2190        let result = f(&mut global, self);
2191        self.app.end_global_lease(global);
2192        result
2193    }
2194
2195    /// Register a callback to be invoked when the given global state changes.
2196    pub fn observe_global<G: Global>(
2197        &mut self,
2198        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2199    ) -> Subscription {
2200        let window_handle = self.window.handle;
2201        let view = self.view().downgrade();
2202        let (subscription, activate) = self.global_observers.insert(
2203            TypeId::of::<G>(),
2204            Box::new(move |cx| {
2205                window_handle
2206                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2207                    .unwrap_or(false)
2208            }),
2209        );
2210        self.app.defer(move |_| activate());
2211        subscription
2212    }
2213
2214    /// Register a callback to be invoked when the given Action type is dispatched to the window.
2215    pub fn on_action(
2216        &mut self,
2217        action_type: TypeId,
2218        listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2219    ) {
2220        let handle = self.view().clone();
2221        self.window_cx
2222            .on_action(action_type, move |action, phase, cx| {
2223                handle.update(cx, |view, cx| {
2224                    listener(view, action, phase, cx);
2225                })
2226            });
2227    }
2228
2229    /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
2230    pub fn emit<Evt>(&mut self, event: Evt)
2231    where
2232        Evt: 'static,
2233        V: EventEmitter<Evt>,
2234    {
2235        let emitter = self.view.model.entity_id;
2236        self.app.push_effect(Effect::Emit {
2237            emitter,
2238            event_type: TypeId::of::<Evt>(),
2239            event: Box::new(event),
2240        });
2241    }
2242
2243    /// Move focus to the current view, assuming it implements [`FocusableView`].
2244    pub fn focus_self(&mut self)
2245    where
2246        V: FocusableView,
2247    {
2248        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2249    }
2250
2251    /// Convenience method for accessing view state in an event callback.
2252    ///
2253    /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
2254    /// but it's often useful to be able to access view state in these
2255    /// callbacks. This method provides a convenient way to do so.
2256    pub fn listener<E>(
2257        &self,
2258        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2259    ) -> impl Fn(&E, &mut WindowContext) + 'static {
2260        let view = self.view().downgrade();
2261        move |e: &E, cx: &mut WindowContext| {
2262            view.update(cx, |view, cx| f(view, e, cx)).ok();
2263        }
2264    }
2265}
2266
2267impl<V> Context for ViewContext<'_, V> {
2268    type Result<U> = U;
2269
2270    fn new_model<T: 'static>(
2271        &mut self,
2272        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2273    ) -> Model<T> {
2274        self.window_cx.new_model(build_model)
2275    }
2276
2277    fn update_model<T: 'static, R>(
2278        &mut self,
2279        model: &Model<T>,
2280        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2281    ) -> R {
2282        self.window_cx.update_model(model, update)
2283    }
2284
2285    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2286    where
2287        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2288    {
2289        self.window_cx.update_window(window, update)
2290    }
2291
2292    fn read_model<T, R>(
2293        &self,
2294        handle: &Model<T>,
2295        read: impl FnOnce(&T, &AppContext) -> R,
2296    ) -> Self::Result<R>
2297    where
2298        T: 'static,
2299    {
2300        self.window_cx.read_model(handle, read)
2301    }
2302
2303    fn read_window<T, R>(
2304        &self,
2305        window: &WindowHandle<T>,
2306        read: impl FnOnce(View<T>, &AppContext) -> R,
2307    ) -> Result<R>
2308    where
2309        T: 'static,
2310    {
2311        self.window_cx.read_window(window, read)
2312    }
2313}
2314
2315impl<V: 'static> VisualContext for ViewContext<'_, V> {
2316    fn new_view<W: Render + 'static>(
2317        &mut self,
2318        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2319    ) -> Self::Result<View<W>> {
2320        self.window_cx.new_view(build_view_state)
2321    }
2322
2323    fn update_view<V2: 'static, R>(
2324        &mut self,
2325        view: &View<V2>,
2326        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2327    ) -> Self::Result<R> {
2328        self.window_cx.update_view(view, update)
2329    }
2330
2331    fn replace_root_view<W>(
2332        &mut self,
2333        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2334    ) -> Self::Result<View<W>>
2335    where
2336        W: 'static + Render,
2337    {
2338        self.window_cx.replace_root_view(build_view)
2339    }
2340
2341    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2342        self.window_cx.focus_view(view)
2343    }
2344
2345    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2346        self.window_cx.dismiss_view(view)
2347    }
2348}
2349
2350impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2351    type Target = WindowContext<'a>;
2352
2353    fn deref(&self) -> &Self::Target {
2354        &self.window_cx
2355    }
2356}
2357
2358impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2359    fn deref_mut(&mut self) -> &mut Self::Target {
2360        &mut self.window_cx
2361    }
2362}
2363
2364// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2365slotmap::new_key_type! {
2366    /// A unique identifier for a window.
2367    pub struct WindowId;
2368}
2369
2370impl WindowId {
2371    /// Converts this window ID to a `u64`.
2372    pub fn as_u64(&self) -> u64 {
2373        self.0.as_ffi()
2374    }
2375}
2376
2377/// A handle to a window with a specific root view type.
2378/// Note that this does not keep the window alive on its own.
2379#[derive(Deref, DerefMut)]
2380pub struct WindowHandle<V> {
2381    #[deref]
2382    #[deref_mut]
2383    pub(crate) any_handle: AnyWindowHandle,
2384    state_type: PhantomData<V>,
2385}
2386
2387impl<V: 'static + Render> WindowHandle<V> {
2388    /// Creates a new handle from a window ID.
2389    /// This does not check if the root type of the window is `V`.
2390    pub fn new(id: WindowId) -> Self {
2391        WindowHandle {
2392            any_handle: AnyWindowHandle {
2393                id,
2394                state_type: TypeId::of::<V>(),
2395            },
2396            state_type: PhantomData,
2397        }
2398    }
2399
2400    /// Get the root view out of this window.
2401    ///
2402    /// This will fail if the window is closed or if the root view's type does not match `V`.
2403    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2404    where
2405        C: Context,
2406    {
2407        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2408            root_view
2409                .downcast::<V>()
2410                .map_err(|_| anyhow!("the type of the window's root view has changed"))
2411        }))
2412    }
2413
2414    /// Updates the root view of this window.
2415    ///
2416    /// This will fail if the window has been closed or if the root view's type does not match
2417    pub fn update<C, R>(
2418        &self,
2419        cx: &mut C,
2420        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2421    ) -> Result<R>
2422    where
2423        C: Context,
2424    {
2425        cx.update_window(self.any_handle, |root_view, cx| {
2426            let view = root_view
2427                .downcast::<V>()
2428                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2429            Ok(cx.update_view(&view, update))
2430        })?
2431    }
2432
2433    /// Read the root view out of this window.
2434    ///
2435    /// This will fail if the window is closed or if the root view's type does not match `V`.
2436    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2437        let x = cx
2438            .windows
2439            .get(self.id)
2440            .and_then(|window| {
2441                window
2442                    .as_ref()
2443                    .and_then(|window| window.root_view.clone())
2444                    .map(|root_view| root_view.downcast::<V>())
2445            })
2446            .ok_or_else(|| anyhow!("window not found"))?
2447            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2448
2449        Ok(x.read(cx))
2450    }
2451
2452    /// Read the root view out of this window, with a callback
2453    ///
2454    /// This will fail if the window is closed or if the root view's type does not match `V`.
2455    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2456    where
2457        C: Context,
2458    {
2459        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2460    }
2461
2462    /// Read the root view pointer off of this window.
2463    ///
2464    /// This will fail if the window is closed or if the root view's type does not match `V`.
2465    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2466    where
2467        C: Context,
2468    {
2469        cx.read_window(self, |root_view, _cx| root_view.clone())
2470    }
2471
2472    /// Check if this window is 'active'.
2473    ///
2474    /// Will return `None` if the window is closed or currently
2475    /// borrowed.
2476    pub fn is_active(&self, cx: &mut AppContext) -> Option<bool> {
2477        cx.update_window(self.any_handle, |_, cx| cx.is_window_active())
2478            .ok()
2479    }
2480}
2481
2482impl<V> Copy for WindowHandle<V> {}
2483
2484impl<V> Clone for WindowHandle<V> {
2485    fn clone(&self) -> Self {
2486        *self
2487    }
2488}
2489
2490impl<V> PartialEq for WindowHandle<V> {
2491    fn eq(&self, other: &Self) -> bool {
2492        self.any_handle == other.any_handle
2493    }
2494}
2495
2496impl<V> Eq for WindowHandle<V> {}
2497
2498impl<V> Hash for WindowHandle<V> {
2499    fn hash<H: Hasher>(&self, state: &mut H) {
2500        self.any_handle.hash(state);
2501    }
2502}
2503
2504impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
2505    fn from(val: WindowHandle<V>) -> Self {
2506        val.any_handle
2507    }
2508}
2509
2510/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
2511#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2512pub struct AnyWindowHandle {
2513    pub(crate) id: WindowId,
2514    state_type: TypeId,
2515}
2516
2517impl AnyWindowHandle {
2518    /// Get the ID of this window.
2519    pub fn window_id(&self) -> WindowId {
2520        self.id
2521    }
2522
2523    /// Attempt to convert this handle to a window handle with a specific root view type.
2524    /// If the types do not match, this will return `None`.
2525    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2526        if TypeId::of::<T>() == self.state_type {
2527            Some(WindowHandle {
2528                any_handle: *self,
2529                state_type: PhantomData,
2530            })
2531        } else {
2532            None
2533        }
2534    }
2535
2536    /// Updates the state of the root view of this window.
2537    ///
2538    /// This will fail if the window has been closed.
2539    pub fn update<C, R>(
2540        self,
2541        cx: &mut C,
2542        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2543    ) -> Result<R>
2544    where
2545        C: Context,
2546    {
2547        cx.update_window(self, update)
2548    }
2549
2550    /// Read the state of the root view of this window.
2551    ///
2552    /// This will fail if the window has been closed.
2553    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2554    where
2555        C: Context,
2556        T: 'static,
2557    {
2558        let view = self
2559            .downcast::<T>()
2560            .context("the type of the window's root view has changed")?;
2561
2562        cx.read_window(&view, read)
2563    }
2564}
2565
2566/// An identifier for an [`Element`](crate::Element).
2567///
2568/// Can be constructed with a string, a number, or both, as well
2569/// as other internal representations.
2570#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2571pub enum ElementId {
2572    /// The ID of a View element
2573    View(EntityId),
2574    /// An integer ID.
2575    Integer(usize),
2576    /// A string based ID.
2577    Name(SharedString),
2578    /// An ID that's equated with a focus handle.
2579    FocusHandle(FocusId),
2580    /// A combination of a name and an integer.
2581    NamedInteger(SharedString, usize),
2582}
2583
2584impl Display for ElementId {
2585    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2586        match self {
2587            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
2588            ElementId::Integer(ix) => write!(f, "{}", ix)?,
2589            ElementId::Name(name) => write!(f, "{}", name)?,
2590            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
2591            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
2592        }
2593
2594        Ok(())
2595    }
2596}
2597
2598impl TryInto<SharedString> for ElementId {
2599    type Error = anyhow::Error;
2600
2601    fn try_into(self) -> anyhow::Result<SharedString> {
2602        if let ElementId::Name(name) = self {
2603            Ok(name)
2604        } else {
2605            Err(anyhow!("element id is not string"))
2606        }
2607    }
2608}
2609
2610impl From<usize> for ElementId {
2611    fn from(id: usize) -> Self {
2612        ElementId::Integer(id)
2613    }
2614}
2615
2616impl From<i32> for ElementId {
2617    fn from(id: i32) -> Self {
2618        Self::Integer(id as usize)
2619    }
2620}
2621
2622impl From<SharedString> for ElementId {
2623    fn from(name: SharedString) -> Self {
2624        ElementId::Name(name)
2625    }
2626}
2627
2628impl From<&'static str> for ElementId {
2629    fn from(name: &'static str) -> Self {
2630        ElementId::Name(name.into())
2631    }
2632}
2633
2634impl<'a> From<&'a FocusHandle> for ElementId {
2635    fn from(handle: &'a FocusHandle) -> Self {
2636        ElementId::FocusHandle(handle.id)
2637    }
2638}
2639
2640impl From<(&'static str, EntityId)> for ElementId {
2641    fn from((name, id): (&'static str, EntityId)) -> Self {
2642        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
2643    }
2644}
2645
2646impl From<(&'static str, usize)> for ElementId {
2647    fn from((name, id): (&'static str, usize)) -> Self {
2648        ElementId::NamedInteger(name.into(), id)
2649    }
2650}
2651
2652impl From<(&'static str, u64)> for ElementId {
2653    fn from((name, id): (&'static str, u64)) -> Self {
2654        ElementId::NamedInteger(name.into(), id as usize)
2655    }
2656}
2657
2658/// A rectangle to be rendered in the window at the given position and size.
2659/// Passed as an argument [`ElementContext::paint_quad`].
2660#[derive(Clone)]
2661pub struct PaintQuad {
2662    bounds: Bounds<Pixels>,
2663    corner_radii: Corners<Pixels>,
2664    background: Hsla,
2665    border_widths: Edges<Pixels>,
2666    border_color: Hsla,
2667}
2668
2669impl PaintQuad {
2670    /// Sets the corner radii of the quad.
2671    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
2672        PaintQuad {
2673            corner_radii: corner_radii.into(),
2674            ..self
2675        }
2676    }
2677
2678    /// Sets the border widths of the quad.
2679    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
2680        PaintQuad {
2681            border_widths: border_widths.into(),
2682            ..self
2683        }
2684    }
2685
2686    /// Sets the border color of the quad.
2687    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
2688        PaintQuad {
2689            border_color: border_color.into(),
2690            ..self
2691        }
2692    }
2693
2694    /// Sets the background color of the quad.
2695    pub fn background(self, background: impl Into<Hsla>) -> Self {
2696        PaintQuad {
2697            background: background.into(),
2698            ..self
2699        }
2700    }
2701}
2702
2703/// Creates a quad with the given parameters.
2704pub fn quad(
2705    bounds: Bounds<Pixels>,
2706    corner_radii: impl Into<Corners<Pixels>>,
2707    background: impl Into<Hsla>,
2708    border_widths: impl Into<Edges<Pixels>>,
2709    border_color: impl Into<Hsla>,
2710) -> PaintQuad {
2711    PaintQuad {
2712        bounds,
2713        corner_radii: corner_radii.into(),
2714        background: background.into(),
2715        border_widths: border_widths.into(),
2716        border_color: border_color.into(),
2717    }
2718}
2719
2720/// Creates a filled quad with the given bounds and background color.
2721pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
2722    PaintQuad {
2723        bounds: bounds.into(),
2724        corner_radii: (0.).into(),
2725        background: background.into(),
2726        border_widths: (0.).into(),
2727        border_color: transparent_black(),
2728    }
2729}
2730
2731/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
2732pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
2733    PaintQuad {
2734        bounds: bounds.into(),
2735        corner_radii: (0.).into(),
2736        background: transparent_black(),
2737        border_widths: (1.).into(),
2738        border_color: border_color.into(),
2739    }
2740}