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