window.rs

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