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