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