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 => PlatformInput::MouseUp(MouseUpEvent {
1161                    button: MouseButton::Left,
1162                    position: Point::default(),
1163                    modifiers: Modifiers::default(),
1164                    click_count: 1,
1165                }),
1166            },
1167            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
1168        };
1169
1170        if let Some(any_mouse_event) = event.mouse_event() {
1171            self.dispatch_mouse_event(any_mouse_event);
1172        } else if let Some(any_key_event) = event.keyboard_event() {
1173            self.dispatch_key_event(any_key_event);
1174        }
1175
1176        !self.app.propagate_event
1177    }
1178
1179    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1180        self.window.mouse_hit_test = self.window.rendered_frame.hit_test(self.mouse_position());
1181
1182        let mut mouse_listeners = mem::take(&mut self.window.rendered_frame.mouse_listeners);
1183        self.with_element_context(|cx| {
1184            // Capture phase, events bubble from back to front. Handlers for this phase are used for
1185            // special purposes, such as detecting events outside of a given Bounds.
1186            for listener in &mut mouse_listeners {
1187                let listener = listener.as_mut().unwrap();
1188                listener(event, DispatchPhase::Capture, cx);
1189                if !cx.app.propagate_event {
1190                    break;
1191                }
1192            }
1193
1194            // Bubble phase, where most normal handlers do their work.
1195            if cx.app.propagate_event {
1196                for listener in mouse_listeners.iter_mut().rev() {
1197                    let listener = listener.as_mut().unwrap();
1198                    listener(event, DispatchPhase::Bubble, cx);
1199                    if !cx.app.propagate_event {
1200                        break;
1201                    }
1202                }
1203            }
1204        });
1205        self.window.rendered_frame.mouse_listeners = mouse_listeners;
1206
1207        if self.app.propagate_event && self.has_active_drag() {
1208            if event.is::<MouseMoveEvent>() {
1209                // If this was a mouse move event, redraw the window so that the
1210                // active drag can follow the mouse cursor.
1211                self.refresh();
1212            } else if event.is::<MouseUpEvent>() {
1213                // If this was a mouse up event, cancel the active drag and redraw
1214                // the window.
1215                self.active_drag = None;
1216                self.refresh();
1217            }
1218        }
1219    }
1220
1221    fn dispatch_key_event(&mut self, event: &dyn Any) {
1222        if self.window.dirty.get() {
1223            self.draw();
1224        }
1225
1226        let node_id = self
1227            .window
1228            .focus
1229            .and_then(|focus_id| {
1230                self.window
1231                    .rendered_frame
1232                    .dispatch_tree
1233                    .focusable_node_id(focus_id)
1234            })
1235            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1236
1237        let dispatch_path = self
1238            .window
1239            .rendered_frame
1240            .dispatch_tree
1241            .dispatch_path(node_id);
1242
1243        if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1244            let KeymatchResult { bindings, pending } = self
1245                .window
1246                .rendered_frame
1247                .dispatch_tree
1248                .dispatch_key(&key_down_event.keystroke, &dispatch_path);
1249
1250            if pending {
1251                let mut currently_pending = self.window.pending_input.take().unwrap_or_default();
1252                if currently_pending.focus.is_some() && currently_pending.focus != self.window.focus
1253                {
1254                    currently_pending = PendingInput::default();
1255                }
1256                currently_pending.focus = self.window.focus;
1257                currently_pending
1258                    .keystrokes
1259                    .push(key_down_event.keystroke.clone());
1260                for binding in bindings {
1261                    currently_pending.bindings.push(binding);
1262                }
1263
1264                currently_pending.timer = Some(self.spawn(|mut cx| async move {
1265                    cx.background_executor.timer(Duration::from_secs(1)).await;
1266                    cx.update(move |cx| {
1267                        cx.clear_pending_keystrokes();
1268                        let Some(currently_pending) = cx.window.pending_input.take() else {
1269                            return;
1270                        };
1271                        cx.replay_pending_input(currently_pending)
1272                    })
1273                    .log_err();
1274                }));
1275
1276                self.window.pending_input = Some(currently_pending);
1277
1278                self.propagate_event = false;
1279                return;
1280            } else if let Some(currently_pending) = self.window.pending_input.take() {
1281                if bindings
1282                    .iter()
1283                    .all(|binding| !currently_pending.used_by_binding(binding))
1284                {
1285                    self.replay_pending_input(currently_pending)
1286                }
1287            }
1288
1289            if !bindings.is_empty() {
1290                self.clear_pending_keystrokes();
1291            }
1292
1293            self.propagate_event = true;
1294            for binding in bindings {
1295                self.dispatch_action_on_node(node_id, binding.action.as_ref());
1296                if !self.propagate_event {
1297                    self.dispatch_keystroke_observers(event, Some(binding.action));
1298                    return;
1299                }
1300            }
1301        }
1302
1303        self.dispatch_key_down_up_event(event, &dispatch_path);
1304        if !self.propagate_event {
1305            return;
1306        }
1307
1308        self.dispatch_keystroke_observers(event, None);
1309    }
1310
1311    fn dispatch_key_down_up_event(
1312        &mut self,
1313        event: &dyn Any,
1314        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
1315    ) {
1316        // Capture phase
1317        for node_id in dispatch_path {
1318            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1319
1320            for key_listener in node.key_listeners.clone() {
1321                self.with_element_context(|cx| {
1322                    key_listener(event, DispatchPhase::Capture, cx);
1323                });
1324                if !self.propagate_event {
1325                    return;
1326                }
1327            }
1328        }
1329
1330        // Bubble phase
1331        for node_id in dispatch_path.iter().rev() {
1332            // Handle low level key events
1333            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1334            for key_listener in node.key_listeners.clone() {
1335                self.with_element_context(|cx| {
1336                    key_listener(event, DispatchPhase::Bubble, cx);
1337                });
1338                if !self.propagate_event {
1339                    return;
1340                }
1341            }
1342        }
1343    }
1344
1345    /// Determine whether a potential multi-stroke key binding is in progress on this window.
1346    pub fn has_pending_keystrokes(&self) -> bool {
1347        self.window
1348            .rendered_frame
1349            .dispatch_tree
1350            .has_pending_keystrokes()
1351    }
1352
1353    fn replay_pending_input(&mut self, currently_pending: PendingInput) {
1354        let node_id = self
1355            .window
1356            .focus
1357            .and_then(|focus_id| {
1358                self.window
1359                    .rendered_frame
1360                    .dispatch_tree
1361                    .focusable_node_id(focus_id)
1362            })
1363            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1364
1365        if self.window.focus != currently_pending.focus {
1366            return;
1367        }
1368
1369        let input = currently_pending.input();
1370
1371        self.propagate_event = true;
1372        for binding in currently_pending.bindings {
1373            self.dispatch_action_on_node(node_id, binding.action.as_ref());
1374            if !self.propagate_event {
1375                return;
1376            }
1377        }
1378
1379        let dispatch_path = self
1380            .window
1381            .rendered_frame
1382            .dispatch_tree
1383            .dispatch_path(node_id);
1384
1385        for keystroke in currently_pending.keystrokes {
1386            let event = KeyDownEvent {
1387                keystroke,
1388                is_held: false,
1389            };
1390
1391            self.dispatch_key_down_up_event(&event, &dispatch_path);
1392            if !self.propagate_event {
1393                return;
1394            }
1395        }
1396
1397        if !input.is_empty() {
1398            if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
1399                input_handler.dispatch_input(&input, self);
1400                self.window.platform_window.set_input_handler(input_handler)
1401            }
1402        }
1403    }
1404
1405    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: &dyn Action) {
1406        let dispatch_path = self
1407            .window
1408            .rendered_frame
1409            .dispatch_tree
1410            .dispatch_path(node_id);
1411
1412        // Capture phase
1413        for node_id in &dispatch_path {
1414            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1415            for DispatchActionListener {
1416                action_type,
1417                listener,
1418            } in node.action_listeners.clone()
1419            {
1420                let any_action = action.as_any();
1421                if action_type == any_action.type_id() {
1422                    self.with_element_context(|cx| {
1423                        listener(any_action, DispatchPhase::Capture, cx);
1424                    });
1425
1426                    if !self.propagate_event {
1427                        return;
1428                    }
1429                }
1430            }
1431        }
1432        // Bubble phase
1433        for node_id in dispatch_path.iter().rev() {
1434            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1435            for DispatchActionListener {
1436                action_type,
1437                listener,
1438            } in node.action_listeners.clone()
1439            {
1440                let any_action = action.as_any();
1441                if action_type == any_action.type_id() {
1442                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1443
1444                    self.with_element_context(|cx| {
1445                        listener(any_action, DispatchPhase::Bubble, cx);
1446                    });
1447
1448                    if !self.propagate_event {
1449                        return;
1450                    }
1451                }
1452            }
1453        }
1454    }
1455
1456    /// Register the given handler to be invoked whenever the global of the given type
1457    /// is updated.
1458    pub fn observe_global<G: Global>(
1459        &mut self,
1460        f: impl Fn(&mut WindowContext<'_>) + 'static,
1461    ) -> Subscription {
1462        let window_handle = self.window.handle;
1463        let (subscription, activate) = self.global_observers.insert(
1464            TypeId::of::<G>(),
1465            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1466        );
1467        self.app.defer(move |_| activate());
1468        subscription
1469    }
1470
1471    /// Focus the current window and bring it to the foreground at the platform level.
1472    pub fn activate_window(&self) {
1473        self.window.platform_window.activate();
1474    }
1475
1476    /// Minimize the current window at the platform level.
1477    pub fn minimize_window(&self) {
1478        self.window.platform_window.minimize();
1479    }
1480
1481    /// Toggle full screen status on the current window at the platform level.
1482    pub fn toggle_full_screen(&self) {
1483        self.window.platform_window.toggle_full_screen();
1484    }
1485
1486    /// Present a platform dialog.
1487    /// The provided message will be presented, along with buttons for each answer.
1488    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
1489    pub fn prompt(
1490        &mut self,
1491        level: PromptLevel,
1492        message: &str,
1493        detail: Option<&str>,
1494        answers: &[&str],
1495    ) -> oneshot::Receiver<usize> {
1496        let prompt_builder = self.app.prompt_builder.take();
1497        let Some(prompt_builder) = prompt_builder else {
1498            unreachable!("Re-entrant window prompting is not supported by GPUI");
1499        };
1500
1501        let receiver = match &prompt_builder {
1502            PromptBuilder::Default => self
1503                .window
1504                .platform_window
1505                .prompt(level, message, detail, answers)
1506                .unwrap_or_else(|| {
1507                    self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
1508                }),
1509            PromptBuilder::Custom(_) => {
1510                self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
1511            }
1512        };
1513
1514        self.app.prompt_builder = Some(prompt_builder);
1515
1516        receiver
1517    }
1518
1519    fn build_custom_prompt(
1520        &mut self,
1521        prompt_builder: &PromptBuilder,
1522        level: PromptLevel,
1523        message: &str,
1524        detail: Option<&str>,
1525        answers: &[&str],
1526    ) -> oneshot::Receiver<usize> {
1527        let (sender, receiver) = oneshot::channel();
1528        let handle = PromptHandle::new(sender);
1529        let handle = (prompt_builder)(level, message, detail, answers, handle, self);
1530        self.window.prompt = Some(handle);
1531        receiver
1532    }
1533
1534    /// Returns all available actions for the focused element.
1535    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1536        let node_id = self
1537            .window
1538            .focus
1539            .and_then(|focus_id| {
1540                self.window
1541                    .rendered_frame
1542                    .dispatch_tree
1543                    .focusable_node_id(focus_id)
1544            })
1545            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1546
1547        let mut actions = self
1548            .window
1549            .rendered_frame
1550            .dispatch_tree
1551            .available_actions(node_id);
1552        for action_type in self.global_action_listeners.keys() {
1553            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
1554                let action = self.actions.build_action_type(action_type).ok();
1555                if let Some(action) = action {
1556                    actions.insert(ix, action);
1557                }
1558            }
1559        }
1560        actions
1561    }
1562
1563    /// Returns key bindings that invoke the given action on the currently focused element.
1564    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1565        self.window
1566            .rendered_frame
1567            .dispatch_tree
1568            .bindings_for_action(
1569                action,
1570                &self.window.rendered_frame.dispatch_tree.context_stack,
1571            )
1572    }
1573
1574    /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
1575    pub fn bindings_for_action_in(
1576        &self,
1577        action: &dyn Action,
1578        focus_handle: &FocusHandle,
1579    ) -> Vec<KeyBinding> {
1580        let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1581
1582        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1583            return vec![];
1584        };
1585        let context_stack: Vec<_> = dispatch_tree
1586            .dispatch_path(node_id)
1587            .into_iter()
1588            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1589            .collect();
1590        dispatch_tree.bindings_for_action(action, &context_stack)
1591    }
1592
1593    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
1594    pub fn listener_for<V: Render, E>(
1595        &self,
1596        view: &View<V>,
1597        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1598    ) -> impl Fn(&E, &mut WindowContext) + 'static {
1599        let view = view.downgrade();
1600        move |e: &E, cx: &mut WindowContext| {
1601            view.update(cx, |view, cx| f(view, e, cx)).ok();
1602        }
1603    }
1604
1605    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
1606    pub fn handler_for<V: Render>(
1607        &self,
1608        view: &View<V>,
1609        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1610    ) -> impl Fn(&mut WindowContext) {
1611        let view = view.downgrade();
1612        move |cx: &mut WindowContext| {
1613            view.update(cx, |view, cx| f(view, cx)).ok();
1614        }
1615    }
1616
1617    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
1618    /// If the callback returns false, the window won't be closed.
1619    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1620        let mut this = self.to_async();
1621        self.window
1622            .platform_window
1623            .on_should_close(Box::new(move || this.update(|cx| f(cx)).unwrap_or(true)))
1624    }
1625
1626    /// Register an action listener on the window for the next frame. The type of action
1627    /// is determined by the first parameter of the given listener. When the next frame is rendered
1628    /// the listener will be cleared.
1629    ///
1630    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
1631    /// a specific need to register a global listener.
1632    pub fn on_action(
1633        &mut self,
1634        action_type: TypeId,
1635        listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
1636    ) {
1637        self.window
1638            .next_frame
1639            .dispatch_tree
1640            .on_action(action_type, Rc::new(listener));
1641    }
1642}
1643
1644impl Context for WindowContext<'_> {
1645    type Result<T> = T;
1646
1647    fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
1648    where
1649        T: 'static,
1650    {
1651        let slot = self.app.entities.reserve();
1652        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1653        self.entities.insert(slot, model)
1654    }
1655
1656    fn update_model<T: 'static, R>(
1657        &mut self,
1658        model: &Model<T>,
1659        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1660    ) -> R {
1661        let mut entity = self.entities.lease(model);
1662        let result = update(
1663            &mut *entity,
1664            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1665        );
1666        self.entities.end_lease(entity);
1667        result
1668    }
1669
1670    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1671    where
1672        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1673    {
1674        if window == self.window.handle {
1675            let root_view = self.window.root_view.clone().unwrap();
1676            Ok(update(root_view, self))
1677        } else {
1678            window.update(self.app, update)
1679        }
1680    }
1681
1682    fn read_model<T, R>(
1683        &self,
1684        handle: &Model<T>,
1685        read: impl FnOnce(&T, &AppContext) -> R,
1686    ) -> Self::Result<R>
1687    where
1688        T: 'static,
1689    {
1690        let entity = self.entities.read(handle);
1691        read(entity, &*self.app)
1692    }
1693
1694    fn read_window<T, R>(
1695        &self,
1696        window: &WindowHandle<T>,
1697        read: impl FnOnce(View<T>, &AppContext) -> R,
1698    ) -> Result<R>
1699    where
1700        T: 'static,
1701    {
1702        if window.any_handle == self.window.handle {
1703            let root_view = self
1704                .window
1705                .root_view
1706                .clone()
1707                .unwrap()
1708                .downcast::<T>()
1709                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1710            Ok(read(root_view, self))
1711        } else {
1712            self.app.read_window(window, read)
1713        }
1714    }
1715}
1716
1717impl VisualContext for WindowContext<'_> {
1718    fn new_view<V>(
1719        &mut self,
1720        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1721    ) -> Self::Result<View<V>>
1722    where
1723        V: 'static + Render,
1724    {
1725        let slot = self.app.entities.reserve();
1726        let view = View {
1727            model: slot.clone(),
1728        };
1729        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1730        let entity = build_view_state(&mut cx);
1731        cx.entities.insert(slot, entity);
1732
1733        // Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
1734        fn notify_observers(cx: &mut WindowContext, tid: TypeId, view: AnyView) {
1735            cx.new_view_observers.clone().retain(&tid, |observer| {
1736                let any_view = view.clone();
1737                (observer)(any_view, cx);
1738                true
1739            });
1740        }
1741        notify_observers(self, TypeId::of::<V>(), AnyView::from(view.clone()));
1742
1743        view
1744    }
1745
1746    /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
1747    fn update_view<T: 'static, R>(
1748        &mut self,
1749        view: &View<T>,
1750        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1751    ) -> Self::Result<R> {
1752        let mut lease = self.app.entities.lease(&view.model);
1753        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
1754        let result = update(&mut *lease, &mut cx);
1755        cx.app.entities.end_lease(lease);
1756        result
1757    }
1758
1759    fn replace_root_view<V>(
1760        &mut self,
1761        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1762    ) -> Self::Result<View<V>>
1763    where
1764        V: 'static + Render,
1765    {
1766        let view = self.new_view(build_view);
1767        self.window.root_view = Some(view.clone().into());
1768        self.refresh();
1769        view
1770    }
1771
1772    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1773        self.update_view(view, |view, cx| {
1774            view.focus_handle(cx).clone().focus(cx);
1775        })
1776    }
1777
1778    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1779    where
1780        V: ManagedView,
1781    {
1782        self.update_view(view, |_, cx| cx.emit(DismissEvent))
1783    }
1784}
1785
1786impl<'a> std::ops::Deref for WindowContext<'a> {
1787    type Target = AppContext;
1788
1789    fn deref(&self) -> &Self::Target {
1790        self.app
1791    }
1792}
1793
1794impl<'a> std::ops::DerefMut for WindowContext<'a> {
1795    fn deref_mut(&mut self) -> &mut Self::Target {
1796        self.app
1797    }
1798}
1799
1800impl<'a> Borrow<AppContext> for WindowContext<'a> {
1801    fn borrow(&self) -> &AppContext {
1802        self.app
1803    }
1804}
1805
1806impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1807    fn borrow_mut(&mut self) -> &mut AppContext {
1808        self.app
1809    }
1810}
1811
1812/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
1813pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1814    #[doc(hidden)]
1815    fn app_mut(&mut self) -> &mut AppContext {
1816        self.borrow_mut()
1817    }
1818
1819    #[doc(hidden)]
1820    fn app(&self) -> &AppContext {
1821        self.borrow()
1822    }
1823
1824    #[doc(hidden)]
1825    fn window(&self) -> &Window {
1826        self.borrow()
1827    }
1828
1829    #[doc(hidden)]
1830    fn window_mut(&mut self) -> &mut Window {
1831        self.borrow_mut()
1832    }
1833}
1834
1835impl Borrow<Window> for WindowContext<'_> {
1836    fn borrow(&self) -> &Window {
1837        self.window
1838    }
1839}
1840
1841impl BorrowMut<Window> for WindowContext<'_> {
1842    fn borrow_mut(&mut self) -> &mut Window {
1843        self.window
1844    }
1845}
1846
1847impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1848
1849/// Provides access to application state that is specialized for a particular [`View`].
1850/// Allows you to interact with focus, emit events, etc.
1851/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
1852/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
1853pub struct ViewContext<'a, V> {
1854    window_cx: WindowContext<'a>,
1855    view: &'a View<V>,
1856}
1857
1858impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1859    fn borrow(&self) -> &AppContext {
1860        &*self.window_cx.app
1861    }
1862}
1863
1864impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1865    fn borrow_mut(&mut self) -> &mut AppContext {
1866        &mut *self.window_cx.app
1867    }
1868}
1869
1870impl<V> Borrow<Window> for ViewContext<'_, V> {
1871    fn borrow(&self) -> &Window {
1872        &*self.window_cx.window
1873    }
1874}
1875
1876impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1877    fn borrow_mut(&mut self) -> &mut Window {
1878        &mut *self.window_cx.window
1879    }
1880}
1881
1882impl<'a, V: 'static> ViewContext<'a, V> {
1883    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1884        Self {
1885            window_cx: WindowContext::new(app, window),
1886            view,
1887        }
1888    }
1889
1890    /// Get the entity_id of this view.
1891    pub fn entity_id(&self) -> EntityId {
1892        self.view.entity_id()
1893    }
1894
1895    /// Get the view pointer underlying this context.
1896    pub fn view(&self) -> &View<V> {
1897        self.view
1898    }
1899
1900    /// Get the model underlying this view.
1901    pub fn model(&self) -> &Model<V> {
1902        &self.view.model
1903    }
1904
1905    /// Access the underlying window context.
1906    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1907        &mut self.window_cx
1908    }
1909
1910    /// Sets a given callback to be run on the next frame.
1911    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1912    where
1913        V: 'static,
1914    {
1915        let view = self.view().clone();
1916        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1917    }
1918
1919    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1920    /// that are currently on the stack to be returned to the app.
1921    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1922        let view = self.view().downgrade();
1923        self.window_cx.defer(move |cx| {
1924            view.update(cx, f).ok();
1925        });
1926    }
1927
1928    /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
1929    pub fn observe<V2, E>(
1930        &mut self,
1931        entity: &E,
1932        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1933    ) -> Subscription
1934    where
1935        V2: 'static,
1936        V: 'static,
1937        E: Entity<V2>,
1938    {
1939        let view = self.view().downgrade();
1940        let entity_id = entity.entity_id();
1941        let entity = entity.downgrade();
1942        let window_handle = self.window.handle;
1943        self.app.new_observer(
1944            entity_id,
1945            Box::new(move |cx| {
1946                window_handle
1947                    .update(cx, |_, cx| {
1948                        if let Some(handle) = E::upgrade_from(&entity) {
1949                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1950                                .is_ok()
1951                        } else {
1952                            false
1953                        }
1954                    })
1955                    .unwrap_or(false)
1956            }),
1957        )
1958    }
1959
1960    /// Subscribe to events emitted by another model or view.
1961    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1962    /// 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.
1963    pub fn subscribe<V2, E, Evt>(
1964        &mut self,
1965        entity: &E,
1966        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
1967    ) -> Subscription
1968    where
1969        V2: EventEmitter<Evt>,
1970        E: Entity<V2>,
1971        Evt: 'static,
1972    {
1973        let view = self.view().downgrade();
1974        let entity_id = entity.entity_id();
1975        let handle = entity.downgrade();
1976        let window_handle = self.window.handle;
1977        self.app.new_subscription(
1978            entity_id,
1979            (
1980                TypeId::of::<Evt>(),
1981                Box::new(move |event, cx| {
1982                    window_handle
1983                        .update(cx, |_, cx| {
1984                            if let Some(handle) = E::upgrade_from(&handle) {
1985                                let event = event.downcast_ref().expect("invalid event type");
1986                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
1987                                    .is_ok()
1988                            } else {
1989                                false
1990                            }
1991                        })
1992                        .unwrap_or(false)
1993                }),
1994            ),
1995        )
1996    }
1997
1998    /// Register a callback to be invoked when the view is released.
1999    ///
2000    /// The callback receives a handle to the view's window. This handle may be
2001    /// invalid, if the window was closed before the view was released.
2002    pub fn on_release(
2003        &mut self,
2004        on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
2005    ) -> Subscription {
2006        let window_handle = self.window.handle;
2007        let (subscription, activate) = self.app.release_listeners.insert(
2008            self.view.model.entity_id,
2009            Box::new(move |this, cx| {
2010                let this = this.downcast_mut().expect("invalid entity type");
2011                on_release(this, window_handle, cx)
2012            }),
2013        );
2014        activate();
2015        subscription
2016    }
2017
2018    /// Register a callback to be invoked when the given Model or View is released.
2019    pub fn observe_release<V2, E>(
2020        &mut self,
2021        entity: &E,
2022        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2023    ) -> Subscription
2024    where
2025        V: 'static,
2026        V2: 'static,
2027        E: Entity<V2>,
2028    {
2029        let view = self.view().downgrade();
2030        let entity_id = entity.entity_id();
2031        let window_handle = self.window.handle;
2032        let (subscription, activate) = self.app.release_listeners.insert(
2033            entity_id,
2034            Box::new(move |entity, cx| {
2035                let entity = entity.downcast_mut().expect("invalid entity type");
2036                let _ = window_handle.update(cx, |_, cx| {
2037                    view.update(cx, |this, cx| on_release(this, entity, cx))
2038                });
2039            }),
2040        );
2041        activate();
2042        subscription
2043    }
2044
2045    /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
2046    /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
2047    pub fn notify(&mut self) {
2048        for view_id in self
2049            .window
2050            .rendered_frame
2051            .dispatch_tree
2052            .view_path(self.view.entity_id())
2053            .into_iter()
2054            .rev()
2055        {
2056            if !self.window.dirty_views.insert(view_id) {
2057                break;
2058            }
2059        }
2060
2061        if self.window.draw_phase == DrawPhase::None {
2062            self.window_cx.window.dirty.set(true);
2063            self.window_cx.app.push_effect(Effect::Notify {
2064                emitter: self.view.model.entity_id,
2065            });
2066        }
2067    }
2068
2069    /// Register a callback to be invoked when the window is resized.
2070    pub fn observe_window_bounds(
2071        &mut self,
2072        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2073    ) -> Subscription {
2074        let view = self.view.downgrade();
2075        let (subscription, activate) = self.window.bounds_observers.insert(
2076            (),
2077            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2078        );
2079        activate();
2080        subscription
2081    }
2082
2083    /// Register a callback to be invoked when the window is activated or deactivated.
2084    pub fn observe_window_activation(
2085        &mut self,
2086        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2087    ) -> Subscription {
2088        let view = self.view.downgrade();
2089        let (subscription, activate) = self.window.activation_observers.insert(
2090            (),
2091            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2092        );
2093        activate();
2094        subscription
2095    }
2096
2097    /// Registers a callback to be invoked when the window appearance changes.
2098    pub fn observe_window_appearance(
2099        &mut self,
2100        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2101    ) -> Subscription {
2102        let view = self.view.downgrade();
2103        let (subscription, activate) = self.window.appearance_observers.insert(
2104            (),
2105            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2106        );
2107        activate();
2108        subscription
2109    }
2110
2111    /// Register a listener to be called when the given focus handle receives focus.
2112    /// Returns a subscription and persists until the subscription is dropped.
2113    pub fn on_focus(
2114        &mut self,
2115        handle: &FocusHandle,
2116        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2117    ) -> Subscription {
2118        let view = self.view.downgrade();
2119        let focus_id = handle.id;
2120        let (subscription, activate) =
2121            self.window.new_focus_listener(Box::new(move |event, cx| {
2122                view.update(cx, |view, cx| {
2123                    if event.previous_focus_path.last() != Some(&focus_id)
2124                        && event.current_focus_path.last() == Some(&focus_id)
2125                    {
2126                        listener(view, cx)
2127                    }
2128                })
2129                .is_ok()
2130            }));
2131        self.app.defer(|_| activate());
2132        subscription
2133    }
2134
2135    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2136    /// Returns a subscription and persists until the subscription is dropped.
2137    pub fn on_focus_in(
2138        &mut self,
2139        handle: &FocusHandle,
2140        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2141    ) -> Subscription {
2142        let view = self.view.downgrade();
2143        let focus_id = handle.id;
2144        let (subscription, activate) =
2145            self.window.new_focus_listener(Box::new(move |event, cx| {
2146                view.update(cx, |view, cx| {
2147                    if !event.previous_focus_path.contains(&focus_id)
2148                        && event.current_focus_path.contains(&focus_id)
2149                    {
2150                        listener(view, cx)
2151                    }
2152                })
2153                .is_ok()
2154            }));
2155        self.app.defer(move |_| activate());
2156        subscription
2157    }
2158
2159    /// Register a listener to be called when the given focus handle loses focus.
2160    /// Returns a subscription and persists until the subscription is dropped.
2161    pub fn on_blur(
2162        &mut self,
2163        handle: &FocusHandle,
2164        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2165    ) -> Subscription {
2166        let view = self.view.downgrade();
2167        let focus_id = handle.id;
2168        let (subscription, activate) =
2169            self.window.new_focus_listener(Box::new(move |event, cx| {
2170                view.update(cx, |view, cx| {
2171                    if event.previous_focus_path.last() == Some(&focus_id)
2172                        && event.current_focus_path.last() != Some(&focus_id)
2173                    {
2174                        listener(view, cx)
2175                    }
2176                })
2177                .is_ok()
2178            }));
2179        self.app.defer(move |_| activate());
2180        subscription
2181    }
2182
2183    /// Register a listener to be called when nothing in the window has focus.
2184    /// This typically happens when the node that was focused is removed from the tree,
2185    /// and this callback lets you chose a default place to restore the users focus.
2186    /// Returns a subscription and persists until the subscription is dropped.
2187    pub fn on_focus_lost(
2188        &mut self,
2189        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2190    ) -> Subscription {
2191        let view = self.view.downgrade();
2192        let (subscription, activate) = self.window.focus_lost_listeners.insert(
2193            (),
2194            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2195        );
2196        activate();
2197        subscription
2198    }
2199
2200    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2201    /// Returns a subscription and persists until the subscription is dropped.
2202    pub fn on_focus_out(
2203        &mut self,
2204        handle: &FocusHandle,
2205        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2206    ) -> Subscription {
2207        let view = self.view.downgrade();
2208        let focus_id = handle.id;
2209        let (subscription, activate) =
2210            self.window.new_focus_listener(Box::new(move |event, cx| {
2211                view.update(cx, |view, cx| {
2212                    if event.previous_focus_path.contains(&focus_id)
2213                        && !event.current_focus_path.contains(&focus_id)
2214                    {
2215                        listener(view, cx)
2216                    }
2217                })
2218                .is_ok()
2219            }));
2220        self.app.defer(move |_| activate());
2221        subscription
2222    }
2223
2224    /// Schedule a future to be run asynchronously.
2225    /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
2226    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
2227    /// The returned future will be polled on the main thread.
2228    pub fn spawn<Fut, R>(
2229        &mut self,
2230        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2231    ) -> Task<R>
2232    where
2233        R: 'static,
2234        Fut: Future<Output = R> + 'static,
2235    {
2236        let view = self.view().downgrade();
2237        self.window_cx.spawn(|cx| f(view, cx))
2238    }
2239
2240    /// Updates the global state of the given type.
2241    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2242    where
2243        G: Global,
2244    {
2245        let mut global = self.app.lease_global::<G>();
2246        let result = f(&mut global, self);
2247        self.app.end_global_lease(global);
2248        result
2249    }
2250
2251    /// Register a callback to be invoked when the given global state changes.
2252    pub fn observe_global<G: Global>(
2253        &mut self,
2254        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2255    ) -> Subscription {
2256        let window_handle = self.window.handle;
2257        let view = self.view().downgrade();
2258        let (subscription, activate) = self.global_observers.insert(
2259            TypeId::of::<G>(),
2260            Box::new(move |cx| {
2261                window_handle
2262                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2263                    .unwrap_or(false)
2264            }),
2265        );
2266        self.app.defer(move |_| activate());
2267        subscription
2268    }
2269
2270    /// Register a callback to be invoked when the given Action type is dispatched to the window.
2271    pub fn on_action(
2272        &mut self,
2273        action_type: TypeId,
2274        listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2275    ) {
2276        let handle = self.view().clone();
2277        self.window_cx
2278            .on_action(action_type, move |action, phase, cx| {
2279                handle.update(cx, |view, cx| {
2280                    listener(view, action, phase, cx);
2281                })
2282            });
2283    }
2284
2285    /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
2286    pub fn emit<Evt>(&mut self, event: Evt)
2287    where
2288        Evt: 'static,
2289        V: EventEmitter<Evt>,
2290    {
2291        let emitter = self.view.model.entity_id;
2292        self.app.push_effect(Effect::Emit {
2293            emitter,
2294            event_type: TypeId::of::<Evt>(),
2295            event: Box::new(event),
2296        });
2297    }
2298
2299    /// Move focus to the current view, assuming it implements [`FocusableView`].
2300    pub fn focus_self(&mut self)
2301    where
2302        V: FocusableView,
2303    {
2304        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2305    }
2306
2307    /// Convenience method for accessing view state in an event callback.
2308    ///
2309    /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
2310    /// but it's often useful to be able to access view state in these
2311    /// callbacks. This method provides a convenient way to do so.
2312    pub fn listener<E>(
2313        &self,
2314        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2315    ) -> impl Fn(&E, &mut WindowContext) + 'static {
2316        let view = self.view().downgrade();
2317        move |e: &E, cx: &mut WindowContext| {
2318            view.update(cx, |view, cx| f(view, e, cx)).ok();
2319        }
2320    }
2321}
2322
2323impl<V> Context for ViewContext<'_, V> {
2324    type Result<U> = U;
2325
2326    fn new_model<T: 'static>(
2327        &mut self,
2328        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2329    ) -> Model<T> {
2330        self.window_cx.new_model(build_model)
2331    }
2332
2333    fn update_model<T: 'static, R>(
2334        &mut self,
2335        model: &Model<T>,
2336        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2337    ) -> R {
2338        self.window_cx.update_model(model, update)
2339    }
2340
2341    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2342    where
2343        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2344    {
2345        self.window_cx.update_window(window, update)
2346    }
2347
2348    fn read_model<T, R>(
2349        &self,
2350        handle: &Model<T>,
2351        read: impl FnOnce(&T, &AppContext) -> R,
2352    ) -> Self::Result<R>
2353    where
2354        T: 'static,
2355    {
2356        self.window_cx.read_model(handle, read)
2357    }
2358
2359    fn read_window<T, R>(
2360        &self,
2361        window: &WindowHandle<T>,
2362        read: impl FnOnce(View<T>, &AppContext) -> R,
2363    ) -> Result<R>
2364    where
2365        T: 'static,
2366    {
2367        self.window_cx.read_window(window, read)
2368    }
2369}
2370
2371impl<V: 'static> VisualContext for ViewContext<'_, V> {
2372    fn new_view<W: Render + 'static>(
2373        &mut self,
2374        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2375    ) -> Self::Result<View<W>> {
2376        self.window_cx.new_view(build_view_state)
2377    }
2378
2379    fn update_view<V2: 'static, R>(
2380        &mut self,
2381        view: &View<V2>,
2382        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2383    ) -> Self::Result<R> {
2384        self.window_cx.update_view(view, update)
2385    }
2386
2387    fn replace_root_view<W>(
2388        &mut self,
2389        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2390    ) -> Self::Result<View<W>>
2391    where
2392        W: 'static + Render,
2393    {
2394        self.window_cx.replace_root_view(build_view)
2395    }
2396
2397    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2398        self.window_cx.focus_view(view)
2399    }
2400
2401    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2402        self.window_cx.dismiss_view(view)
2403    }
2404}
2405
2406impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2407    type Target = WindowContext<'a>;
2408
2409    fn deref(&self) -> &Self::Target {
2410        &self.window_cx
2411    }
2412}
2413
2414impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2415    fn deref_mut(&mut self) -> &mut Self::Target {
2416        &mut self.window_cx
2417    }
2418}
2419
2420// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2421slotmap::new_key_type! {
2422    /// A unique identifier for a window.
2423    pub struct WindowId;
2424}
2425
2426impl WindowId {
2427    /// Converts this window ID to a `u64`.
2428    pub fn as_u64(&self) -> u64 {
2429        self.0.as_ffi()
2430    }
2431}
2432
2433/// A handle to a window with a specific root view type.
2434/// Note that this does not keep the window alive on its own.
2435#[derive(Deref, DerefMut)]
2436pub struct WindowHandle<V> {
2437    #[deref]
2438    #[deref_mut]
2439    pub(crate) any_handle: AnyWindowHandle,
2440    state_type: PhantomData<V>,
2441}
2442
2443impl<V: 'static + Render> WindowHandle<V> {
2444    /// Creates a new handle from a window ID.
2445    /// This does not check if the root type of the window is `V`.
2446    pub fn new(id: WindowId) -> Self {
2447        WindowHandle {
2448            any_handle: AnyWindowHandle {
2449                id,
2450                state_type: TypeId::of::<V>(),
2451            },
2452            state_type: PhantomData,
2453        }
2454    }
2455
2456    /// Get the root view out of this window.
2457    ///
2458    /// This will fail if the window is closed or if the root view's type does not match `V`.
2459    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2460    where
2461        C: Context,
2462    {
2463        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2464            root_view
2465                .downcast::<V>()
2466                .map_err(|_| anyhow!("the type of the window's root view has changed"))
2467        }))
2468    }
2469
2470    /// Updates the root view of this window.
2471    ///
2472    /// This will fail if the window has been closed or if the root view's type does not match
2473    pub fn update<C, R>(
2474        &self,
2475        cx: &mut C,
2476        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2477    ) -> Result<R>
2478    where
2479        C: Context,
2480    {
2481        cx.update_window(self.any_handle, |root_view, cx| {
2482            let view = root_view
2483                .downcast::<V>()
2484                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2485            Ok(cx.update_view(&view, update))
2486        })?
2487    }
2488
2489    /// Read the root view out of this window.
2490    ///
2491    /// This will fail if the window is closed or if the root view's type does not match `V`.
2492    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2493        let x = cx
2494            .windows
2495            .get(self.id)
2496            .and_then(|window| {
2497                window
2498                    .as_ref()
2499                    .and_then(|window| window.root_view.clone())
2500                    .map(|root_view| root_view.downcast::<V>())
2501            })
2502            .ok_or_else(|| anyhow!("window not found"))?
2503            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2504
2505        Ok(x.read(cx))
2506    }
2507
2508    /// Read the root view out of this window, with a callback
2509    ///
2510    /// This will fail if the window is closed or if the root view's type does not match `V`.
2511    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2512    where
2513        C: Context,
2514    {
2515        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2516    }
2517
2518    /// Read the root view pointer off of this window.
2519    ///
2520    /// This will fail if the window is closed or if the root view's type does not match `V`.
2521    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2522    where
2523        C: Context,
2524    {
2525        cx.read_window(self, |root_view, _cx| root_view.clone())
2526    }
2527
2528    /// Check if this window is 'active'.
2529    ///
2530    /// Will return `None` if the window is closed or currently
2531    /// borrowed.
2532    pub fn is_active(&self, cx: &mut AppContext) -> Option<bool> {
2533        cx.update_window(self.any_handle, |_, cx| cx.is_window_active())
2534            .ok()
2535    }
2536}
2537
2538impl<V> Copy for WindowHandle<V> {}
2539
2540impl<V> Clone for WindowHandle<V> {
2541    fn clone(&self) -> Self {
2542        *self
2543    }
2544}
2545
2546impl<V> PartialEq for WindowHandle<V> {
2547    fn eq(&self, other: &Self) -> bool {
2548        self.any_handle == other.any_handle
2549    }
2550}
2551
2552impl<V> Eq for WindowHandle<V> {}
2553
2554impl<V> Hash for WindowHandle<V> {
2555    fn hash<H: Hasher>(&self, state: &mut H) {
2556        self.any_handle.hash(state);
2557    }
2558}
2559
2560impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
2561    fn from(val: WindowHandle<V>) -> Self {
2562        val.any_handle
2563    }
2564}
2565
2566/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
2567#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2568pub struct AnyWindowHandle {
2569    pub(crate) id: WindowId,
2570    state_type: TypeId,
2571}
2572
2573impl AnyWindowHandle {
2574    /// Get the ID of this window.
2575    pub fn window_id(&self) -> WindowId {
2576        self.id
2577    }
2578
2579    /// Attempt to convert this handle to a window handle with a specific root view type.
2580    /// If the types do not match, this will return `None`.
2581    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2582        if TypeId::of::<T>() == self.state_type {
2583            Some(WindowHandle {
2584                any_handle: *self,
2585                state_type: PhantomData,
2586            })
2587        } else {
2588            None
2589        }
2590    }
2591
2592    /// Updates the state of the root view of this window.
2593    ///
2594    /// This will fail if the window has been closed.
2595    pub fn update<C, R>(
2596        self,
2597        cx: &mut C,
2598        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2599    ) -> Result<R>
2600    where
2601        C: Context,
2602    {
2603        cx.update_window(self, update)
2604    }
2605
2606    /// Read the state of the root view of this window.
2607    ///
2608    /// This will fail if the window has been closed.
2609    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2610    where
2611        C: Context,
2612        T: 'static,
2613    {
2614        let view = self
2615            .downcast::<T>()
2616            .context("the type of the window's root view has changed")?;
2617
2618        cx.read_window(&view, read)
2619    }
2620}
2621
2622/// An identifier for an [`Element`](crate::Element).
2623///
2624/// Can be constructed with a string, a number, or both, as well
2625/// as other internal representations.
2626#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2627pub enum ElementId {
2628    /// The ID of a View element
2629    View(EntityId),
2630    /// An integer ID.
2631    Integer(usize),
2632    /// A string based ID.
2633    Name(SharedString),
2634    /// An ID that's equated with a focus handle.
2635    FocusHandle(FocusId),
2636    /// A combination of a name and an integer.
2637    NamedInteger(SharedString, usize),
2638}
2639
2640impl Display for ElementId {
2641    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2642        match self {
2643            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
2644            ElementId::Integer(ix) => write!(f, "{}", ix)?,
2645            ElementId::Name(name) => write!(f, "{}", name)?,
2646            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
2647            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
2648        }
2649
2650        Ok(())
2651    }
2652}
2653
2654impl TryInto<SharedString> for ElementId {
2655    type Error = anyhow::Error;
2656
2657    fn try_into(self) -> anyhow::Result<SharedString> {
2658        if let ElementId::Name(name) = self {
2659            Ok(name)
2660        } else {
2661            Err(anyhow!("element id is not string"))
2662        }
2663    }
2664}
2665
2666impl From<usize> for ElementId {
2667    fn from(id: usize) -> Self {
2668        ElementId::Integer(id)
2669    }
2670}
2671
2672impl From<i32> for ElementId {
2673    fn from(id: i32) -> Self {
2674        Self::Integer(id as usize)
2675    }
2676}
2677
2678impl From<SharedString> for ElementId {
2679    fn from(name: SharedString) -> Self {
2680        ElementId::Name(name)
2681    }
2682}
2683
2684impl From<&'static str> for ElementId {
2685    fn from(name: &'static str) -> Self {
2686        ElementId::Name(name.into())
2687    }
2688}
2689
2690impl<'a> From<&'a FocusHandle> for ElementId {
2691    fn from(handle: &'a FocusHandle) -> Self {
2692        ElementId::FocusHandle(handle.id)
2693    }
2694}
2695
2696impl From<(&'static str, EntityId)> for ElementId {
2697    fn from((name, id): (&'static str, EntityId)) -> Self {
2698        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
2699    }
2700}
2701
2702impl From<(&'static str, usize)> for ElementId {
2703    fn from((name, id): (&'static str, usize)) -> Self {
2704        ElementId::NamedInteger(name.into(), id)
2705    }
2706}
2707
2708impl From<(&'static str, u64)> for ElementId {
2709    fn from((name, id): (&'static str, u64)) -> Self {
2710        ElementId::NamedInteger(name.into(), id as usize)
2711    }
2712}
2713
2714/// A rectangle to be rendered in the window at the given position and size.
2715/// Passed as an argument [`ElementContext::paint_quad`].
2716#[derive(Clone)]
2717pub struct PaintQuad {
2718    bounds: Bounds<Pixels>,
2719    corner_radii: Corners<Pixels>,
2720    background: Hsla,
2721    border_widths: Edges<Pixels>,
2722    border_color: Hsla,
2723}
2724
2725impl PaintQuad {
2726    /// Sets the corner radii of the quad.
2727    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
2728        PaintQuad {
2729            corner_radii: corner_radii.into(),
2730            ..self
2731        }
2732    }
2733
2734    /// Sets the border widths of the quad.
2735    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
2736        PaintQuad {
2737            border_widths: border_widths.into(),
2738            ..self
2739        }
2740    }
2741
2742    /// Sets the border color of the quad.
2743    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
2744        PaintQuad {
2745            border_color: border_color.into(),
2746            ..self
2747        }
2748    }
2749
2750    /// Sets the background color of the quad.
2751    pub fn background(self, background: impl Into<Hsla>) -> Self {
2752        PaintQuad {
2753            background: background.into(),
2754            ..self
2755        }
2756    }
2757}
2758
2759/// Creates a quad with the given parameters.
2760pub fn quad(
2761    bounds: Bounds<Pixels>,
2762    corner_radii: impl Into<Corners<Pixels>>,
2763    background: impl Into<Hsla>,
2764    border_widths: impl Into<Edges<Pixels>>,
2765    border_color: impl Into<Hsla>,
2766) -> PaintQuad {
2767    PaintQuad {
2768        bounds,
2769        corner_radii: corner_radii.into(),
2770        background: background.into(),
2771        border_widths: border_widths.into(),
2772        border_color: border_color.into(),
2773    }
2774}
2775
2776/// Creates a filled quad with the given bounds and background color.
2777pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
2778    PaintQuad {
2779        bounds: bounds.into(),
2780        corner_radii: (0.).into(),
2781        background: background.into(),
2782        border_widths: (0.).into(),
2783        border_color: transparent_black(),
2784    }
2785}
2786
2787/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
2788pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
2789    PaintQuad {
2790        bounds: bounds.into(),
2791        corner_radii: (0.).into(),
2792        background: transparent_black(),
2793        border_widths: (1.).into(),
2794        border_color: border_color.into(),
2795    }
2796}