window.rs

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