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 the opaque layer is an extension of the queried layer, we don't want
 863            // to consider the opaque layer to be on top and so we ignore it.
 864            // - Else, we will bail early and say that the queried layer wasn't the top one.
 865            let opaque_layer_is_extension_of_queried_layer = opaque_layer.len() >= layer.len()
 866                && opaque_layer
 867                    .iter()
 868                    .zip(layer.iter())
 869                    .all(|(a, b)| a.z_index == b.z_index);
 870            if !opaque_layer_is_extension_of_queried_layer {
 871                return false;
 872            }
 873        }
 874
 875        true
 876    }
 877
 878    pub(crate) fn was_top_layer_under_active_drag(
 879        &self,
 880        point: &Point<Pixels>,
 881        layer: &StackingOrder,
 882    ) -> bool {
 883        // Precondition: the depth map is ordered from topmost to bottomost.
 884
 885        for (opaque_layer, _, bounds) in self.window.rendered_frame.depth_map.iter() {
 886            if layer >= opaque_layer {
 887                // The queried layer is either above or is the same as the this opaque layer.
 888                // Anything after this point is guaranteed to be below the queried layer.
 889                return true;
 890            }
 891
 892            if !bounds.contains(point) {
 893                // This opaque layer is above the queried layer but it doesn't contain
 894                // the given position, so we can ignore it even if it's above.
 895                continue;
 896            }
 897
 898            // All normal content is rendered with a base z-index of 0, we know that if the root of this opaque layer
 899            // equals `ACTIVE_DRAG_Z_INDEX` then it must be the drag layer and we can ignore it as we are
 900            // looking to see if the queried layer was the topmost underneath the drag layer.
 901            if opaque_layer
 902                .first()
 903                .map(|c| c.z_index == ACTIVE_DRAG_Z_INDEX)
 904                .unwrap_or(false)
 905            {
 906                continue;
 907            }
 908
 909            // At this point, we've established that this opaque layer is on top of the queried layer
 910            // and contains the position:
 911            // - If the opaque layer is an extension of the queried layer, we don't want
 912            // to consider the opaque layer to be on top and so we ignore it.
 913            // - Else, we will bail early and say that the queried layer wasn't the top one.
 914            let opaque_layer_is_extension_of_queried_layer = opaque_layer.len() >= layer.len()
 915                && opaque_layer
 916                    .iter()
 917                    .zip(layer.iter())
 918                    .all(|(a, b)| a.z_index == b.z_index);
 919            if !opaque_layer_is_extension_of_queried_layer {
 920                return false;
 921            }
 922        }
 923
 924        true
 925    }
 926
 927    /// Called during painting to get the current stacking order.
 928    pub fn stacking_order(&self) -> &StackingOrder {
 929        &self.window.next_frame.z_index_stack
 930    }
 931
 932    /// Draw pixels to the display for this window based on the contents of its scene.
 933    pub(crate) fn draw(&mut self) {
 934        self.window.dirty = false;
 935        self.window.drawing = true;
 936
 937        #[cfg(any(test, feature = "test-support"))]
 938        {
 939            self.window.focus_invalidated = false;
 940        }
 941
 942        if let Some(requested_handler) = self.window.rendered_frame.requested_input_handler.as_mut()
 943        {
 944            let input_handler = self.window.platform_window.take_input_handler();
 945            requested_handler.handler = input_handler;
 946        }
 947
 948        let root_view = self.window.root_view.take().unwrap();
 949        self.with_element_context(|cx| {
 950            cx.with_z_index(0, |cx| {
 951                cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| {
 952                    // We need to use cx.cx here so we can utilize borrow splitting
 953                    for (action_type, action_listeners) in &cx.cx.app.global_action_listeners {
 954                        for action_listener in action_listeners.iter().cloned() {
 955                            cx.cx.window.next_frame.dispatch_tree.on_action(
 956                                *action_type,
 957                                Rc::new(
 958                                    move |action: &dyn Any, phase, cx: &mut WindowContext<'_>| {
 959                                        action_listener(action, phase, cx)
 960                                    },
 961                                ),
 962                            )
 963                        }
 964                    }
 965
 966                    let available_space = cx.window.viewport_size.map(Into::into);
 967                    root_view.draw(Point::default(), available_space, cx);
 968                })
 969            })
 970        });
 971
 972        if let Some(active_drag) = self.app.active_drag.take() {
 973            self.with_element_context(|cx| {
 974                cx.with_z_index(ACTIVE_DRAG_Z_INDEX, |cx| {
 975                    let offset = cx.mouse_position() - active_drag.cursor_offset;
 976                    let available_space =
 977                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
 978                    active_drag.view.draw(offset, available_space, cx);
 979                })
 980            });
 981            self.active_drag = Some(active_drag);
 982        } else if let Some(tooltip_request) = self.window.next_frame.tooltip_request.take() {
 983            self.with_element_context(|cx| {
 984                cx.with_z_index(1, |cx| {
 985                    let available_space =
 986                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
 987                    tooltip_request.tooltip.view.draw(
 988                        tooltip_request.tooltip.cursor_offset,
 989                        available_space,
 990                        cx,
 991                    );
 992                })
 993            });
 994            self.window.next_frame.tooltip_request = Some(tooltip_request);
 995        }
 996        self.window.dirty_views.clear();
 997
 998        self.window
 999            .next_frame
