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