window.rs

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