1000            .dispatch_tree
1001            .preserve_pending_keystrokes(
1002                &mut self.window.rendered_frame.dispatch_tree,
1003                self.window.focus,
1004            );
1005        self.window.next_frame.focus = self.window.focus;
1006        self.window.next_frame.window_active = self.window.active;
1007        self.window.root_view = Some(root_view);
1008
1009        // Set the cursor only if we're the active window.
1010        let cursor_style = self
1011            .window
1012            .next_frame
1013            .requested_cursor_style
1014            .take()
1015            .unwrap_or(CursorStyle::Arrow);
1016        if self.is_window_active() {
1017            self.platform.set_cursor_style(cursor_style);
1018        }
1019
1020        // Register requested input handler with the platform window.
1021        if let Some(requested_input) = self.window.next_frame.requested_input_handler.as_mut() {
1022            if let Some(handler) = requested_input.handler.take() {
1023                self.window.platform_window.set_input_handler(handler);
1024            }
1025        }
1026
1027        self.window.layout_engine.as_mut().unwrap().clear();
1028        self.text_system()
1029            .finish_frame(&self.window.next_frame.reused_views);
1030        self.window
1031            .next_frame
1032            .finish(&mut self.window.rendered_frame);
1033        ELEMENT_ARENA.with_borrow_mut(|element_arena| {
1034            let percentage = (element_arena.len() as f32 / element_arena.capacity() as f32) * 100.;
1035            if percentage >= 80. {
1036                log::warn!("elevated element arena occupation: {}.", percentage);
1037            }
1038            element_arena.clear();
1039        });
1040
1041        let previous_focus_path = self.window.rendered_frame.focus_path();
1042        let previous_window_active = self.window.rendered_frame.window_active;
1043        mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1044        self.window.next_frame.clear();
1045        let current_focus_path = self.window.rendered_frame.focus_path();
1046        let current_window_active = self.window.rendered_frame.window_active;
1047
1048        if previous_focus_path != current_focus_path
1049            || previous_window_active != current_window_active
1050        {
1051            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1052                self.window
1053                    .focus_lost_listeners
1054                    .clone()
1055                    .retain(&(), |listener| listener(self));
1056            }
1057
1058            let event = FocusEvent {
1059                previous_focus_path: if previous_window_active {
1060                    previous_focus_path
1061                } else {
1062                    Default::default()
1063                },
1064                current_focus_path: if current_window_active {
1065                    current_focus_path
1066                } else {
1067                    Default::default()
1068                },
1069            };
1070            self.window
1071                .focus_listeners
1072                .clone()
1073                .retain(&(), |listener| listener(&event, self));
1074        }
1075
1076        self.window
1077            .platform_window
1078            .draw(&self.window.rendered_frame.scene);
1079        self.window.refreshing = false;
1080        self.window.drawing = false;
1081    }
1082
1083    /// Dispatch a mouse or keyboard event on the window.
1084    pub fn dispatch_event(&mut self, event: PlatformInput) -> bool {
1085        // Handlers may set this to false by calling `stop_propagation`.
1086        self.app.propagate_event = true;
1087        // Handlers may set this to true by calling `prevent_default`.
1088        self.window.default_prevented = false;
1089
1090        let event = match event {
1091            // Track the mouse position with our own state, since accessing the platform
1092            // API for the mouse position can only occur on the main thread.
1093            PlatformInput::MouseMove(mouse_move) => {
1094                self.window.mouse_position = mouse_move.position;
1095                self.window.modifiers = mouse_move.modifiers;
1096                PlatformInput::MouseMove(mouse_move)
1097            }
1098            PlatformInput::MouseDown(mouse_down) => {
1099                self.window.mouse_position = mouse_down.position;
1100                self.window.modifiers = mouse_down.modifiers;
1101                PlatformInput::MouseDown(mouse_down)
1102            }
1103            PlatformInput::MouseUp(mouse_up) => {
1104                self.window.mouse_position = mouse_up.position;
1105                self.window.modifiers = mouse_up.modifiers;
1106                PlatformInput::MouseUp(mouse_up)
1107            }
1108            PlatformInput::MouseExited(mouse_exited) => {
1109                self.window.modifiers = mouse_exited.modifiers;
1110                PlatformInput::MouseExited(mouse_exited)
1111            }
1112            PlatformInput::ModifiersChanged(modifiers_changed) => {
1113                self.window.modifiers = modifiers_changed.modifiers;
1114                PlatformInput::ModifiersChanged(modifiers_changed)
1115            }
1116            PlatformInput::ScrollWheel(scroll_wheel) => {
1117                self.window.mouse_position = scroll_wheel.position;
1118                self.window.modifiers = scroll_wheel.modifiers;
1119                PlatformInput::ScrollWheel(scroll_wheel)
1120            }
1121            // Translate dragging and dropping of external files from the operating system
1122            // to internal drag and drop events.
1123            PlatformInput::FileDrop(file_drop) => match file_drop {
1124                FileDropEvent::Entered { position, paths } => {
1125                    self.window.mouse_position = position;
1126                    if self.active_drag.is_none() {
1127                        self.active_drag = Some(AnyDrag {
1128                            value: Box::new(paths.clone()),
1129                            view: self.new_view(|_| paths).into(),
1130                            cursor_offset: position,
1131                        });
1132                    }
1133                    PlatformInput::MouseMove(MouseMoveEvent {
1134                        position,
1135                        pressed_button: Some(MouseButton::Left),
1136                        modifiers: Modifiers::default(),
1137                    })
1138                }
1139                FileDropEvent::Pending { position } => {
1140                    self.window.mouse_position = position;
1141                    PlatformInput::MouseMove(MouseMoveEvent {
1142                        position,
1143                        pressed_button: Some(MouseButton::Left),
1144                        modifiers: Modifiers::default(),
1145                    })
1146                }
1147                FileDropEvent::Submit { position } => {
1148                    self.activate(true);
1149                    self.window.mouse_position = position;
1150                    PlatformInput::MouseUp(MouseUpEvent {
1151                        button: MouseButton::Left,
1152                        position,
1153                        modifiers: Modifiers::default(),
1154                        click_count: 1,
1155                    })
1156                }
1157                FileDropEvent::Exited => PlatformInput::MouseUp(MouseUpEvent {
1158                    button: MouseButton::Left,
1159                    position: Point::default(),
1160                    modifiers: Modifiers::default(),
1161                    click_count: 1,
1162                }),
1163            },
1164            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
1165        };
1166
1167        if let Some(any_mouse_event) = event.mouse_event() {
1168            self.dispatch_mouse_event(any_mouse_event);
1169        } else if let Some(any_key_event) = event.keyboard_event() {
1170            self.dispatch_key_event(any_key_event);
1171        }
1172
1173        !self.app.propagate_event
1174    }
1175
1176    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1177        if let Some(mut handlers) = self
1178            .window
1179            .rendered_frame
1180            .mouse_listeners
1181            .remove(&event.type_id())
1182        {
1183            // Because handlers may add other handlers, we sort every time.
1184            handlers.sort_by(|(a, _, _), (b, _, _)| a.cmp(b));
1185
1186            // Capture phase, events bubble from back to front. Handlers for this phase are used for
1187            // special purposes, such as detecting events outside of a given Bounds.
1188            for (_, _, handler) in &mut handlers {
1189                self.with_element_context(|cx| {
1190                    handler(event, DispatchPhase::Capture, cx);
1191                });
1192                if !self.app.propagate_event {
1193                    break;
1194                }
1195            }
1196
1197            // Bubble phase, where most normal handlers do their work.
1198            if self.app.propagate_event {
1199                for (_, _, handler) in handlers.iter_mut().rev() {
1200                    self.with_element_context(|cx| {
1201                        handler(event, DispatchPhase::Bubble, cx);
1202                    });
1203                    if !self.app.propagate_event {
1204                        break;
1205                    }
1206                }
1207            }
1208
1209            self.window
1210                .rendered_frame
1211                .mouse_listeners
1212                .insert(event.type_id(), handlers);
1213        }
1214
1215        if self.app.propagate_event && self.has_active_drag() {
1216            if event.is::<MouseMoveEvent>() {
1217                // If this was a mouse move event, redraw the window so that the
1218                // active drag can follow the mouse cursor.
1219                self.refresh();
1220            } else if event.is::<MouseUpEvent>() {
1221                // If this was a mouse up event, cancel the active drag and redraw
1222                // the window.
1223                self.active_drag = None;
1224                self.refresh();
1225            }
1226        }
1227    }
1228
1229    fn dispatch_key_event(&mut self, event: &dyn Any) {
1230        let node_id = self
1231            .window
1232            .focus
1233            .and_then(|focus_id| {
1234                self.window
1235                    .rendered_frame
1236                    .dispatch_tree
1237                    .focusable_node_id(focus_id)
1238            })
1239            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1240
1241        let dispatch_path = self
1242            .window
1243            .rendered_frame
1244            .dispatch_tree
1245            .dispatch_path(node_id);
1246
1247        if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1248            let KeymatchResult {
1249                bindings,
1250                mut pending,
1251            } = self
1252                .window
1253                .rendered_frame
1254                .dispatch_tree
1255                .dispatch_key(&key_down_event.keystroke, &dispatch_path);
1256
1257            if self.window.rendered_frame.dispatch_tree.keymatch_mode == KeymatchMode::Immediate
1258                && !bindings.is_empty()
1259            {
1260                pending = false;
1261            }
1262
1263            if pending {
1264                let mut currently_pending = self.window.pending_input.take().unwrap_or_default();
1265                if currently_pending.focus.is_some() && currently_pending.focus != self.window.focus
1266                {
1267                    currently_pending = PendingInput::default();
1268                }
1269                currently_pending.focus = self.window.focus;
1270                currently_pending
1271                    .keystrokes
1272                    .push(key_down_event.keystroke.clone());
1273                for binding in bindings {
1274                    currently_pending.bindings.push(binding);
1275                }
1276
1277                // for vim compatibility, we also should check "is input handler enabled"
1278                if !currently_pending.is_noop() {
1279                    currently_pending.timer = Some(self.spawn(|mut cx| async move {
1280                        cx.background_executor.timer(Duration::from_secs(1)).await;
1281                        cx.update(move |cx| {
1282                            cx.clear_pending_keystrokes();
1283                            let Some(currently_pending) = cx.window.pending_input.take() else {
1284                                return;
1285                            };
1286                            cx.replay_pending_input(currently_pending)
1287                        })
1288                        .log_err();
1289                    }));
1290                } else {
1291                    currently_pending.timer = None;
1292                }
1293                self.window.pending_input = Some(currently_pending);
1294
1295                self.propagate_event = false;
1296                return;
1297            } else if let Some(currently_pending) = self.window.pending_input.take() {
1298                if bindings
1299                    .iter()
1300                    .all(|binding| !currently_pending.used_by_binding(binding))
1301                {
1302                    self.replay_pending_input(currently_pending)
1303                }
1304            }
1305
1306            if !bindings.is_empty() {
1307                self.clear_pending_keystrokes();
1308            }
1309
1310            self.propagate_event = true;
1311            for binding in bindings {
1312                self.dispatch_action_on_node(node_id, binding.action.boxed_clone());
1313                if !self.propagate_event {
1314                    self.dispatch_keystroke_observers(event, Some(binding.action));
1315                    return;
1316                }
1317            }
1318        }
1319
1320        // Capture phase
1321        for node_id in &dispatch_path {
1322            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1323
1324            for key_listener in node.key_listeners.clone() {
1325                self.with_element_context(|cx| {
1326                    key_listener(event, DispatchPhase::Capture, cx);
1327                });
1328                if !self.propagate_event {
1329                    return;
1330                }
1331            }
1332        }
1333
1334        // Bubble phase
1335        for node_id in dispatch_path.iter().rev() {
1336            // Handle low level key events
1337            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1338            for key_listener in node.key_listeners.clone() {
1339                self.with_element_context(|cx| {
1340                    key_listener(event, DispatchPhase::Bubble, cx);
1341                });
1342                if !self.propagate_event {
1343                    return;
1344                }
1345            }
1346        }
1347
1348        self.dispatch_keystroke_observers(event, None);
1349    }
1350
1351    /// Determine whether a potential multi-stroke key binding is in progress on this window.
1352    pub fn has_pending_keystrokes(&self) -> bool {
1353        self.window
1354            .rendered_frame
1355            .dispatch_tree
1356            .has_pending_keystrokes()
1357    }
1358
1359    fn replay_pending_input(&mut self, currently_pending: PendingInput) {
1360        let node_id = self
1361            .window
1362            .focus
1363            .and_then(|focus_id| {
1364                self.window
1365                    .rendered_frame
1366                    .dispatch_tree
1367                    .focusable_node_id(focus_id)
1368            })
1369            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1370
1371        if self.window.focus != currently_pending.focus {
1372            return;
1373        }
1374
1375        let input = currently_pending.input();
1376
1377        self.propagate_event = true;
1378        for binding in currently_pending.bindings {
1379            self.dispatch_action_on_node(node_id, binding.action.boxed_clone());
1380            if !self.propagate_event {
1381                return;
1382            }
1383        }
1384
1385        if !input.is_empty() {
1386            if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
1387                input_handler.flush_pending_input(&input, self);
1388                self.window.platform_window.set_input_handler(input_handler)
1389            }
1390        }
1391    }
1392
1393    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1394        let dispatch_path = self
1395            .window
1396            .rendered_frame
1397            .dispatch_tree
1398            .dispatch_path(node_id);
1399
1400        // Capture phase
1401        for node_id in &dispatch_path {
1402            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1403            for DispatchActionListener {
1404                action_type,
1405                listener,
1406            } in node.action_listeners.clone()
1407            {
1408                let any_action = action.as_any();
1409                if action_type == any_action.type_id() {
1410                    self.with_element_context(|cx| {
1411                        listener(any_action, DispatchPhase::Capture, cx);
1412                    });
1413
1414                    if !self.propagate_event {
1415                        return;
1416                    }
1417                }
1418            }
1419        }
1420        // Bubble phase
1421        for node_id in dispatch_path.iter().rev() {
1422            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1423            for DispatchActionListener {
1424                action_type,
1425                listener,
1426            } in node.action_listeners.clone()
1427            {
1428                let any_action = action.as_any();
1429                if action_type == any_action.type_id() {
1430                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1431
1432                    self.with_element_context(|cx| {
1433                        listener(any_action, DispatchPhase::Bubble, cx);
1434                    });
1435
1436                    if !self.propagate_event {
1437                        return;
1438                    }
1439                }
1440            }
1441        }
1442    }
1443
1444    /// Register the given handler to be invoked whenever the global of the given type
1445    /// is updated.
1446    pub fn observe_global<G: 'static>(
1447        &mut self,
1448        f: impl Fn(&mut WindowContext<'_>) + 'static,
1449    ) -> Subscription {
1450        let window_handle = self.window.handle;
1451        let (subscription, activate) = self.global_observers.insert(
1452            TypeId::of::<G>(),
1453            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1454        );
1455        self.app.defer(move |_| activate());
1456        subscription
1457    }
1458
1459    /// Focus the current window and bring it to the foreground at the platform level.
1460    pub fn activate_window(&self) {
1461        self.window.platform_window.activate();
1462    }
1463
1464    /// Minimize the current window at the platform level.
1465    pub fn minimize_window(&self) {
1466        self.window.platform_window.minimize();
1467    }
1468
1469    /// Toggle full screen status on the current window at the platform level.
1470    pub fn toggle_full_screen(&self) {
1471        self.window.platform_window.toggle_full_screen();
1472    }
1473
1474    /// Present a platform dialog.
1475    /// The provided message will be presented, along with buttons for each answer.
1476    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
1477    pub fn prompt(
1478        &self,
1479        level: PromptLevel,
1480        message: &str,
1481        answers: &[&str],
1482    ) -> oneshot::Receiver<usize> {
1483        self.window.platform_window.prompt(level, message, answers)
1484    }
1485
1486    /// Returns all available actions for the focused element.
1487    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1488        let node_id = self
1489            .window
1490            .focus
1491            .and_then(|focus_id| {
1492                self.window
1493                    .rendered_frame
1494                    .dispatch_tree
1495                    .focusable_node_id(focus_id)
1496            })
1497            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1498
1499        self.window
1500            .rendered_frame
1501            .dispatch_tree
1502            .available_actions(node_id)
1503    }
1504
1505    /// Returns key bindings that invoke the given action on the currently focused element.
1506    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1507        self.window
1508            .rendered_frame
1509            .dispatch_tree
1510            .bindings_for_action(
1511                action,
1512                &self.window.rendered_frame.dispatch_tree.context_stack,
1513            )
1514    }
1515
1516    /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
1517    pub fn bindings_for_action_in(
1518        &self,
1519        action: &dyn Action,
1520        focus_handle: &FocusHandle,
1521    ) -> Vec<KeyBinding> {
1522        let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1523
1524        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1525            return vec![];
1526        };
1527        let context_stack = dispatch_tree
1528            .dispatch_path(node_id)
1529            .into_iter()
1530            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1531            .collect();
1532        dispatch_tree.bindings_for_action(action, &context_stack)
1533    }
1534
1535    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
1536    pub fn listener_for<V: Render, E>(
1537        &self,
1538        view: &View<V>,
1539        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1540    ) -> impl Fn(&E, &mut WindowContext) + 'static {
1541        let view = view.downgrade();
1542        move |e: &E, cx: &mut WindowContext| {
1543            view.update(cx, |view, cx| f(view, e, cx)).ok();
1544        }
1545    }
1546
1547    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
1548    pub fn handler_for<V: Render>(
1549        &self,
1550        view: &View<V>,
1551        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1552    ) -> impl Fn(&mut WindowContext) {
1553        let view = view.downgrade();
1554        move |cx: &mut WindowContext| {
1555            view.update(cx, |view, cx| f(view, cx)).ok();
1556        }
1557    }
1558
1559    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
1560    /// If the callback returns false, the window won't be closed.
1561    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1562        let mut this = self.to_async();
1563        self.window
1564            .platform_window
1565            .on_should_close(Box::new(move || {
1566                this.update(|cx| {
1567                    // Ensure that the window is removed from the app if it's been closed
1568                    // by always pre-empting the system close event.
1569                    if f(cx) {
1570                        cx.remove_window();
1571                    }
1572                    false
1573                })
1574                .unwrap_or(true)
1575            }))
1576    }
1577
1578    pub(crate) fn parent_view_id(&self) -> EntityId {
1579        *self
1580            .window
1581            .next_frame
1582            .view_stack
1583            .last()
1584            .expect("a view should always be on the stack while drawing")
1585    }
1586
1587    /// Register an action listener on the window for the next frame. The type of action
1588    /// is determined by the first parameter of the given listener. When the next frame is rendered
1589    /// the listener will be cleared.
1590    ///
1591    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
1592    /// a specific need to register a global listener.
1593    pub fn on_action(
1594        &mut self,
1595        action_type: TypeId,
1596        listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
1597    ) {
1598        self.window
1599            .next_frame
1600            .dispatch_tree
1601            .on_action(action_type, Rc::new(listener));
1602    }
1603}
1604
1605impl Context for WindowContext<'_> {
1606    type Result<T> = T;
1607
1608    fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
1609    where
1610        T: 'static,
1611    {
1612        let slot = self.app.entities.reserve();
1613        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1614        self.entities.insert(slot, model)
1615    }
1616
1617    fn update_model<T: 'static, R>(
1618        &mut self,
1619        model: &Model<T>,
1620        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1621    ) -> R {
1622        let mut entity = self.entities.lease(model);
1623        let result = update(
1624            &mut *entity,
1625            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1626        );
1627        self.entities.end_lease(entity);
1628        result
1629    }
1630
1631    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1632    where
1633        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1634    {
1635        if window == self.window.handle {
1636            let root_view = self.window.root_view.clone().unwrap();
1637            Ok(update(root_view, self))
1638        } else {
1639            window.update(self.app, update)
1640        }
1641    }
1642
1643    fn read_model<T, R>(
1644        &self,
1645        handle: &Model<T>,
1646        read: impl FnOnce(&T, &AppContext) -> R,
1647    ) -> Self::Result<R>
1648    where
1649        T: 'static,
1650    {
1651        let entity = self.entities.read(handle);
1652        read(entity, &*self.app)
1653    }
1654
1655    fn read_window<T, R>(
1656        &self,
1657        window: &WindowHandle<T>,
1658        read: impl FnOnce(View<T>, &AppContext) -> R,
1659    ) -> Result<R>
1660    where
1661        T: 'static,
1662    {
1663        if window.any_handle == self.window.handle {
1664            let root_view = self
1665                .window
1666                .root_view
1667                .clone()
1668                .unwrap()
1669                .downcast::<T>()
1670                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1671            Ok(read(root_view, self))
1672        } else {
1673            self.app.read_window(window, read)
1674        }
1675    }
1676}
1677
1678impl VisualContext for WindowContext<'_> {
1679    fn new_view<V>(
1680        &mut self,
1681        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1682    ) -> Self::Result<View<V>>
1683    where
1684        V: 'static + Render,
1685    {
1686        let slot = self.app.entities.reserve();
1687        let view = View {
1688            model: slot.clone(),
1689        };
1690        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1691        let entity = build_view_state(&mut cx);
1692        cx.entities.insert(slot, entity);
1693
1694        cx.new_view_observers
1695            .clone()
1696            .retain(&TypeId::of::<V>(), |observer| {
1697                let any_view = AnyView::from(view.clone());
1698                (observer)(any_view, self);
1699                true
1700            });
1701
1702        view
1703    }
1704
1705    /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
1706    fn update_view<T: 'static, R>(
1707        &mut self,
1708        view: &View<T>,
1709        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1710    ) -> Self::Result<R> {
1711        let mut lease = self.app.entities.lease(&view.model);
1712        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
1713        let result = update(&mut *lease, &mut cx);
1714        cx.app.entities.end_lease(lease);
1715        result
1716    }
1717
1718    fn replace_root_view<V>(
1719        &mut self,
1720        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1721    ) -> Self::Result<View<V>>
1722    where
1723        V: 'static + Render,
1724    {
1725        let view = self.new_view(build_view);
1726        self.window.root_view = Some(view.clone().into());
1727        self.refresh();
1728        view
1729    }
1730
1731    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1732        self.update_view(view, |view, cx| {
1733            view.focus_handle(cx).clone().focus(cx);
1734        })
1735    }
1736
1737    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1738    where
1739        V: ManagedView,
1740    {
1741        self.update_view(view, |_, cx| cx.emit(DismissEvent))
1742    }
1743}
1744
1745impl<'a> std::ops::Deref for WindowContext<'a> {
1746    type Target = AppContext;
1747
1748    fn deref(&self) -> &Self::Target {
1749        self.app
1750    }
1751}
1752
1753impl<'a> std::ops::DerefMut for WindowContext<'a> {
1754    fn deref_mut(&mut self) -> &mut Self::Target {
1755        self.app
1756    }
1757}
1758
1759impl<'a> Borrow<AppContext> for WindowContext<'a> {
1760    fn borrow(&self) -> &AppContext {
1761        self.app
1762    }
1763}
1764
1765impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1766    fn borrow_mut(&mut self) -> &mut AppContext {
1767        self.app
1768    }
1769}
1770
1771/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
1772pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1773    #[doc(hidden)]
1774    fn app_mut(&mut self) -> &mut AppContext {
1775        self.borrow_mut()
1776    }
1777
1778    #[doc(hidden)]
1779    fn app(&self) -> &AppContext {
1780        self.borrow()
1781    }
1782
1783    #[doc(hidden)]
1784    fn window(&self) -> &Window {
1785        self.borrow()
1786    }
1787
1788    #[doc(hidden)]
1789    fn window_mut(&mut self) -> &mut Window {
1790        self.borrow_mut()
1791    }
1792}
1793
1794impl Borrow<Window> for WindowContext<'_> {
1795    fn borrow(&self) -> &Window {
1796        self.window
1797    }
1798}
1799
1800impl BorrowMut<Window> for WindowContext<'_> {
1801    fn borrow_mut(&mut self) -> &mut Window {
1802        self.window
1803    }
1804}
1805
1806impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1807
1808/// Provides access to application state that is specialized for a particular [`View`].
1809/// Allows you to interact with focus, emit events, etc.
1810/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
1811/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
1812pub struct ViewContext<'a, V> {
1813    window_cx: WindowContext<'a>,
1814    view: &'a View<V>,
1815}
1816
1817impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1818    fn borrow(&self) -> &AppContext {
1819        &*self.window_cx.app
1820    }
1821}
1822
1823impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1824    fn borrow_mut(&mut self) -> &mut AppContext {
1825        &mut *self.window_cx.app
1826    }
1827}
1828
1829impl<V> Borrow<Window> for ViewContext<'_, V> {
1830    fn borrow(&self) -> &Window {
1831        &*self.window_cx.window
1832    }
1833}
1834
1835impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1836    fn borrow_mut(&mut self) -> &mut Window {
1837        &mut *self.window_cx.window
1838    }
1839}
1840
1841impl<'a, V: 'static> ViewContext<'a, V> {
1842    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1843        Self {
1844            window_cx: WindowContext::new(app, window),
1845            view,
1846        }
1847    }
1848
1849    /// Get the entity_id of this view.
1850    pub fn entity_id(&self) -> EntityId {
1851        self.view.entity_id()
1852    }
1853
1854    /// Get the view pointer underlying this context.
1855    pub fn view(&self) -> &View<V> {
1856        self.view
1857    }
1858
1859    /// Get the model underlying this view.
1860    pub fn model(&self) -> &Model<V> {
1861        &self.view.model
1862    }
1863
1864    /// Access the underlying window context.
1865    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1866        &mut self.window_cx
1867    }
1868
1869    /// Sets a given callback to be run on the next frame.
1870    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1871    where
1872        V: 'static,
1873    {
1874        let view = self.view().clone();
1875        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1876    }
1877
1878    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1879    /// that are currently on the stack to be returned to the app.
1880    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1881        let view = self.view().downgrade();
1882        self.window_cx.defer(move |cx| {
1883            view.update(cx, f).ok();
1884        });
1885    }
1886
1887    /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
1888    pub fn observe<V2, E>(
1889        &mut self,
1890        entity: &E,
1891        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1892    ) -> Subscription
1893    where
1894        V2: 'static,
1895        V: 'static,
1896        E: Entity<V2>,
1897    {
1898        let view = self.view().downgrade();
1899        let entity_id = entity.entity_id();
1900        let entity = entity.downgrade();
1901        let window_handle = self.window.handle;
1902        let (subscription, activate) = self.app.observers.insert(
1903            entity_id,
1904            Box::new(move |cx| {
1905                window_handle
1906                    .update(cx, |_, cx| {
1907                        if let Some(handle) = E::upgrade_from(&entity) {
1908                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1909                                .is_ok()
1910                        } else {
1911                            false
1912                        }
1913                    })
1914                    .unwrap_or(false)
1915            }),
1916        );
1917        self.app.defer(move |_| activate());
1918        subscription
1919    }
1920
1921    /// Subscribe to events emitted by another model or view.
1922    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1923    /// 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.
1924    pub fn subscribe<V2, E, Evt>(
1925        &mut self,
1926        entity: &E,
1927        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
1928    ) -> Subscription
1929    where
1930        V2: EventEmitter<Evt>,
1931        E: Entity<V2>,
1932        Evt: 'static,
1933    {
1934        let view = self.view().downgrade();
1935        let entity_id = entity.entity_id();
1936        let handle = entity.downgrade();
1937        let window_handle = self.window.handle;
1938        let (subscription, activate) = self.app.event_listeners.insert(
1939            entity_id,
1940            (
1941                TypeId::of::<Evt>(),
1942                Box::new(move |event, cx| {
1943                    window_handle
1944                        .update(cx, |_, cx| {
1945                            if let Some(handle) = E::upgrade_from(&handle) {
1946                                let event = event.downcast_ref().expect("invalid event type");
1947                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
1948                                    .is_ok()
1949                            } else {
1950                                false
1951                            }
1952                        })
1953                        .unwrap_or(false)
1954                }),
1955            ),
1956        );
1957        self.app.defer(move |_| activate());
1958        subscription
1959    }
1960
1961    /// Register a callback to be invoked when the view is released.
1962    ///
1963    /// The callback receives a handle to the view's window. This handle may be
1964    /// invalid, if the window was closed before the view was released.
1965    pub fn on_release(
1966        &mut self,
1967        on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
1968    ) -> Subscription {
1969        let window_handle = self.window.handle;
1970        let (subscription, activate) = self.app.release_listeners.insert(
1971            self.view.model.entity_id,
1972            Box::new(move |this, cx| {
1973                let this = this.downcast_mut().expect("invalid entity type");
1974                on_release(this, window_handle, cx)
1975            }),
1976        );
1977        activate();
1978        subscription
1979    }
1980
1981    /// Register a callback to be invoked when the given Model or View is released.
1982    pub fn observe_release<V2, E>(
1983        &mut self,
1984        entity: &E,
1985        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
1986    ) -> Subscription
1987    where
1988        V: 'static,
1989        V2: 'static,
1990        E: Entity<V2>,
1991    {
1992        let view = self.view().downgrade();
1993        let entity_id = entity.entity_id();
1994        let window_handle = self.window.handle;
1995        let (subscription, activate) = self.app.release_listeners.insert(
1996            entity_id,
1997            Box::new(move |entity, cx| {
1998                let entity = entity.downcast_mut().expect("invalid entity type");
1999                let _ = window_handle.update(cx, |_, cx| {
2000                    view.update(cx, |this, cx| on_release(this, entity, cx))
2001                });
2002            }),
2003        );
2004        activate();
2005        subscription
2006    }
2007
2008    /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
2009    /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
2010    pub fn notify(&mut self) {
2011        for view_id in self
2012            .window
2013            .rendered_frame
2014            .dispatch_tree
2015            .view_path(self.view.entity_id())
2016            .into_iter()
2017            .rev()
2018        {
2019            if !self.window.dirty_views.insert(view_id) {
2020                break;
2021            }
2022        }
2023
2024        if !self.window.drawing {
2025            self.window_cx.window.dirty = true;
2026            self.window_cx.app.push_effect(Effect::Notify {
2027                emitter: self.view.model.entity_id,
2028            });
2029        }
2030    }
2031
2032    /// Register a callback to be invoked when the window is resized.
2033    pub fn observe_window_bounds(
2034        &mut self,
2035        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2036    ) -> Subscription {
2037        let view = self.view.downgrade();
2038        let (subscription, activate) = self.window.bounds_observers.insert(
2039            (),
2040            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2041        );
2042        activate();
2043        subscription
2044    }
2045
2046    /// Register a callback to be invoked when the window is activated or deactivated.
2047    pub fn observe_window_activation(
2048        &mut self,
2049        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2050    ) -> Subscription {
2051        let view = self.view.downgrade();
2052        let (subscription, activate) = self.window.activation_observers.insert(
2053            (),
2054            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2055        );
2056        activate();
2057        subscription
2058    }
2059
2060    /// Register a listener to be called when the given focus handle receives focus.
2061    /// Returns a subscription and persists until the subscription is dropped.
2062    pub fn on_focus(
2063        &mut self,
2064        handle: &FocusHandle,
2065        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2066    ) -> Subscription {
2067        let view = self.view.downgrade();
2068        let focus_id = handle.id;
2069        let (subscription, activate) = self.window.focus_listeners.insert(
2070            (),
2071            Box::new(move |event, cx| {
2072                view.update(cx, |view, cx| {
2073                    if event.previous_focus_path.last() != Some(&focus_id)
2074                        && event.current_focus_path.last() == Some(&focus_id)
2075                    {
2076                        listener(view, cx)
2077                    }
2078                })
2079                .is_ok()
2080            }),
2081        );
2082        self.app.defer(move |_| activate());
2083        subscription
2084    }
2085
2086    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2087    /// Returns a subscription and persists until the subscription is dropped.
2088    pub fn on_focus_in(
2089        &mut self,
2090        handle: &FocusHandle,
2091        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2092    ) -> Subscription {
2093        let view = self.view.downgrade();
2094        let focus_id = handle.id;
2095        let (subscription, activate) = self.window.focus_listeners.insert(
2096            (),
2097            Box::new(move |event, cx| {
2098                view.update(cx, |view, cx| {
2099                    if !event.previous_focus_path.contains(&focus_id)
2100                        && event.current_focus_path.contains(&focus_id)
2101                    {
2102                        listener(view, cx)
2103                    }
2104                })
2105                .is_ok()
2106            }),
2107        );
2108        self.app.defer(move |_| activate());
2109        subscription
2110    }
2111
2112    /// Register a listener to be called when the given focus handle loses focus.
2113    /// Returns a subscription and persists until the subscription is dropped.
2114    pub fn on_blur(
2115        &mut self,
2116        handle: &FocusHandle,
2117        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2118    ) -> Subscription {
2119        let view = self.view.downgrade();
2120        let focus_id = handle.id;
2121        let (subscription, activate) = self.window.focus_listeners.insert(
2122            (),
2123            Box::new(move |event, cx| {
2124                view.update(cx, |view, cx| {
2125                    if event.previous_focus_path.last() == Some(&focus_id)
2126                        && event.current_focus_path.last() != Some(&focus_id)
2127                    {
2128                        listener(view, cx)
2129                    }
2130                })
2131                .is_ok()
2132            }),
2133        );
2134        self.app.defer(move |_| activate());
2135        subscription
2136    }
2137
2138    /// Register a listener to be called when nothing in the window has focus.
2139    /// This typically happens when the node that was focused is removed from the tree,
2140    /// and this callback lets you chose a default place to restore the users focus.
2141    /// Returns a subscription and persists until the subscription is dropped.
2142    pub fn on_focus_lost(
2143        &mut self,
2144        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2145    ) -> Subscription {
2146        let view = self.view.downgrade();
2147        let (subscription, activate) = self.window.focus_lost_listeners.insert(
2148            (),
2149            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2150        );
2151        activate();
2152        subscription
2153    }
2154
2155    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2156    /// Returns a subscription and persists until the subscription is dropped.
2157    pub fn on_focus_out(
2158        &mut self,
2159        handle: &FocusHandle,
2160        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2161    ) -> Subscription {
2162        let view = self.view.downgrade();
2163        let focus_id = handle.id;
2164        let (subscription, activate) = self.window.focus_listeners.insert(
2165            (),
2166            Box::new(move |event, cx| {
2167                view.update(cx, |view, cx| {
2168                    if event.previous_focus_path.contains(&focus_id)
2169                        && !event.current_focus_path.contains(&focus_id)
2170                    {
2171                        listener(view, cx)
2172                    }
2173                })
2174                .is_ok()
2175            }),
2176        );
2177        self.app.defer(move |_| activate());
2178        subscription
2179    }
2180
2181    /// Schedule a future to be run asynchronously.
2182    /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
2183    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
2184    /// The returned future will be polled on the main thread.
2185    pub fn spawn<Fut, R>(
2186        &mut self,
2187        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2188    ) -> Task<R>
2189    where
2190        R: 'static,
2191        Fut: Future<Output = R> + 'static,
2192    {
2193        let view = self.view().downgrade();
2194        self.window_cx.spawn(|cx| f(view, cx))
2195    }
2196
2197    /// Updates the global state of the given type.
2198    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2199    where
2200        G: 'static,
2201    {
2202        let mut global = self.app.lease_global::<G>();
2203        let result = f(&mut global, self);
2204        self.app.end_global_lease(global);
2205        result
2206    }
2207
2208    /// Register a callback to be invoked when the given global state changes.
2209    pub fn observe_global<G: 'static>(
2210        &mut self,
2211        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2212    ) -> Subscription {
2213        let window_handle = self.window.handle;
2214        let view = self.view().downgrade();
2215        let (subscription, activate) = self.global_observers.insert(
2216            TypeId::of::<G>(),
2217            Box::new(move |cx| {
2218                window_handle
2219                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2220                    .unwrap_or(false)
2221            }),
2222        );
2223        self.app.defer(move |_| activate());
2224        subscription
2225    }
2226
2227    /// Register a callback to be invoked when the given Action type is dispatched to the window.
2228    pub fn on_action(
2229        &mut self,
2230        action_type: TypeId,
2231        listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2232    ) {
2233        let handle = self.view().clone();
2234        self.window_cx
2235            .on_action(action_type, move |action, phase, cx| {
2236                handle.update(cx, |view, cx| {
2237                    listener(view, action, phase, cx);
2238                })
2239            });
2240    }
2241
2242    /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
2243    pub fn emit<Evt>(&mut self, event: Evt)
2244    where
2245        Evt: 'static,
2246        V: EventEmitter<Evt>,
2247    {
2248        let emitter = self.view.model.entity_id;
2249        self.app.push_effect(Effect::Emit {
2250            emitter,
2251            event_type: TypeId::of::<Evt>(),
2252            event: Box::new(event),
2253        });
2254    }
2255
2256    /// Move focus to the current view, assuming it implements [`FocusableView`].
2257    pub fn focus_self(&mut self)
2258    where
2259        V: FocusableView,
2260    {
2261        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2262    }
2263
2264    /// Convenience method for accessing view state in an event callback.
2265    ///
2266    /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
2267    /// but it's often useful to be able to access view state in these
2268    /// callbacks. This method provides a convenient way to do so.
2269    pub fn listener<E>(
2270        &self,
2271        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2272    ) -> impl Fn(&E, &mut WindowContext) + 'static {
2273        let view = self.view().downgrade();
2274        move |e: &E, cx: &mut WindowContext| {
2275            view.update(cx, |view, cx| f(view, e, cx)).ok();
2276        }
2277    }
2278}
2279
2280impl<V> Context for ViewContext<'_, V> {
2281    type Result<U> = U;
2282
2283    fn new_model<T: 'static>(
2284        &mut self,
2285        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2286    ) -> Model<T> {
2287        self.window_cx.new_model(build_model)
2288    }
2289
2290    fn update_model<T: 'static, R>(
2291        &mut self,
2292        model: &Model<T>,
2293        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2294    ) -> R {
2295        self.window_cx.update_model(model, update)
2296    }
2297
2298    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2299    where
2300        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2301    {
2302        self.window_cx.update_window(window, update)
2303    }
2304
2305    fn read_model<T, R>(
2306        &self,
2307        handle: &Model<T>,
2308        read: impl FnOnce(&T, &AppContext) -> R,
2309    ) -> Self::Result<R>
2310    where
2311        T: 'static,
2312    {
2313        self.window_cx.read_model(handle, read)
2314    }
2315
2316    fn read_window<T, R>(
2317        &self,
2318        window: &WindowHandle<T>,
2319        read: impl FnOnce(View<T>, &AppContext) -> R,
2320    ) -> Result<R>
2321    where
2322        T: 'static,
2323    {
2324        self.window_cx.read_window(window, read)
2325    }
2326}
2327
2328impl<V: 'static> VisualContext for ViewContext<'_, V> {
2329    fn new_view<W: Render + 'static>(
2330        &mut self,
2331        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2332    ) -> Self::Result<View<W>> {
2333        self.window_cx.new_view(build_view_state)
2334    }
2335
2336    fn update_view<V2: 'static, R>(
2337        &mut self,
2338        view: &View<V2>,
2339        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2340    ) -> Self::Result<R> {
2341        self.window_cx.update_view(view, update)
2342    }
2343
2344    fn replace_root_view<W>(
2345        &mut self,
2346        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2347    ) -> Self::Result<View<W>>
2348    where
2349        W: 'static + Render,
2350    {
2351        self.window_cx.replace_root_view(build_view)
2352    }
2353
2354    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2355        self.window_cx.focus_view(view)
2356    }
2357
2358    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2359        self.window_cx.dismiss_view(view)
2360    }
2361}
2362
2363impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2364    type Target = WindowContext<'a>;
2365
2366    fn deref(&self) -> &Self::Target {
2367        &self.window_cx
2368    }
2369}
2370
2371impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2372    fn deref_mut(&mut self) -> &mut Self::Target {
2373        &mut self.window_cx
2374    }
2375}
2376
2377// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2378slotmap::new_key_type! {
2379    /// A unique identifier for a window.
2380    pub struct WindowId;
2381}
2382
2383impl WindowId {
2384    /// Converts this window ID to a `u64`.
2385    pub fn as_u64(&self) -> u64 {
2386        self.0.as_ffi()
2387    }
2388}
2389
2390/// A handle to a window with a specific root view type.
2391/// Note that this does not keep the window alive on its own.
2392#[derive(Deref, DerefMut)]
2393pub struct WindowHandle<V> {
2394    #[deref]
2395    #[deref_mut]
2396    pub(crate) any_handle: AnyWindowHandle,
2397    state_type: PhantomData<V>,
2398}
2399
2400impl<V: 'static + Render> WindowHandle<V> {
2401    /// Creates a new handle from a window ID.
2402    /// This does not check if the root type of the window is `V`.
2403    pub fn new(id: WindowId) -> Self {
2404        WindowHandle {
2405            any_handle: AnyWindowHandle {
2406                id,
2407                state_type: TypeId::of::<V>(),
2408            },
2409            state_type: PhantomData,
2410        }
2411    }
2412
2413    /// Get the root view out of this window.
2414    ///
2415    /// This will fail if the window is closed or if the root view's type does not match `V`.
2416    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2417    where
2418        C: Context,
2419    {
2420        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2421            root_view
2422                .downcast::<V>()
2423                .map_err(|_| anyhow!("the type of the window's root view has changed"))
2424        }))
2425    }
2426
2427    /// Updates the root view of this window.
2428    ///
2429    /// This will fail if the window has been closed or if the root view's type does not match
2430    pub fn update<C, R>(
2431        &self,
2432        cx: &mut C,
2433        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2434    ) -> Result<R>
2435    where
2436        C: Context,
2437    {
2438        cx.update_window(self.any_handle, |root_view, cx| {
2439            let view = root_view
2440                .downcast::<V>()
2441                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2442            Ok(cx.update_view(&view, update))
2443        })?
2444    }
2445
2446    /// Read the root view out of this window.
2447    ///
2448    /// This will fail if the window is closed or if the root view's type does not match `V`.
2449    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2450        let x = cx
2451            .windows
2452            .get(self.id)
2453            .and_then(|window| {
2454                window
2455                    .as_ref()
2456                    .and_then(|window| window.root_view.clone())
2457                    .map(|root_view| root_view.downcast::<V>())
2458            })
2459            .ok_or_else(|| anyhow!("window not found"))?
2460            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2461
2462        Ok(x.read(cx))
2463    }
2464
2465    /// Read the root view out of this window, with a callback
2466    ///
2467    /// This will fail if the window is closed or if the root view's type does not match `V`.
2468    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2469    where
2470        C: Context,
2471    {
2472        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2473    }
2474
2475    /// Read the root view pointer off of this window.
2476    ///
2477    /// This will fail if the window is closed or if the root view's type does not match `V`.
2478    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2479    where
2480        C: Context,
2481    {
2482        cx.read_window(self, |root_view, _cx| root_view.clone())
2483    }
2484
2485    /// Check if this window is 'active'.
2486    ///
2487    /// Will return `None` if the window is closed.
2488    pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
2489        cx.windows
2490            .get(self.id)
2491            .and_then(|window| window.as_ref().map(|window| window.active))
2492    }
2493}
2494
2495impl<V> Copy for WindowHandle<V> {}
2496
2497impl<V> Clone for WindowHandle<V> {
2498    fn clone(&self) -> Self {
2499        *self
2500    }
2501}
2502
2503impl<V> PartialEq for WindowHandle<V> {
2504    fn eq(&self, other: &Self) -> bool {
2505        self.any_handle == other.any_handle
2506    }
2507}
2508
2509impl<V> Eq for WindowHandle<V> {}
2510
2511impl<V> Hash for WindowHandle<V> {
2512    fn hash<H: Hasher>(&self, state: &mut H) {
2513        self.any_handle.hash(state);
2514    }
2515}
2516
2517impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
2518    fn from(val: WindowHandle<V>) -> Self {
2519        val.any_handle
2520    }
2521}
2522
2523/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
2524#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2525pub struct AnyWindowHandle {
2526    pub(crate) id: WindowId,
2527    state_type: TypeId,
2528}
2529
2530impl AnyWindowHandle {
2531    /// Get the ID of this window.
2532    pub fn window_id(&self) -> WindowId {
2533        self.id
2534    }
2535
2536    /// Attempt to convert this handle to a window handle with a specific root view type.
2537    /// If the types do not match, this will return `None`.
2538    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2539        if TypeId::of::<T>() == self.state_type {
2540            Some(WindowHandle {
2541                any_handle: *self,
2542                state_type: PhantomData,
2543            })
2544        } else {
2545            None
2546        }
2547    }
2548
2549    /// Updates the state of the root view of this window.
2550    ///
2551    /// This will fail if the window has been closed.
2552    pub fn update<C, R>(
2553        self,
2554        cx: &mut C,
2555        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2556    ) -> Result<R>
2557    where
2558        C: Context,
2559    {
2560        cx.update_window(self, update)
2561    }
2562
2563    /// Read the state of the root view of this window.
2564    ///
2565    /// This will fail if the window has been closed.
2566    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2567    where
2568        C: Context,
2569        T: 'static,
2570    {
2571        let view = self
2572            .downcast::<T>()
2573            .context("the type of the window's root view has changed")?;
2574
2575        cx.read_window(&view, read)
2576    }
2577}
2578
2579/// An identifier for an [`Element`](crate::Element).
2580///
2581/// Can be constructed with a string, a number, or both, as well
2582/// as other internal representations.
2583#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2584pub enum ElementId {
2585    /// The ID of a View element
2586    View(EntityId),
2587    /// An integer ID.
2588    Integer(usize),
2589    /// A string based ID.
2590    Name(SharedString),
2591    /// An ID that's equated with a focus handle.
2592    FocusHandle(FocusId),
2593    /// A combination of a name and an integer.
2594    NamedInteger(SharedString, usize),
2595}
2596
2597impl Display for ElementId {
2598    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2599        match self {
2600            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
2601            ElementId::Integer(ix) => write!(f, "{}", ix)?,
2602            ElementId::Name(name) => write!(f, "{}", name)?,
2603            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
2604            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
2605        }
2606
2607        Ok(())
2608    }
2609}
2610
2611impl ElementId {
2612    pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
2613        ElementId::View(entity_id)
2614    }
2615}
2616
2617impl TryInto<SharedString> for ElementId {
2618    type Error = anyhow::Error;
2619
2620    fn try_into(self) -> anyhow::Result<SharedString> {
2621        if let ElementId::Name(name) = self {
2622            Ok(name)
2623        } else {
2624            Err(anyhow!("element id is not string"))
2625        }
2626    }
2627}
2628
2629impl From<usize> for ElementId {
2630    fn from(id: usize) -> Self {
2631        ElementId::Integer(id)
2632    }
2633}
2634
2635impl From<i32> for ElementId {
2636    fn from(id: i32) -> Self {
2637        Self::Integer(id as usize)
2638    }
2639}
2640
2641impl From<SharedString> for ElementId {
2642    fn from(name: SharedString) -> Self {
2643        ElementId::Name(name)
2644    }
2645}
2646
2647impl From<&'static str> for ElementId {
2648    fn from(name: &'static str) -> Self {
2649        ElementId::Name(name.into())
2650    }
2651}
2652
2653impl<'a> From<&'a FocusHandle> for ElementId {
2654    fn from(handle: &'a FocusHandle) -> Self {
2655        ElementId::FocusHandle(handle.id)
2656    }
2657}
2658
2659impl From<(&'static str, EntityId)> for ElementId {
2660    fn from((name, id): (&'static str, EntityId)) -> Self {
2661        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
2662    }
2663}
2664
2665impl From<(&'static str, usize)> for ElementId {
2666    fn from((name, id): (&'static str, usize)) -> Self {
2667        ElementId::NamedInteger(name.into(), id)
2668    }
2669}
2670
2671impl From<(&'static str, u64)> for ElementId {
2672    fn from((name, id): (&'static str, u64)) -> Self {
2673        ElementId::NamedInteger(name.into(), id as usize)
2674    }
2675}
2676
2677/// A rectangle to be rendered in the window at the given position and size.
2678/// Passed as an argument [`ElementContext::paint_quad`].
2679#[derive(Clone)]
2680pub struct PaintQuad {
2681    bounds: Bounds<Pixels>,
2682    corner_radii: Corners<Pixels>,
2683    background: Hsla,
2684    border_widths: Edges<Pixels>,
2685    border_color: Hsla,
2686}
2687
2688impl PaintQuad {
2689    /// Sets the corner radii of the quad.
2690    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
2691        PaintQuad {
2692            corner_radii: corner_radii.into(),
2693            ..self
2694        }
2695    }
2696
2697    /// Sets the border widths of the quad.
2698    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
2699        PaintQuad {
2700            border_widths: border_widths.into(),
2701            ..self
2702        }
2703    }
2704
2705    /// Sets the border color of the quad.
2706    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
2707        PaintQuad {
2708            border_color: border_color.into(),
2709            ..self
2710        }
2711    }
2712
2713    /// Sets the background color of the quad.
2714    pub fn background(self, background: impl Into<Hsla>) -> Self {
2715        PaintQuad {
2716            background: background.into(),
2717            ..self
2718        }
2719    }
2720}
2721
2722/// Creates a quad with the given parameters.
2723pub fn quad(
2724    bounds: Bounds<Pixels>,
2725    corner_radii: impl Into<Corners<Pixels>>,
2726    background: impl Into<Hsla>,
2727    border_widths: impl Into<Edges<Pixels>>,
2728    border_color: impl Into<Hsla>,
2729) -> PaintQuad {
2730    PaintQuad {
2731        bounds,
2732        corner_radii: corner_radii.into(),
2733        background: background.into(),
2734        border_widths: border_widths.into(),
2735        border_color: border_color.into(),
2736    }
2737}
2738
2739/// Creates a filled quad with the given bounds and background color.
2740pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
2741    PaintQuad {
2742        bounds: bounds.into(),
2743        corner_radii: (0.).into(),
2744        background: background.into(),
2745        border_widths: (0.).into(),
2746        border_color: transparent_black(),
2747    }
2748}
2749
2750/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
2751pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
2752    PaintQuad {
2753        bounds: bounds.into(),
2754        corner_radii: (0.).into(),
2755        background: transparent_black(),
2756        border_widths: (1.).into(),
2757        border_color: border_color.into(),
2758    }
2759}