window.rs

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