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