window.rs

   1use crate::{
   2    hash, point, prelude::*, px, size, transparent_black, Action, AnyDrag, AnyElement, AnyTooltip,
   3    AnyView, AppContext, Arena, Asset, AsyncWindowContext, AvailableSpace, Bounds, BoxShadow,
   4    Context, Corners, CursorStyle, DevicePixels, DispatchActionListener, DispatchNodeId,
   5    DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter, FileDropEvent, Flatten,
   6    FontId, Global, GlobalElementId, GlyphId, Hsla, ImageData, InputHandler, IsZero, KeyBinding,
   7    KeyContext, KeyDownEvent, KeyEvent, KeyMatch, KeymatchResult, Keystroke, KeystrokeEvent,
   8    LayoutId, LineLayoutIndex, Model, ModelContext, Modifiers, ModifiersChangedEvent,
   9    MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels,
  10    PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point,
  11    PolychromeSprite, PromptLevel, Quad, Render, RenderGlyphParams, RenderImageParams,
  12    RenderSvgParams, ScaledPixels, Scene, Shadow, SharedString, Size, StrikethroughStyle, Style,
  13    SubscriberSet, Subscription, TaffyLayoutEngine, Task, TextStyle, TextStyleRefinement,
  14    TransformationMatrix, Underline, UnderlineStyle, View, VisualContext, WeakView,
  15    WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowOptions, WindowParams,
  16    WindowTextSystem, SUBPIXEL_VARIANTS,
  17};
  18use anyhow::{anyhow, Context as _, Result};
  19use collections::{FxHashMap, FxHashSet};
  20use derive_more::{Deref, DerefMut};
  21use futures::channel::oneshot;
  22use futures::{future::Shared, FutureExt};
  23#[cfg(target_os = "macos")]
  24use media::core_video::CVImageBuffer;
  25use parking_lot::RwLock;
  26use refineable::Refineable;
  27use slotmap::SlotMap;
  28use smallvec::SmallVec;
  29use std::{
  30    any::{Any, TypeId},
  31    borrow::{Borrow, BorrowMut, Cow},
  32    cell::{Cell, RefCell},
  33    cmp,
  34    fmt::{Debug, Display},
  35    future::Future,
  36    hash::{Hash, Hasher},
  37    marker::PhantomData,
  38    mem,
  39    ops::Range,
  40    rc::Rc,
  41    sync::{
  42        atomic::{AtomicUsize, Ordering::SeqCst},
  43        Arc, Weak,
  44    },
  45    time::{Duration, Instant},
  46};
  47use util::post_inc;
  48use util::{measure, ResultExt};
  49use uuid::Uuid;
  50
  51mod prompts;
  52
  53pub use prompts::*;
  54
  55pub(crate) const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1024.), px(700.));
  56
  57/// Represents the two different phases when dispatching events.
  58#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
  59pub enum DispatchPhase {
  60    /// After the capture phase comes the bubble phase, in which mouse event listeners are
  61    /// invoked front to back and keyboard event listeners are invoked from the focused element
  62    /// to the root of the element tree. This is the phase you'll most commonly want to use when
  63    /// registering event listeners.
  64    #[default]
  65    Bubble,
  66    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
  67    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
  68    /// is used for special purposes such as clearing the "pressed" state for click events. If
  69    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
  70    /// outside of the immediate region may rely on detecting non-local events during this phase.
  71    Capture,
  72}
  73
  74impl DispatchPhase {
  75    /// Returns true if this represents the "bubble" phase.
  76    pub fn bubble(self) -> bool {
  77        self == DispatchPhase::Bubble
  78    }
  79
  80    /// Returns true if this represents the "capture" phase.
  81    pub fn capture(self) -> bool {
  82        self == DispatchPhase::Capture
  83    }
  84}
  85
  86type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
  87
  88type AnyWindowFocusListener =
  89    Box<dyn FnMut(&WindowFocusEvent, &mut WindowContext) -> bool + 'static>;
  90
  91struct WindowFocusEvent {
  92    previous_focus_path: SmallVec<[FocusId; 8]>,
  93    current_focus_path: SmallVec<[FocusId; 8]>,
  94}
  95
  96impl WindowFocusEvent {
  97    pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
  98        !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
  99    }
 100
 101    pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
 102        self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
 103    }
 104}
 105
 106/// This is provided when subscribing for `ViewContext::on_focus_out` events.
 107pub struct FocusOutEvent {
 108    /// A weak focus handle representing what was blurred.
 109    pub blurred: WeakFocusHandle,
 110}
 111
 112slotmap::new_key_type! {
 113    /// A globally unique identifier for a focusable element.
 114    pub struct FocusId;
 115}
 116
 117thread_local! {
 118    /// 8MB wasn't quite enough...
 119    pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(32 * 1024 * 1024));
 120}
 121
 122impl FocusId {
 123    /// Obtains whether the element associated with this handle is currently focused.
 124    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 125        cx.window.focus == Some(*self)
 126    }
 127
 128    /// Obtains whether the element associated with this handle contains the focused
 129    /// element or is itself focused.
 130    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 131        cx.focused()
 132            .map_or(false, |focused| self.contains(focused.id, cx))
 133    }
 134
 135    /// Obtains whether the element associated with this handle is contained within the
 136    /// focused element or is itself focused.
 137    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 138        let focused = cx.focused();
 139        focused.map_or(false, |focused| focused.id.contains(*self, cx))
 140    }
 141
 142    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 143    pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
 144        cx.window
 145            .rendered_frame
 146            .dispatch_tree
 147            .focus_contains(*self, other)
 148    }
 149}
 150
 151/// A handle which can be used to track and manipulate the focused element in a window.
 152pub struct FocusHandle {
 153    pub(crate) id: FocusId,
 154    handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 155}
 156
 157impl std::fmt::Debug for FocusHandle {
 158    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 159        f.write_fmt(format_args!("FocusHandle({:?})", self.id))
 160    }
 161}
 162
 163impl FocusHandle {
 164    pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
 165        let id = handles.write().insert(AtomicUsize::new(1));
 166        Self {
 167            id,
 168            handles: handles.clone(),
 169        }
 170    }
 171
 172    pub(crate) fn for_id(
 173        id: FocusId,
 174        handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 175    ) -> Option<Self> {
 176        let lock = handles.read();
 177        let ref_count = lock.get(id)?;
 178        if ref_count.load(SeqCst) == 0 {
 179            None
 180        } else {
 181            ref_count.fetch_add(1, SeqCst);
 182            Some(Self {
 183                id,
 184                handles: handles.clone(),
 185            })
 186        }
 187    }
 188
 189    /// Converts this focus handle into a weak variant, which does not prevent it from being released.
 190    pub fn downgrade(&self) -> WeakFocusHandle {
 191        WeakFocusHandle {
 192            id: self.id,
 193            handles: Arc::downgrade(&self.handles),
 194        }
 195    }
 196
 197    /// Moves the focus to the element associated with this handle.
 198    pub fn focus(&self, cx: &mut WindowContext) {
 199        cx.focus(self)
 200    }
 201
 202    /// Obtains whether the element associated with this handle is currently focused.
 203    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 204        self.id.is_focused(cx)
 205    }
 206
 207    /// Obtains whether the element associated with this handle contains the focused
 208    /// element or is itself focused.
 209    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 210        self.id.contains_focused(cx)
 211    }
 212
 213    /// Obtains whether the element associated with this handle is contained within the
 214    /// focused element or is itself focused.
 215    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 216        self.id.within_focused(cx)
 217    }
 218
 219    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 220    pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
 221        self.id.contains(other.id, cx)
 222    }
 223
 224    /// Dispatch an action on the element that rendered this focus handle
 225    pub fn dispatch_action(&self, action: &dyn Action, cx: &mut WindowContext) {
 226        if let Some(node_id) = cx
 227            .window
 228            .rendered_frame
 229            .dispatch_tree
 230            .focusable_node_id(self.id)
 231        {
 232            cx.dispatch_action_on_node(node_id, action)
 233        }
 234    }
 235}
 236
 237impl Clone for FocusHandle {
 238    fn clone(&self) -> Self {
 239        Self::for_id(self.id, &self.handles).unwrap()
 240    }
 241}
 242
 243impl PartialEq for FocusHandle {
 244    fn eq(&self, other: &Self) -> bool {
 245        self.id == other.id
 246    }
 247}
 248
 249impl Eq for FocusHandle {}
 250
 251impl Drop for FocusHandle {
 252    fn drop(&mut self) {
 253        self.handles
 254            .read()
 255            .get(self.id)
 256            .unwrap()
 257            .fetch_sub(1, SeqCst);
 258    }
 259}
 260
 261/// A weak reference to a focus handle.
 262#[derive(Clone, Debug)]
 263pub struct WeakFocusHandle {
 264    pub(crate) id: FocusId,
 265    handles: Weak<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 266}
 267
 268impl WeakFocusHandle {
 269    /// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle].
 270    pub fn upgrade(&self) -> Option<FocusHandle> {
 271        let handles = self.handles.upgrade()?;
 272        FocusHandle::for_id(self.id, &handles)
 273    }
 274}
 275
 276impl PartialEq for WeakFocusHandle {
 277    fn eq(&self, other: &WeakFocusHandle) -> bool {
 278        self.id == other.id
 279    }
 280}
 281
 282impl Eq for WeakFocusHandle {}
 283
 284impl PartialEq<FocusHandle> for WeakFocusHandle {
 285    fn eq(&self, other: &FocusHandle) -> bool {
 286        self.id == other.id
 287    }
 288}
 289
 290impl PartialEq<WeakFocusHandle> for FocusHandle {
 291    fn eq(&self, other: &WeakFocusHandle) -> bool {
 292        self.id == other.id
 293    }
 294}
 295
 296/// FocusableView allows users of your view to easily
 297/// focus it (using cx.focus_view(view))
 298pub trait FocusableView: 'static + Render {
 299    /// Returns the focus handle associated with this view.
 300    fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
 301}
 302
 303/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
 304/// where the lifecycle of the view is handled by another view.
 305pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
 306
 307impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
 308
 309/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
 310pub struct DismissEvent;
 311
 312type FrameCallback = Box<dyn FnOnce(&mut WindowContext)>;
 313
 314pub(crate) type AnyMouseListener =
 315    Box<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
 316
 317#[derive(Clone)]
 318pub(crate) struct CursorStyleRequest {
 319    pub(crate) hitbox_id: HitboxId,
 320    pub(crate) style: CursorStyle,
 321}
 322
 323/// An identifier for a [Hitbox].
 324#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
 325pub struct HitboxId(usize);
 326
 327impl HitboxId {
 328    /// Checks if the hitbox with this id is currently hovered.
 329    pub fn is_hovered(&self, cx: &WindowContext) -> bool {
 330        cx.window.mouse_hit_test.0.contains(self)
 331    }
 332}
 333
 334/// A rectangular region that potentially blocks hitboxes inserted prior.
 335/// See [WindowContext::insert_hitbox] for more details.
 336#[derive(Clone, Debug, Deref)]
 337pub struct Hitbox {
 338    /// A unique identifier for the hitbox.
 339    pub id: HitboxId,
 340    /// The bounds of the hitbox.
 341    #[deref]
 342    pub bounds: Bounds<Pixels>,
 343    /// The content mask when the hitbox was inserted.
 344    pub content_mask: ContentMask<Pixels>,
 345    /// Whether the hitbox occludes other hitboxes inserted prior.
 346    pub opaque: bool,
 347}
 348
 349impl Hitbox {
 350    /// Checks if the hitbox is currently hovered.
 351    pub fn is_hovered(&self, cx: &WindowContext) -> bool {
 352        self.id.is_hovered(cx)
 353    }
 354}
 355
 356#[derive(Default, Eq, PartialEq)]
 357pub(crate) struct HitTest(SmallVec<[HitboxId; 8]>);
 358
 359/// An identifier for a tooltip.
 360#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
 361pub struct TooltipId(usize);
 362
 363impl TooltipId {
 364    /// Checks if the tooltip is currently hovered.
 365    pub fn is_hovered(&self, cx: &WindowContext) -> bool {
 366        cx.window
 367            .tooltip_bounds
 368            .as_ref()
 369            .map_or(false, |tooltip_bounds| {
 370                tooltip_bounds.id == *self && tooltip_bounds.bounds.contains(&cx.mouse_position())
 371            })
 372    }
 373}
 374
 375pub(crate) struct TooltipBounds {
 376    id: TooltipId,
 377    bounds: Bounds<Pixels>,
 378}
 379
 380#[derive(Clone)]
 381pub(crate) struct TooltipRequest {
 382    id: TooltipId,
 383    tooltip: AnyTooltip,
 384}
 385
 386pub(crate) struct DeferredDraw {
 387    priority: usize,
 388    parent_node: DispatchNodeId,
 389    element_id_stack: SmallVec<[ElementId; 32]>,
 390    text_style_stack: Vec<TextStyleRefinement>,
 391    element: Option<AnyElement>,
 392    absolute_offset: Point<Pixels>,
 393    prepaint_range: Range<PrepaintStateIndex>,
 394    paint_range: Range<PaintIndex>,
 395}
 396
 397pub(crate) struct Frame {
 398    pub(crate) focus: Option<FocusId>,
 399    pub(crate) window_active: bool,
 400    pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
 401    accessed_element_states: Vec<(GlobalElementId, TypeId)>,
 402    pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
 403    pub(crate) dispatch_tree: DispatchTree,
 404    pub(crate) scene: Scene,
 405    pub(crate) hitboxes: Vec<Hitbox>,
 406    pub(crate) deferred_draws: Vec<DeferredDraw>,
 407    pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
 408    pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
 409    pub(crate) cursor_styles: Vec<CursorStyleRequest>,
 410    #[cfg(any(test, feature = "test-support"))]
 411    pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
 412}
 413
 414#[derive(Clone, Default)]
 415pub(crate) struct PrepaintStateIndex {
 416    hitboxes_index: usize,
 417    tooltips_index: usize,
 418    deferred_draws_index: usize,
 419    dispatch_tree_index: usize,
 420    accessed_element_states_index: usize,
 421    line_layout_index: LineLayoutIndex,
 422}
 423
 424#[derive(Clone, Default)]
 425pub(crate) struct PaintIndex {
 426    scene_index: usize,
 427    mouse_listeners_index: usize,
 428    input_handlers_index: usize,
 429    cursor_styles_index: usize,
 430    accessed_element_states_index: usize,
 431    line_layout_index: LineLayoutIndex,
 432}
 433
 434impl Frame {
 435    pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
 436        Frame {
 437            focus: None,
 438            window_active: false,
 439            element_states: FxHashMap::default(),
 440            accessed_element_states: Vec::new(),
 441            mouse_listeners: Vec::new(),
 442            dispatch_tree,
 443            scene: Scene::default(),
 444            hitboxes: Vec::new(),
 445            deferred_draws: Vec::new(),
 446            input_handlers: Vec::new(),
 447            tooltip_requests: Vec::new(),
 448            cursor_styles: Vec::new(),
 449
 450            #[cfg(any(test, feature = "test-support"))]
 451            debug_bounds: FxHashMap::default(),
 452        }
 453    }
 454
 455    pub(crate) fn clear(&mut self) {
 456        self.element_states.clear();
 457        self.accessed_element_states.clear();
 458        self.mouse_listeners.clear();
 459        self.dispatch_tree.clear();
 460        self.scene.clear();
 461        self.input_handlers.clear();
 462        self.tooltip_requests.clear();
 463        self.cursor_styles.clear();
 464        self.hitboxes.clear();
 465        self.deferred_draws.clear();
 466    }
 467
 468    pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
 469        let mut hit_test = HitTest::default();
 470        for hitbox in self.hitboxes.iter().rev() {
 471            let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
 472            if bounds.contains(&position) {
 473                hit_test.0.push(hitbox.id);
 474                if hitbox.opaque {
 475                    break;
 476                }
 477            }
 478        }
 479        hit_test
 480    }
 481
 482    pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
 483        self.focus
 484            .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
 485            .unwrap_or_default()
 486    }
 487
 488    pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
 489        for element_state_key in &self.accessed_element_states {
 490            if let Some((element_state_key, element_state)) =
 491                prev_frame.element_states.remove_entry(element_state_key)
 492            {
 493                self.element_states.insert(element_state_key, element_state);
 494            }
 495        }
 496
 497        self.scene.finish();
 498    }
 499}
 500
 501// Holds the state for a specific window.
 502#[doc(hidden)]
 503pub struct Window {
 504    pub(crate) handle: AnyWindowHandle,
 505    pub(crate) removed: bool,
 506    pub(crate) platform_window: Box<dyn PlatformWindow>,
 507    display_id: Option<DisplayId>,
 508    sprite_atlas: Arc<dyn PlatformAtlas>,
 509    text_system: Arc<WindowTextSystem>,
 510    rem_size: Pixels,
 511    /// The stack of override values for the window's rem size.
 512    ///
 513    /// This is used by `with_rem_size` to allow rendering an element tree with
 514    /// a given rem size.
 515    rem_size_override_stack: SmallVec<[Pixels; 8]>,
 516    pub(crate) viewport_size: Size<Pixels>,
 517    layout_engine: Option<TaffyLayoutEngine>,
 518    pub(crate) root_view: Option<AnyView>,
 519    pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
 520    pub(crate) text_style_stack: Vec<TextStyleRefinement>,
 521    pub(crate) element_offset_stack: Vec<Point<Pixels>>,
 522    pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
 523    pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
 524    pub(crate) rendered_frame: Frame,
 525    pub(crate) next_frame: Frame,
 526    pub(crate) next_hitbox_id: HitboxId,
 527    pub(crate) next_tooltip_id: TooltipId,
 528    pub(crate) tooltip_bounds: Option<TooltipBounds>,
 529    next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
 530    pub(crate) dirty_views: FxHashSet<EntityId>,
 531    pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 532    focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
 533    focus_lost_listeners: SubscriberSet<(), AnyObserver>,
 534    default_prevented: bool,
 535    mouse_position: Point<Pixels>,
 536    mouse_hit_test: HitTest,
 537    modifiers: Modifiers,
 538    scale_factor: f32,
 539    bounds_observers: SubscriberSet<(), AnyObserver>,
 540    appearance: WindowAppearance,
 541    appearance_observers: SubscriberSet<(), AnyObserver>,
 542    active: Rc<Cell<bool>>,
 543    pub(crate) dirty: Rc<Cell<bool>>,
 544    pub(crate) needs_present: Rc<Cell<bool>>,
 545    pub(crate) last_input_timestamp: Rc<Cell<Instant>>,
 546    pub(crate) refreshing: bool,
 547    pub(crate) draw_phase: DrawPhase,
 548    activation_observers: SubscriberSet<(), AnyObserver>,
 549    pub(crate) focus: Option<FocusId>,
 550    focus_enabled: bool,
 551    pending_input: Option<PendingInput>,
 552    pending_modifier: ModifierState,
 553    pending_input_observers: SubscriberSet<(), AnyObserver>,
 554    prompt: Option<RenderablePromptHandle>,
 555}
 556
 557#[derive(Clone, Debug, Default)]
 558struct ModifierState {
 559    modifiers: Modifiers,
 560    saw_keystroke: bool,
 561}
 562
 563#[derive(Clone, Copy, Debug, Eq, PartialEq)]
 564pub(crate) enum DrawPhase {
 565    None,
 566    Prepaint,
 567    Paint,
 568    Focus,
 569}
 570
 571#[derive(Default, Debug)]
 572struct PendingInput {
 573    keystrokes: SmallVec<[Keystroke; 1]>,
 574    bindings: SmallVec<[KeyBinding; 1]>,
 575    focus: Option<FocusId>,
 576    timer: Option<Task<()>>,
 577}
 578
 579impl PendingInput {
 580    fn input(&self) -> String {
 581        self.keystrokes
 582            .iter()
 583            .flat_map(|k| k.ime_key.clone())
 584            .collect::<Vec<String>>()
 585            .join("")
 586    }
 587
 588    fn used_by_binding(&self, binding: &KeyBinding) -> bool {
 589        if self.keystrokes.is_empty() {
 590            return true;
 591        }
 592        let keystroke = &self.keystrokes[0];
 593        for candidate in keystroke.match_candidates() {
 594            if binding.match_keystrokes(&[candidate]) == KeyMatch::Pending {
 595                return true;
 596            }
 597        }
 598        false
 599    }
 600}
 601
 602pub(crate) struct ElementStateBox {
 603    pub(crate) inner: Box<dyn Any>,
 604    #[cfg(debug_assertions)]
 605    pub(crate) type_name: &'static str,
 606}
 607
 608fn default_bounds(display_id: Option<DisplayId>, cx: &mut AppContext) -> Bounds<Pixels> {
 609    const DEFAULT_WINDOW_OFFSET: Point<Pixels> = point(px(0.), px(35.));
 610
 611    cx.active_window()
 612        .and_then(|w| w.update(cx, |_, cx| cx.bounds()).ok())
 613        .map(|bounds| bounds.map_origin(|origin| origin + DEFAULT_WINDOW_OFFSET))
 614        .unwrap_or_else(|| {
 615            let display = display_id
 616                .map(|id| cx.find_display(id))
 617                .unwrap_or_else(|| cx.primary_display());
 618
 619            display
 620                .map(|display| display.default_bounds())
 621                .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE))
 622        })
 623}
 624
 625impl Window {
 626    pub(crate) fn new(
 627        handle: AnyWindowHandle,
 628        options: WindowOptions,
 629        cx: &mut AppContext,
 630    ) -> Result<Self> {
 631        let WindowOptions {
 632            window_bounds,
 633            titlebar,
 634            focus,
 635            show,
 636            kind,
 637            is_movable,
 638            display_id,
 639            window_background,
 640            app_id,
 641            window_min_size,
 642        } = options;
 643
 644        let bounds = window_bounds
 645            .map(|bounds| bounds.get_bounds())
 646            .unwrap_or_else(|| default_bounds(display_id, cx));
 647        let mut platform_window = cx.platform.open_window(
 648            handle,
 649            WindowParams {
 650                bounds,
 651                titlebar,
 652                kind,
 653                is_movable,
 654                focus,
 655                show,
 656                display_id,
 657                window_background,
 658                window_min_size,
 659            },
 660        )?;
 661        let display_id = platform_window.display().map(|display| display.id());
 662        let sprite_atlas = platform_window.sprite_atlas();
 663        let mouse_position = platform_window.mouse_position();
 664        let modifiers = platform_window.modifiers();
 665        let content_size = platform_window.content_size();
 666        let scale_factor = platform_window.scale_factor();
 667        let appearance = platform_window.appearance();
 668        let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
 669        let dirty = Rc::new(Cell::new(true));
 670        let active = Rc::new(Cell::new(platform_window.is_active()));
 671        let needs_present = Rc::new(Cell::new(false));
 672        let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
 673        let last_input_timestamp = Rc::new(Cell::new(Instant::now()));
 674
 675        if let Some(ref window_open_state) = window_bounds {
 676            match window_open_state {
 677                WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
 678                WindowBounds::Maximized(_) => platform_window.zoom(),
 679                WindowBounds::Windowed(_) => {}
 680            }
 681        }
 682
 683        platform_window.on_close(Box::new({
 684            let mut cx = cx.to_async();
 685            move || {
 686                let _ = handle.update(&mut cx, |_, cx| cx.remove_window());
 687            }
 688        }));
 689        platform_window.on_request_frame(Box::new({
 690            let mut cx = cx.to_async();
 691            let dirty = dirty.clone();
 692            let active = active.clone();
 693            let needs_present = needs_present.clone();
 694            let next_frame_callbacks = next_frame_callbacks.clone();
 695            let last_input_timestamp = last_input_timestamp.clone();
 696            move || {
 697                let next_frame_callbacks = next_frame_callbacks.take();
 698                if !next_frame_callbacks.is_empty() {
 699                    handle
 700                        .update(&mut cx, |_, cx| {
 701                            for callback in next_frame_callbacks {
 702                                callback(cx);
 703                            }
 704                        })
 705                        .log_err();
 706                }
 707
 708                // Keep presenting the current scene for 1 extra second since the
 709                // last input to prevent the display from underclocking the refresh rate.
 710                let needs_present = needs_present.get()
 711                    || (active.get()
 712                        && last_input_timestamp.get().elapsed() < Duration::from_secs(1));
 713
 714                if dirty.get() {
 715                    measure("frame duration", || {
 716                        handle
 717                            .update(&mut cx, |_, cx| {
 718                                cx.draw();
 719                                cx.present();
 720                            })
 721                            .log_err();
 722                    })
 723                } else if needs_present {
 724                    handle.update(&mut cx, |_, cx| cx.present()).log_err();
 725                }
 726
 727                handle
 728                    .update(&mut cx, |_, cx| {
 729                        cx.complete_frame();
 730                    })
 731                    .log_err();
 732            }
 733        }));
 734        platform_window.on_resize(Box::new({
 735            let mut cx = cx.to_async();
 736            move |_, _| {
 737                handle
 738                    .update(&mut cx, |_, cx| cx.bounds_changed())
 739                    .log_err();
 740            }
 741        }));
 742        platform_window.on_moved(Box::new({
 743            let mut cx = cx.to_async();
 744            move || {
 745                handle
 746                    .update(&mut cx, |_, cx| cx.bounds_changed())
 747                    .log_err();
 748            }
 749        }));
 750        platform_window.on_appearance_changed(Box::new({
 751            let mut cx = cx.to_async();
 752            move || {
 753                handle
 754                    .update(&mut cx, |_, cx| cx.appearance_changed())
 755                    .log_err();
 756            }
 757        }));
 758        platform_window.on_active_status_change(Box::new({
 759            let mut cx = cx.to_async();
 760            move |active| {
 761                handle
 762                    .update(&mut cx, |_, cx| {
 763                        cx.window.active.set(active);
 764                        cx.window
 765                            .activation_observers
 766                            .clone()
 767                            .retain(&(), |callback| callback(cx));
 768                        cx.refresh();
 769                    })
 770                    .log_err();
 771            }
 772        }));
 773
 774        platform_window.on_input({
 775            let mut cx = cx.to_async();
 776            Box::new(move |event| {
 777                handle
 778                    .update(&mut cx, |_, cx| cx.dispatch_event(event))
 779                    .log_err()
 780                    .unwrap_or(DispatchEventResult::default())
 781            })
 782        });
 783
 784        if let Some(app_id) = app_id {
 785            platform_window.set_app_id(&app_id);
 786        }
 787
 788        Ok(Window {
 789            handle,
 790            removed: false,
 791            platform_window,
 792            display_id,
 793            sprite_atlas,
 794            text_system,
 795            rem_size: px(16.),
 796            rem_size_override_stack: SmallVec::new(),
 797            viewport_size: content_size,
 798            layout_engine: Some(TaffyLayoutEngine::new()),
 799            root_view: None,
 800            element_id_stack: SmallVec::default(),
 801            text_style_stack: Vec::new(),
 802            element_offset_stack: Vec::new(),
 803            content_mask_stack: Vec::new(),
 804            requested_autoscroll: None,
 805            rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 806            next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 807            next_frame_callbacks,
 808            next_hitbox_id: HitboxId::default(),
 809            next_tooltip_id: TooltipId::default(),
 810            tooltip_bounds: None,
 811            dirty_views: FxHashSet::default(),
 812            focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
 813            focus_listeners: SubscriberSet::new(),
 814            focus_lost_listeners: SubscriberSet::new(),
 815            default_prevented: true,
 816            mouse_position,
 817            mouse_hit_test: HitTest::default(),
 818            modifiers,
 819            scale_factor,
 820            bounds_observers: SubscriberSet::new(),
 821            appearance,
 822            appearance_observers: SubscriberSet::new(),
 823            active,
 824            dirty,
 825            needs_present,
 826            last_input_timestamp,
 827            refreshing: false,
 828            draw_phase: DrawPhase::None,
 829            activation_observers: SubscriberSet::new(),
 830            focus: None,
 831            focus_enabled: true,
 832            pending_input: None,
 833            pending_modifier: ModifierState::default(),
 834            pending_input_observers: SubscriberSet::new(),
 835            prompt: None,
 836        })
 837    }
 838    fn new_focus_listener(
 839        &mut self,
 840        value: AnyWindowFocusListener,
 841    ) -> (Subscription, impl FnOnce()) {
 842        self.focus_listeners.insert((), value)
 843    }
 844}
 845
 846#[derive(Clone, Debug, Default, PartialEq, Eq)]
 847pub(crate) struct DispatchEventResult {
 848    pub propagate: bool,
 849    pub default_prevented: bool,
 850}
 851
 852/// Indicates which region of the window is visible. Content falling outside of this mask will not be
 853/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
 854/// to leave room to support more complex shapes in the future.
 855#[derive(Clone, Debug, Default, PartialEq, Eq)]
 856#[repr(C)]
 857pub struct ContentMask<P: Clone + Default + Debug> {
 858    /// The bounds
 859    pub bounds: Bounds<P>,
 860}
 861
 862impl ContentMask<Pixels> {
 863    /// Scale the content mask's pixel units by the given scaling factor.
 864    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
 865        ContentMask {
 866            bounds: self.bounds.scale(factor),
 867        }
 868    }
 869
 870    /// Intersect the content mask with the given content mask.
 871    pub fn intersect(&self, other: &Self) -> Self {
 872        let bounds = self.bounds.intersect(&other.bounds);
 873        ContentMask { bounds }
 874    }
 875}
 876
 877/// Provides access to application state in the context of a single window. Derefs
 878/// to an [`AppContext`], so you can also pass a [`WindowContext`] to any method that takes
 879/// an [`AppContext`] and call any [`AppContext`] methods.
 880pub struct WindowContext<'a> {
 881    pub(crate) app: &'a mut AppContext,
 882    pub(crate) window: &'a mut Window,
 883}
 884
 885impl<'a> WindowContext<'a> {
 886    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
 887        Self { app, window }
 888    }
 889
 890    /// Obtain a handle to the window that belongs to this context.
 891    pub fn window_handle(&self) -> AnyWindowHandle {
 892        self.window.handle
 893    }
 894
 895    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
 896    pub fn refresh(&mut self) {
 897        if self.window.draw_phase == DrawPhase::None {
 898            self.window.refreshing = true;
 899            self.window.dirty.set(true);
 900        }
 901    }
 902
 903    /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
 904    /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
 905    pub fn notify(&mut self, view_id: EntityId) {
 906        for view_id in self
 907            .window
 908            .rendered_frame
 909            .dispatch_tree
 910            .view_path(view_id)
 911            .into_iter()
 912            .rev()
 913        {
 914            if !self.window.dirty_views.insert(view_id) {
 915                break;
 916            }
 917        }
 918
 919        if self.window.draw_phase == DrawPhase::None {
 920            self.window.dirty.set(true);
 921            self.app.push_effect(Effect::Notify { emitter: view_id });
 922        }
 923    }
 924
 925    /// Close this window.
 926    pub fn remove_window(&mut self) {
 927        self.window.removed = true;
 928    }
 929
 930    /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
 931    /// for elements rendered within this window.
 932    pub fn focus_handle(&mut self) -> FocusHandle {
 933        FocusHandle::new(&self.window.focus_handles)
 934    }
 935
 936    /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
 937    pub fn focused(&self) -> Option<FocusHandle> {
 938        self.window
 939            .focus
 940            .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
 941    }
 942
 943    /// Move focus to the element associated with the given [`FocusHandle`].
 944    pub fn focus(&mut self, handle: &FocusHandle) {
 945        if !self.window.focus_enabled || self.window.focus == Some(handle.id) {
 946            return;
 947        }
 948
 949        self.window.focus = Some(handle.id);
 950        self.window
 951            .rendered_frame
 952            .dispatch_tree
 953            .clear_pending_keystrokes();
 954        self.refresh();
 955    }
 956
 957    /// Remove focus from all elements within this context's window.
 958    pub fn blur(&mut self) {
 959        if !self.window.focus_enabled {
 960            return;
 961        }
 962
 963        self.window.focus = None;
 964        self.refresh();
 965    }
 966
 967    /// Blur the window and don't allow anything in it to be focused again.
 968    pub fn disable_focus(&mut self) {
 969        self.blur();
 970        self.window.focus_enabled = false;
 971    }
 972
 973    /// Accessor for the text system.
 974    pub fn text_system(&self) -> &Arc<WindowTextSystem> {
 975        &self.window.text_system
 976    }
 977
 978    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
 979    pub fn text_style(&self) -> TextStyle {
 980        let mut style = TextStyle::default();
 981        for refinement in &self.window.text_style_stack {
 982            style.refine(refinement);
 983        }
 984        style
 985    }
 986
 987    /// Check if the platform window is maximized
 988    /// On some platforms (namely Windows) this is different than the bounds being the size of the display
 989    pub fn is_maximized(&self) -> bool {
 990        self.window.platform_window.is_maximized()
 991    }
 992
 993    /// Return the `WindowBounds` to indicate that how a window should be opened
 994    /// after it has been closed
 995    pub fn window_bounds(&self) -> WindowBounds {
 996        self.window.platform_window.window_bounds()
 997    }
 998
 999    /// Dispatch the given action on the currently focused element.
1000    pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
1001        let focus_handle = self.focused();
1002
1003        let window = self.window.handle;
1004        self.app.defer(move |cx| {
1005            window
1006                .update(cx, |_, cx| {
1007                    let node_id = focus_handle
1008                        .and_then(|handle| {
1009                            cx.window
1010                                .rendered_frame
1011                                .dispatch_tree
1012                                .focusable_node_id(handle.id)
1013                        })
1014                        .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
1015
1016                    cx.dispatch_action_on_node(node_id, action.as_ref());
1017                })
1018                .log_err();
1019        })
1020    }
1021
1022    pub(crate) fn dispatch_keystroke_observers(
1023        &mut self,
1024        event: &dyn Any,
1025        action: Option<Box<dyn Action>>,
1026    ) {
1027        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1028            return;
1029        };
1030
1031        self.keystroke_observers
1032            .clone()
1033            .retain(&(), move |callback| {
1034                (callback)(
1035                    &KeystrokeEvent {
1036                        keystroke: key_down_event.keystroke.clone(),
1037                        action: action.as_ref().map(|action| action.boxed_clone()),
1038                    },
1039                    self,
1040                );
1041                true
1042            });
1043    }
1044
1045    pub(crate) fn clear_pending_keystrokes(&mut self) {
1046        self.window
1047            .rendered_frame
1048            .dispatch_tree
1049            .clear_pending_keystrokes();
1050        self.window
1051            .next_frame
1052            .dispatch_tree
1053            .clear_pending_keystrokes();
1054    }
1055
1056    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1057    /// that are currently on the stack to be returned to the app.
1058    pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
1059        let handle = self.window.handle;
1060        self.app.defer(move |cx| {
1061            handle.update(cx, |_, cx| f(cx)).ok();
1062        });
1063    }
1064
1065    /// Subscribe to events emitted by a model or view.
1066    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1067    /// 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.
1068    pub fn observe<E, T>(
1069        &mut self,
1070        entity: &E,
1071        mut on_notify: impl FnMut(E, &mut WindowContext<'_>) + 'static,
1072    ) -> Subscription
1073    where
1074        E: Entity<T>,
1075    {
1076        let entity_id = entity.entity_id();
1077        let entity = entity.downgrade();
1078        let window_handle = self.window.handle;
1079        self.app.new_observer(
1080            entity_id,
1081            Box::new(move |cx| {
1082                window_handle
1083                    .update(cx, |_, cx| {
1084                        if let Some(handle) = E::upgrade_from(&entity) {
1085                            on_notify(handle, cx);
1086                            true
1087                        } else {
1088                            false
1089                        }
1090                    })
1091                    .unwrap_or(false)
1092            }),
1093        )
1094    }
1095
1096    /// Subscribe to events emitted by a model or view.
1097    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1098    /// 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.
1099    pub fn subscribe<Emitter, E, Evt>(
1100        &mut self,
1101        entity: &E,
1102        mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
1103    ) -> Subscription
1104    where
1105        Emitter: EventEmitter<Evt>,
1106        E: Entity<Emitter>,
1107        Evt: 'static,
1108    {
1109        let entity_id = entity.entity_id();
1110        let entity = entity.downgrade();
1111        let window_handle = self.window.handle;
1112        self.app.new_subscription(
1113            entity_id,
1114            (
1115                TypeId::of::<Evt>(),
1116                Box::new(move |event, cx| {
1117                    window_handle
1118                        .update(cx, |_, cx| {
1119                            if let Some(handle) = E::upgrade_from(&entity) {
1120                                let event = event.downcast_ref().expect("invalid event type");
1121                                on_event(handle, event, cx);
1122                                true
1123                            } else {
1124                                false
1125                            }
1126                        })
1127                        .unwrap_or(false)
1128                }),
1129            ),
1130        )
1131    }
1132
1133    /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
1134    /// await points in async code.
1135    pub fn to_async(&self) -> AsyncWindowContext {
1136        AsyncWindowContext::new(self.app.to_async(), self.window.handle)
1137    }
1138
1139    /// Schedule the given closure to be run directly after the current frame is rendered.
1140    pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
1141        RefCell::borrow_mut(&self.window.next_frame_callbacks).push(Box::new(callback));
1142    }
1143
1144    /// Spawn the future returned by the given closure on the application thread pool.
1145    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
1146    /// use within your future.
1147    pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
1148    where
1149        R: 'static,
1150        Fut: Future<Output = R> + 'static,
1151    {
1152        self.app
1153            .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
1154    }
1155
1156    fn bounds_changed(&mut self) {
1157        self.window.scale_factor = self.window.platform_window.scale_factor();
1158        self.window.viewport_size = self.window.platform_window.content_size();
1159        self.window.display_id = self
1160            .window
1161            .platform_window
1162            .display()
1163            .map(|display| display.id());
1164
1165        self.refresh();
1166
1167        self.window
1168            .bounds_observers
1169            .clone()
1170            .retain(&(), |callback| callback(self));
1171    }
1172
1173    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
1174    pub fn bounds(&self) -> Bounds<Pixels> {
1175        self.window.platform_window.bounds()
1176    }
1177
1178    /// Returns whether or not the window is currently fullscreen
1179    pub fn is_fullscreen(&self) -> bool {
1180        self.window.platform_window.is_fullscreen()
1181    }
1182
1183    pub(crate) fn appearance_changed(&mut self) {
1184        self.window.appearance = self.window.platform_window.appearance();
1185
1186        self.window
1187            .appearance_observers
1188            .clone()
1189            .retain(&(), |callback| callback(self));
1190    }
1191
1192    /// Returns the appearance of the current window.
1193    pub fn appearance(&self) -> WindowAppearance {
1194        self.window.appearance
1195    }
1196
1197    /// Returns the size of the drawable area within the window.
1198    pub fn viewport_size(&self) -> Size<Pixels> {
1199        self.window.viewport_size
1200    }
1201
1202    /// Returns whether this window is focused by the operating system (receiving key events).
1203    pub fn is_window_active(&self) -> bool {
1204        self.window.active.get()
1205    }
1206
1207    /// Toggle zoom on the window.
1208    pub fn zoom_window(&self) {
1209        self.window.platform_window.zoom();
1210    }
1211
1212    /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
1213    pub fn show_window_menu(&self, position: Point<Pixels>) {
1214        self.window.platform_window.show_window_menu(position)
1215    }
1216
1217    /// Tells the compositor to take control of window movement (Wayland and X11)
1218    ///
1219    /// Events may not be received during a move operation.
1220    pub fn start_system_move(&self) {
1221        self.window.platform_window.start_system_move()
1222    }
1223
1224    /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
1225    pub fn should_render_window_controls(&self) -> bool {
1226        self.window.platform_window.should_render_window_controls()
1227    }
1228
1229    /// Updates the window's title at the platform level.
1230    pub fn set_window_title(&mut self, title: &str) {
1231        self.window.platform_window.set_title(title);
1232    }
1233
1234    /// Sets the application identifier.
1235    pub fn set_app_id(&mut self, app_id: &str) {
1236        self.window.platform_window.set_app_id(app_id);
1237    }
1238
1239    /// Sets the window background appearance.
1240    pub fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance) {
1241        self.window
1242            .platform_window
1243            .set_background_appearance(background_appearance);
1244    }
1245
1246    /// Mark the window as dirty at the platform level.
1247    pub fn set_window_edited(&mut self, edited: bool) {
1248        self.window.platform_window.set_edited(edited);
1249    }
1250
1251    /// Determine the display on which the window is visible.
1252    pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1253        self.platform
1254            .displays()
1255            .into_iter()
1256            .find(|display| Some(display.id()) == self.window.display_id)
1257    }
1258
1259    /// Show the platform character palette.
1260    pub fn show_character_palette(&self) {
1261        self.window.platform_window.show_character_palette();
1262    }
1263
1264    /// The scale factor of the display associated with the window. For example, it could
1265    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
1266    /// be rendered as two pixels on screen.
1267    pub fn scale_factor(&self) -> f32 {
1268        self.window.scale_factor
1269    }
1270
1271    /// The size of an em for the base font of the application. Adjusting this value allows the
1272    /// UI to scale, just like zooming a web page.
1273    pub fn rem_size(&self) -> Pixels {
1274        self.window
1275            .rem_size_override_stack
1276            .last()
1277            .copied()
1278            .unwrap_or(self.window.rem_size)
1279    }
1280
1281    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
1282    /// UI to scale, just like zooming a web page.
1283    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
1284        self.window.rem_size = rem_size.into();
1285    }
1286
1287    /// Executes the provided function with the specified rem size.
1288    ///
1289    /// This method must only be called as part of element drawing.
1290    pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
1291    where
1292        F: FnOnce(&mut Self) -> R,
1293    {
1294        debug_assert!(
1295            matches!(
1296                self.window.draw_phase,
1297                DrawPhase::Prepaint | DrawPhase::Paint
1298            ),
1299            "this method can only be called during request_layout, prepaint, or paint"
1300        );
1301
1302        if let Some(rem_size) = rem_size {
1303            self.window.rem_size_override_stack.push(rem_size.into());
1304            let result = f(self);
1305            self.window.rem_size_override_stack.pop();
1306            result
1307        } else {
1308            f(self)
1309        }
1310    }
1311
1312    /// The line height associated with the current text style.
1313    pub fn line_height(&self) -> Pixels {
1314        let rem_size = self.rem_size();
1315        let text_style = self.text_style();
1316        text_style
1317            .line_height
1318            .to_pixels(text_style.font_size, rem_size)
1319    }
1320
1321    /// Call to prevent the default action of an event. Currently only used to prevent
1322    /// parent elements from becoming focused on mouse down.
1323    pub fn prevent_default(&mut self) {
1324        self.window.default_prevented = true;
1325    }
1326
1327    /// Obtain whether default has been prevented for the event currently being dispatched.
1328    pub fn default_prevented(&self) -> bool {
1329        self.window.default_prevented
1330    }
1331
1332    /// Determine whether the given action is available along the dispatch path to the currently focused element.
1333    pub fn is_action_available(&self, action: &dyn Action) -> bool {
1334        let target = self
1335            .focused()
1336            .and_then(|focused_handle| {
1337                self.window
1338                    .rendered_frame
1339                    .dispatch_tree
1340                    .focusable_node_id(focused_handle.id)
1341            })
1342            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1343        self.window
1344            .rendered_frame
1345            .dispatch_tree
1346            .is_action_available(action, target)
1347    }
1348
1349    /// The position of the mouse relative to the window.
1350    pub fn mouse_position(&self) -> Point<Pixels> {
1351        self.window.mouse_position
1352    }
1353
1354    /// The current state of the keyboard's modifiers
1355    pub fn modifiers(&self) -> Modifiers {
1356        self.window.modifiers
1357    }
1358
1359    fn complete_frame(&self) {
1360        self.window.platform_window.completed_frame();
1361    }
1362
1363    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
1364    /// the contents of the new [Scene], use [present].
1365    #[profiling::function]
1366    pub fn draw(&mut self) {
1367        self.window.dirty.set(false);
1368        self.window.requested_autoscroll = None;
1369
1370        // Restore the previously-used input handler.
1371        if let Some(input_handler) = self.window.platform_window.take_input_handler() {
1372            self.window
1373                .rendered_frame
1374                .input_handlers
1375                .push(Some(input_handler));
1376        }
1377
1378        self.draw_roots();
1379        self.window.dirty_views.clear();
1380
1381        self.window
1382            .next_frame
1383            .dispatch_tree
1384            .preserve_pending_keystrokes(
1385                &mut self.window.rendered_frame.dispatch_tree,
1386                self.window.focus,
1387            );
1388        self.window.next_frame.focus = self.window.focus;
1389        self.window.next_frame.window_active = self.window.active.get();
1390
1391        // Register requested input handler with the platform window.
1392        if let Some(input_handler) = self.window.next_frame.input_handlers.pop() {
1393            self.window
1394                .platform_window
1395                .set_input_handler(input_handler.unwrap());
1396        }
1397
1398        self.window.layout_engine.as_mut().unwrap().clear();
1399        self.text_system().finish_frame();
1400        self.window
1401            .next_frame
1402            .finish(&mut self.window.rendered_frame);
1403        ELEMENT_ARENA.with_borrow_mut(|element_arena| {
1404            let percentage = (element_arena.len() as f32 / element_arena.capacity() as f32) * 100.;
1405            if percentage >= 80. {
1406                log::warn!("elevated element arena occupation: {}.", percentage);
1407            }
1408            element_arena.clear();
1409        });
1410
1411        self.window.draw_phase = DrawPhase::Focus;
1412        let previous_focus_path = self.window.rendered_frame.focus_path();
1413        let previous_window_active = self.window.rendered_frame.window_active;
1414        mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1415        self.window.next_frame.clear();
1416        let current_focus_path = self.window.rendered_frame.focus_path();
1417        let current_window_active = self.window.rendered_frame.window_active;
1418
1419        if previous_focus_path != current_focus_path
1420            || previous_window_active != current_window_active
1421        {
1422            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1423                self.window
1424                    .focus_lost_listeners
1425                    .clone()
1426                    .retain(&(), |listener| listener(self));
1427            }
1428
1429            let event = WindowFocusEvent {
1430                previous_focus_path: if previous_window_active {
1431                    previous_focus_path
1432                } else {
1433                    Default::default()
1434                },
1435                current_focus_path: if current_window_active {
1436                    current_focus_path
1437                } else {
1438                    Default::default()
1439                },
1440            };
1441            self.window
1442                .focus_listeners
1443                .clone()
1444                .retain(&(), |listener| listener(&event, self));
1445        }
1446
1447        self.reset_cursor_style();
1448        self.window.refreshing = false;
1449        self.window.draw_phase = DrawPhase::None;
1450        self.window.needs_present.set(true);
1451    }
1452
1453    #[profiling::function]
1454    fn present(&self) {
1455        self.window
1456            .platform_window
1457            .draw(&self.window.rendered_frame.scene);
1458        self.window.needs_present.set(false);
1459        profiling::finish_frame!();
1460    }
1461
1462    fn draw_roots(&mut self) {
1463        self.window.draw_phase = DrawPhase::Prepaint;
1464        self.window.tooltip_bounds.take();
1465
1466        // Layout all root elements.
1467        let mut root_element = self.window.root_view.as_ref().unwrap().clone().into_any();
1468        root_element.prepaint_as_root(Point::default(), self.window.viewport_size.into(), self);
1469
1470        let mut sorted_deferred_draws =
1471            (0..self.window.next_frame.deferred_draws.len()).collect::<SmallVec<[_; 8]>>();
1472        sorted_deferred_draws.sort_by_key(|ix| self.window.next_frame.deferred_draws[*ix].priority);
1473        self.prepaint_deferred_draws(&sorted_deferred_draws);
1474
1475        let mut prompt_element = None;
1476        let mut active_drag_element = None;
1477        let mut tooltip_element = None;
1478        if let Some(prompt) = self.window.prompt.take() {
1479            let mut element = prompt.view.any_view().into_any();
1480            element.prepaint_as_root(Point::default(), self.window.viewport_size.into(), self);
1481            prompt_element = Some(element);
1482            self.window.prompt = Some(prompt);
1483        } else if let Some(active_drag) = self.app.active_drag.take() {
1484            let mut element = active_drag.view.clone().into_any();
1485            let offset = self.mouse_position() - active_drag.cursor_offset;
1486            element.prepaint_as_root(offset, AvailableSpace::min_size(), self);
1487            active_drag_element = Some(element);
1488            self.app.active_drag = Some(active_drag);
1489        } else {
1490            tooltip_element = self.prepaint_tooltip();
1491        }
1492
1493        self.window.mouse_hit_test = self.window.next_frame.hit_test(self.window.mouse_position);
1494
1495        // Now actually paint the elements.
1496        self.window.draw_phase = DrawPhase::Paint;
1497        root_element.paint(self);
1498
1499        self.paint_deferred_draws(&sorted_deferred_draws);
1500
1501        if let Some(mut prompt_element) = prompt_element {
1502            prompt_element.paint(self)
1503        } else if let Some(mut drag_element) = active_drag_element {
1504            drag_element.paint(self);
1505        } else if let Some(mut tooltip_element) = tooltip_element {
1506            tooltip_element.paint(self);
1507        }
1508    }
1509
1510    fn prepaint_tooltip(&mut self) -> Option<AnyElement> {
1511        let tooltip_request = self.window.next_frame.tooltip_requests.last().cloned()?;
1512        let tooltip_request = tooltip_request.unwrap();
1513        let mut element = tooltip_request.tooltip.view.clone().into_any();
1514        let mouse_position = tooltip_request.tooltip.mouse_position;
1515        let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self);
1516
1517        let mut tooltip_bounds = Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
1518        let window_bounds = Bounds {
1519            origin: Point::default(),
1520            size: self.viewport_size(),
1521        };
1522
1523        if tooltip_bounds.right() > window_bounds.right() {
1524            let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
1525            if new_x >= Pixels::ZERO {
1526                tooltip_bounds.origin.x = new_x;
1527            } else {
1528                tooltip_bounds.origin.x = cmp::max(
1529                    Pixels::ZERO,
1530                    tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
1531                );
1532            }
1533        }
1534
1535        if tooltip_bounds.bottom() > window_bounds.bottom() {
1536            let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
1537            if new_y >= Pixels::ZERO {
1538                tooltip_bounds.origin.y = new_y;
1539            } else {
1540                tooltip_bounds.origin.y = cmp::max(
1541                    Pixels::ZERO,
1542                    tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
1543                );
1544            }
1545        }
1546
1547        self.with_absolute_element_offset(tooltip_bounds.origin, |cx| element.prepaint(cx));
1548
1549        self.window.tooltip_bounds = Some(TooltipBounds {
1550            id: tooltip_request.id,
1551            bounds: tooltip_bounds,
1552        });
1553        Some(element)
1554    }
1555
1556    fn prepaint_deferred_draws(&mut self, deferred_draw_indices: &[usize]) {
1557        assert_eq!(self.window.element_id_stack.len(), 0);
1558
1559        let mut deferred_draws = mem::take(&mut self.window.next_frame.deferred_draws);
1560        for deferred_draw_ix in deferred_draw_indices {
1561            let deferred_draw = &mut deferred_draws[*deferred_draw_ix];
1562            self.window
1563                .element_id_stack
1564                .clone_from(&deferred_draw.element_id_stack);
1565            self.window
1566                .text_style_stack
1567                .clone_from(&deferred_draw.text_style_stack);
1568            self.window
1569                .next_frame
1570                .dispatch_tree
1571                .set_active_node(deferred_draw.parent_node);
1572
1573            let prepaint_start = self.prepaint_index();
1574            if let Some(element) = deferred_draw.element.as_mut() {
1575                self.with_absolute_element_offset(deferred_draw.absolute_offset, |cx| {
1576                    element.prepaint(cx)
1577                });
1578            } else {
1579                self.reuse_prepaint(deferred_draw.prepaint_range.clone());
1580            }
1581            let prepaint_end = self.prepaint_index();
1582            deferred_draw.prepaint_range = prepaint_start..prepaint_end;
1583        }
1584        assert_eq!(
1585            self.window.next_frame.deferred_draws.len(),
1586            0,
1587            "cannot call defer_draw during deferred drawing"
1588        );
1589        self.window.next_frame.deferred_draws = deferred_draws;
1590        self.window.element_id_stack.clear();
1591        self.window.text_style_stack.clear();
1592    }
1593
1594    fn paint_deferred_draws(&mut self, deferred_draw_indices: &[usize]) {
1595        assert_eq!(self.window.element_id_stack.len(), 0);
1596
1597        let mut deferred_draws = mem::take(&mut self.window.next_frame.deferred_draws);
1598        for deferred_draw_ix in deferred_draw_indices {
1599            let mut deferred_draw = &mut deferred_draws[*deferred_draw_ix];
1600            self.window
1601                .element_id_stack
1602                .clone_from(&deferred_draw.element_id_stack);
1603            self.window
1604                .next_frame
1605                .dispatch_tree
1606                .set_active_node(deferred_draw.parent_node);
1607
1608            let paint_start = self.paint_index();
1609            if let Some(element) = deferred_draw.element.as_mut() {
1610                element.paint(self);
1611            } else {
1612                self.reuse_paint(deferred_draw.paint_range.clone());
1613            }
1614            let paint_end = self.paint_index();
1615            deferred_draw.paint_range = paint_start..paint_end;
1616        }
1617        self.window.next_frame.deferred_draws = deferred_draws;
1618        self.window.element_id_stack.clear();
1619    }
1620
1621    pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
1622        PrepaintStateIndex {
1623            hitboxes_index: self.window.next_frame.hitboxes.len(),
1624            tooltips_index: self.window.next_frame.tooltip_requests.len(),
1625            deferred_draws_index: self.window.next_frame.deferred_draws.len(),
1626            dispatch_tree_index: self.window.next_frame.dispatch_tree.len(),
1627            accessed_element_states_index: self.window.next_frame.accessed_element_states.len(),
1628            line_layout_index: self.window.text_system.layout_index(),
1629        }
1630    }
1631
1632    pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
1633        let window = &mut self.window;
1634        window.next_frame.hitboxes.extend(
1635            window.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
1636                .iter()
1637                .cloned(),
1638        );
1639        window.next_frame.tooltip_requests.extend(
1640            window.rendered_frame.tooltip_requests
1641                [range.start.tooltips_index..range.end.tooltips_index]
1642                .iter_mut()
1643                .map(|request| request.take()),
1644        );
1645        window.next_frame.accessed_element_states.extend(
1646            window.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
1647                ..range.end.accessed_element_states_index]
1648                .iter()
1649                .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
1650        );
1651        window
1652            .text_system
1653            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
1654
1655        let reused_subtree = window.next_frame.dispatch_tree.reuse_subtree(
1656            range.start.dispatch_tree_index..range.end.dispatch_tree_index,
1657            &mut window.rendered_frame.dispatch_tree,
1658        );
1659        window.next_frame.deferred_draws.extend(
1660            window.rendered_frame.deferred_draws
1661                [range.start.deferred_draws_index..range.end.deferred_draws_index]
1662                .iter()
1663                .map(|deferred_draw| DeferredDraw {
1664                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
1665                    element_id_stack: deferred_draw.element_id_stack.clone(),
1666                    text_style_stack: deferred_draw.text_style_stack.clone(),
1667                    priority: deferred_draw.priority,
1668                    element: None,
1669                    absolute_offset: deferred_draw.absolute_offset,
1670                    prepaint_range: deferred_draw.prepaint_range.clone(),
1671                    paint_range: deferred_draw.paint_range.clone(),
1672                }),
1673        );
1674    }
1675
1676    pub(crate) fn paint_index(&self) -> PaintIndex {
1677        PaintIndex {
1678            scene_index: self.window.next_frame.scene.len(),
1679            mouse_listeners_index: self.window.next_frame.mouse_listeners.len(),
1680            input_handlers_index: self.window.next_frame.input_handlers.len(),
1681            cursor_styles_index: self.window.next_frame.cursor_styles.len(),
1682            accessed_element_states_index: self.window.next_frame.accessed_element_states.len(),
1683            line_layout_index: self.window.text_system.layout_index(),
1684        }
1685    }
1686
1687    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
1688        let window = &mut self.window;
1689
1690        window.next_frame.cursor_styles.extend(
1691            window.rendered_frame.cursor_styles
1692                [range.start.cursor_styles_index..range.end.cursor_styles_index]
1693                .iter()
1694                .cloned(),
1695        );
1696        window.next_frame.input_handlers.extend(
1697            window.rendered_frame.input_handlers
1698                [range.start.input_handlers_index..range.end.input_handlers_index]
1699                .iter_mut()
1700                .map(|handler| handler.take()),
1701        );
1702        window.next_frame.mouse_listeners.extend(
1703            window.rendered_frame.mouse_listeners
1704                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
1705                .iter_mut()
1706                .map(|listener| listener.take()),
1707        );
1708        window.next_frame.accessed_element_states.extend(
1709            window.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
1710                ..range.end.accessed_element_states_index]
1711                .iter()
1712                .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
1713        );
1714        window
1715            .text_system
1716            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
1717        window.next_frame.scene.replay(
1718            range.start.scene_index..range.end.scene_index,
1719            &window.rendered_frame.scene,
1720        );
1721    }
1722
1723    /// Push a text style onto the stack, and call a function with that style active.
1724    /// Use [`AppContext::text_style`] to get the current, combined text style. This method
1725    /// should only be called as part of element drawing.
1726    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
1727    where
1728        F: FnOnce(&mut Self) -> R,
1729    {
1730        debug_assert!(
1731            matches!(
1732                self.window.draw_phase,
1733                DrawPhase::Prepaint | DrawPhase::Paint
1734            ),
1735            "this method can only be called during request_layout, prepaint, or paint"
1736        );
1737        if let Some(style) = style {
1738            self.window.text_style_stack.push(style);
1739            let result = f(self);
1740            self.window.text_style_stack.pop();
1741            result
1742        } else {
1743            f(self)
1744        }
1745    }
1746
1747    /// Updates the cursor style at the platform level. This method should only be called
1748    /// during the prepaint phase of element drawing.
1749    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
1750        debug_assert_eq!(
1751            self.window.draw_phase,
1752            DrawPhase::Paint,
1753            "this method can only be called during paint"
1754        );
1755        self.window
1756            .next_frame
1757            .cursor_styles
1758            .push(CursorStyleRequest {
1759                hitbox_id: hitbox.id,
1760                style,
1761            });
1762    }
1763
1764    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
1765    /// during the paint phase of element drawing.
1766    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
1767        debug_assert_eq!(
1768            self.window.draw_phase,
1769            DrawPhase::Prepaint,
1770            "this method can only be called during prepaint"
1771        );
1772        let id = TooltipId(post_inc(&mut self.window.next_tooltip_id.0));
1773        self.window
1774            .next_frame
1775            .tooltip_requests
1776            .push(Some(TooltipRequest { id, tooltip }));
1777        id
1778    }
1779
1780    /// Invoke the given function with the given content mask after intersecting it
1781    /// with the current mask. This method should only be called during element drawing.
1782    pub fn with_content_mask<R>(
1783        &mut self,
1784        mask: Option<ContentMask<Pixels>>,
1785        f: impl FnOnce(&mut Self) -> R,
1786    ) -> R {
1787        debug_assert!(
1788            matches!(
1789                self.window.draw_phase,
1790                DrawPhase::Prepaint | DrawPhase::Paint
1791            ),
1792            "this method can only be called during request_layout, prepaint, or paint"
1793        );
1794        if let Some(mask) = mask {
1795            let mask = mask.intersect(&self.content_mask());
1796            self.window_mut().content_mask_stack.push(mask);
1797            let result = f(self);
1798            self.window_mut().content_mask_stack.pop();
1799            result
1800        } else {
1801            f(self)
1802        }
1803    }
1804
1805    /// Updates the global element offset relative to the current offset. This is used to implement
1806    /// scrolling. This method should only be called during the prepaint phase of element drawing.
1807    pub fn with_element_offset<R>(
1808        &mut self,
1809        offset: Point<Pixels>,
1810        f: impl FnOnce(&mut Self) -> R,
1811    ) -> R {
1812        debug_assert_eq!(
1813            self.window.draw_phase,
1814            DrawPhase::Prepaint,
1815            "this method can only be called during request_layout, or prepaint"
1816        );
1817
1818        if offset.is_zero() {
1819            return f(self);
1820        };
1821
1822        let abs_offset = self.element_offset() + offset;
1823        self.with_absolute_element_offset(abs_offset, f)
1824    }
1825
1826    /// Updates the global element offset based on the given offset. This is used to implement
1827    /// drag handles and other manual painting of elements. This method should only be called during
1828    /// the prepaint phase of element drawing.
1829    pub fn with_absolute_element_offset<R>(
1830        &mut self,
1831        offset: Point<Pixels>,
1832        f: impl FnOnce(&mut Self) -> R,
1833    ) -> R {
1834        debug_assert_eq!(
1835            self.window.draw_phase,
1836            DrawPhase::Prepaint,
1837            "this method can only be called during request_layout, or prepaint"
1838        );
1839        self.window_mut().element_offset_stack.push(offset);
1840        let result = f(self);
1841        self.window_mut().element_offset_stack.pop();
1842        result
1843    }
1844
1845    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
1846    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
1847    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
1848    /// element offset and prepaint again. See [`List`] for an example. This method should only be
1849    /// called during the prepaint phase of element drawing.
1850    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
1851        debug_assert_eq!(
1852            self.window.draw_phase,
1853            DrawPhase::Prepaint,
1854            "this method can only be called during prepaint"
1855        );
1856        let index = self.prepaint_index();
1857        let result = f(self);
1858        if result.is_err() {
1859            self.window
1860                .next_frame
1861                .hitboxes
1862                .truncate(index.hitboxes_index);
1863            self.window
1864                .next_frame
1865                .tooltip_requests
1866                .truncate(index.tooltips_index);
1867            self.window
1868                .next_frame
1869                .deferred_draws
1870                .truncate(index.deferred_draws_index);
1871            self.window
1872                .next_frame
1873                .dispatch_tree
1874                .truncate(index.dispatch_tree_index);
1875            self.window
1876                .next_frame
1877                .accessed_element_states
1878                .truncate(index.accessed_element_states_index);
1879            self.window
1880                .text_system
1881                .truncate_layouts(index.line_layout_index);
1882        }
1883        result
1884    }
1885
1886    /// When you call this method during [`prepaint`], containing elements will attempt to
1887    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
1888    /// [`prepaint`] again with a new set of bounds. See [`List`] for an example of an element
1889    /// that supports this method being called on the elements it contains. This method should only be
1890    /// called during the prepaint phase of element drawing.
1891    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
1892        debug_assert_eq!(
1893            self.window.draw_phase,
1894            DrawPhase::Prepaint,
1895            "this method can only be called during prepaint"
1896        );
1897        self.window.requested_autoscroll = Some(bounds);
1898    }
1899
1900    /// This method can be called from a containing element such as [`List`] to support the autoscroll behavior
1901    /// described in [`request_autoscroll`].
1902    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
1903        debug_assert_eq!(
1904            self.window.draw_phase,
1905            DrawPhase::Prepaint,
1906            "this method can only be called during prepaint"
1907        );
1908        self.window.requested_autoscroll.take()
1909    }
1910
1911    /// Remove an asset from GPUI's cache
1912    pub fn remove_cached_asset<A: Asset + 'static>(
1913        &mut self,
1914        source: &A::Source,
1915    ) -> Option<A::Output> {
1916        self.asset_cache.remove::<A>(source)
1917    }
1918
1919    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1920    /// Your view will be re-drawn once the asset has finished loading.
1921    ///
1922    /// Note that the multiple calls to this method will only result in one `Asset::load` call.
1923    /// The results of that call will be cached, and returned on subsequent uses of this API.
1924    ///
1925    /// Use [Self::remove_cached_asset] to reload your asset.
1926    pub fn use_cached_asset<A: Asset + 'static>(
1927        &mut self,
1928        source: &A::Source,
1929    ) -> Option<A::Output> {
1930        self.asset_cache.get::<A>(source).or_else(|| {
1931            if let Some(asset) = self.use_asset::<A>(source) {
1932                self.asset_cache
1933                    .insert::<A>(source.to_owned(), asset.clone());
1934                Some(asset)
1935            } else {
1936                None
1937            }
1938        })
1939    }
1940
1941    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1942    /// Your view will be re-drawn once the asset has finished loading.
1943    ///
1944    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
1945    /// time.
1946    ///
1947    /// This asset will not be cached by default, see [Self::use_cached_asset]
1948    pub fn use_asset<A: Asset + 'static>(&mut self, source: &A::Source) -> Option<A::Output> {
1949        let asset_id = (TypeId::of::<A>(), hash(source));
1950        let mut is_first = false;
1951        let task = self
1952            .loading_assets
1953            .remove(&asset_id)
1954            .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
1955            .unwrap_or_else(|| {
1956                is_first = true;
1957                let future = A::load(source.clone(), self);
1958                let task = self.background_executor().spawn(future).shared();
1959                task
1960            });
1961
1962        task.clone().now_or_never().or_else(|| {
1963            if is_first {
1964                let parent_id = self.parent_view_id();
1965                self.spawn({
1966                    let task = task.clone();
1967                    |mut cx| async move {
1968                        task.await;
1969
1970                        cx.on_next_frame(move |cx| {
1971                            if let Some(parent_id) = parent_id {
1972                                cx.notify(parent_id)
1973                            } else {
1974                                cx.refresh()
1975                            }
1976                        });
1977                    }
1978                })
1979                .detach();
1980            }
1981
1982            self.loading_assets.insert(asset_id, Box::new(task));
1983
1984            None
1985        })
1986    }
1987
1988    /// Obtain the current element offset. This method should only be called during the
1989    /// prepaint phase of element drawing.
1990    pub fn element_offset(&self) -> Point<Pixels> {
1991        debug_assert_eq!(
1992            self.window.draw_phase,
1993            DrawPhase::Prepaint,
1994            "this method can only be called during prepaint"
1995        );
1996        self.window()
1997            .element_offset_stack
1998            .last()
1999            .copied()
2000            .unwrap_or_default()
2001    }
2002
2003    /// Obtain the current content mask. This method should only be called during element drawing.
2004    pub fn content_mask(&self) -> ContentMask<Pixels> {
2005        debug_assert!(
2006            matches!(
2007                self.window.draw_phase,
2008                DrawPhase::Prepaint | DrawPhase::Paint
2009            ),
2010            "this method can only be called during prepaint, or paint"
2011        );
2012        self.window()
2013            .content_mask_stack
2014            .last()
2015            .cloned()
2016            .unwrap_or_else(|| ContentMask {
2017                bounds: Bounds {
2018                    origin: Point::default(),
2019                    size: self.window().viewport_size,
2020                },
2021            })
2022    }
2023
2024    /// Provide elements in the called function with a new namespace in which their identiers must be unique.
2025    /// This can be used within a custom element to distinguish multiple sets of child elements.
2026    pub fn with_element_namespace<R>(
2027        &mut self,
2028        element_id: impl Into<ElementId>,
2029        f: impl FnOnce(&mut Self) -> R,
2030    ) -> R {
2031        self.window.element_id_stack.push(element_id.into());
2032        let result = f(self);
2033        self.window.element_id_stack.pop();
2034        result
2035    }
2036
2037    /// Updates or initializes state for an element with the given id that lives across multiple
2038    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
2039    /// to the given closure. The state returned by the closure will be stored so it can be referenced
2040    /// when drawing the next frame. This method should only be called as part of element drawing.
2041    pub fn with_element_state<S, R>(
2042        &mut self,
2043        global_id: &GlobalElementId,
2044        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2045    ) -> R
2046    where
2047        S: 'static,
2048    {
2049        debug_assert!(
2050            matches!(
2051                self.window.draw_phase,
2052                DrawPhase::Prepaint | DrawPhase::Paint
2053            ),
2054            "this method can only be called during request_layout, prepaint, or paint"
2055        );
2056
2057        let key = (GlobalElementId(global_id.0.clone()), TypeId::of::<S>());
2058        self.window
2059            .next_frame
2060            .accessed_element_states
2061            .push((GlobalElementId(key.0.clone()), TypeId::of::<S>()));
2062
2063        if let Some(any) = self
2064            .window
2065            .next_frame
2066            .element_states
2067            .remove(&key)
2068            .or_else(|| self.window.rendered_frame.element_states.remove(&key))
2069        {
2070            let ElementStateBox {
2071                inner,
2072                #[cfg(debug_assertions)]
2073                type_name,
2074            } = any;
2075            // Using the extra inner option to avoid needing to reallocate a new box.
2076            let mut state_box = inner
2077                .downcast::<Option<S>>()
2078                .map_err(|_| {
2079                    #[cfg(debug_assertions)]
2080                    {
2081                        anyhow::anyhow!(
2082                            "invalid element state type for id, requested {:?}, actual: {:?}",
2083                            std::any::type_name::<S>(),
2084                            type_name
2085                        )
2086                    }
2087
2088                    #[cfg(not(debug_assertions))]
2089                    {
2090                        anyhow::anyhow!(
2091                            "invalid element state type for id, requested {:?}",
2092                            std::any::type_name::<S>(),
2093                        )
2094                    }
2095                })
2096                .unwrap();
2097
2098            let state = state_box.take().expect(
2099                "reentrant call to with_element_state for the same state type and element id",
2100            );
2101            let (result, state) = f(Some(state), self);
2102            state_box.replace(state);
2103            self.window.next_frame.element_states.insert(
2104                key,
2105                ElementStateBox {
2106                    inner: state_box,
2107                    #[cfg(debug_assertions)]
2108                    type_name,
2109                },
2110            );
2111            result
2112        } else {
2113            let (result, state) = f(None, self);
2114            self.window.next_frame.element_states.insert(
2115                key,
2116                ElementStateBox {
2117                    inner: Box::new(Some(state)),
2118                    #[cfg(debug_assertions)]
2119                    type_name: std::any::type_name::<S>(),
2120                },
2121            );
2122            result
2123        }
2124    }
2125
2126    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
2127    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
2128    /// when the element is guaranteed to have an id.
2129    pub fn with_optional_element_state<S, R>(
2130        &mut self,
2131        global_id: Option<&GlobalElementId>,
2132        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
2133    ) -> R
2134    where
2135        S: 'static,
2136    {
2137        debug_assert!(
2138            matches!(
2139                self.window.draw_phase,
2140                DrawPhase::Prepaint | DrawPhase::Paint
2141            ),
2142            "this method can only be called during request_layout, prepaint, or paint"
2143        );
2144
2145        if let Some(global_id) = global_id {
2146            self.with_element_state(global_id, |state, cx| {
2147                let (result, state) = f(Some(state), cx);
2148                let state =
2149                    state.expect("you must return some state when you pass some element id");
2150                (result, state)
2151            })
2152        } else {
2153            let (result, state) = f(None, self);
2154            debug_assert!(
2155                state.is_none(),
2156                "you must not return an element state when passing None for the global id"
2157            );
2158            result
2159        }
2160    }
2161
2162    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
2163    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
2164    /// with higher values being drawn on top.
2165    ///
2166    /// This method should only be called as part of the prepaint phase of element drawing.
2167    pub fn defer_draw(
2168        &mut self,
2169        element: AnyElement,
2170        absolute_offset: Point<Pixels>,
2171        priority: usize,
2172    ) {
2173        let window = &mut self.window;
2174        debug_assert_eq!(
2175            window.draw_phase,
2176            DrawPhase::Prepaint,
2177            "this method can only be called during request_layout or prepaint"
2178        );
2179        let parent_node = window.next_frame.dispatch_tree.active_node_id().unwrap();
2180        window.next_frame.deferred_draws.push(DeferredDraw {
2181            parent_node,
2182            element_id_stack: window.element_id_stack.clone(),
2183            text_style_stack: window.text_style_stack.clone(),
2184            priority,
2185            element: Some(element),
2186            absolute_offset,
2187            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
2188            paint_range: PaintIndex::default()..PaintIndex::default(),
2189        });
2190    }
2191
2192    /// Creates a new painting layer for the specified bounds. A "layer" is a batch
2193    /// of geometry that are non-overlapping and have the same draw order. This is typically used
2194    /// for performance reasons.
2195    ///
2196    /// This method should only be called as part of the paint phase of element drawing.
2197    pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
2198        debug_assert_eq!(
2199            self.window.draw_phase,
2200            DrawPhase::Paint,
2201            "this method can only be called during paint"
2202        );
2203
2204        let scale_factor = self.scale_factor();
2205        let content_mask = self.content_mask();
2206        let clipped_bounds = bounds.intersect(&content_mask.bounds);
2207        if !clipped_bounds.is_empty() {
2208            self.window
2209                .next_frame
2210                .scene
2211                .push_layer(clipped_bounds.scale(scale_factor));
2212        }
2213
2214        let result = f(self);
2215
2216        if !clipped_bounds.is_empty() {
2217            self.window.next_frame.scene.pop_layer();
2218        }
2219
2220        result
2221    }
2222
2223    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
2224    ///
2225    /// This method should only be called as part of the paint phase of element drawing.
2226    pub fn paint_shadows(
2227        &mut self,
2228        bounds: Bounds<Pixels>,
2229        corner_radii: Corners<Pixels>,
2230        shadows: &[BoxShadow],
2231    ) {
2232        debug_assert_eq!(
2233            self.window.draw_phase,
2234            DrawPhase::Paint,
2235            "this method can only be called during paint"
2236        );
2237
2238        let scale_factor = self.scale_factor();
2239        let content_mask = self.content_mask();
2240        for shadow in shadows {
2241            let mut shadow_bounds = bounds;
2242            shadow_bounds.origin += shadow.offset;
2243            shadow_bounds.dilate(shadow.spread_radius);
2244            self.window.next_frame.scene.insert_primitive(Shadow {
2245                order: 0,
2246                blur_radius: shadow.blur_radius.scale(scale_factor),
2247                bounds: shadow_bounds.scale(scale_factor),
2248                content_mask: content_mask.scale(scale_factor),
2249                corner_radii: corner_radii.scale(scale_factor),
2250                color: shadow.color,
2251            });
2252        }
2253    }
2254
2255    /// Paint one or more quads into the scene for the next frame at the current stacking context.
2256    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
2257    /// see [`fill`](crate::fill), [`outline`](crate::outline), and [`quad`](crate::quad) to construct this type.
2258    ///
2259    /// This method should only be called as part of the paint phase of element drawing.
2260    pub fn paint_quad(&mut self, quad: PaintQuad) {
2261        debug_assert_eq!(
2262            self.window.draw_phase,
2263            DrawPhase::Paint,
2264            "this method can only be called during paint"
2265        );
2266
2267        let scale_factor = self.scale_factor();
2268        let content_mask = self.content_mask();
2269        self.window.next_frame.scene.insert_primitive(Quad {
2270            order: 0,
2271            pad: 0,
2272            bounds: quad.bounds.scale(scale_factor),
2273            content_mask: content_mask.scale(scale_factor),
2274            background: quad.background,
2275            border_color: quad.border_color,
2276            corner_radii: quad.corner_radii.scale(scale_factor),
2277            border_widths: quad.border_widths.scale(scale_factor),
2278        });
2279    }
2280
2281    /// Paint the given `Path` into the scene for the next frame at the current z-index.
2282    ///
2283    /// This method should only be called as part of the paint phase of element drawing.
2284    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
2285        debug_assert_eq!(
2286            self.window.draw_phase,
2287            DrawPhase::Paint,
2288            "this method can only be called during paint"
2289        );
2290
2291        let scale_factor = self.scale_factor();
2292        let content_mask = self.content_mask();
2293        path.content_mask = content_mask;
2294        path.color = color.into();
2295        self.window
2296            .next_frame
2297            .scene
2298            .insert_primitive(path.scale(scale_factor));
2299    }
2300
2301    /// Paint an underline into the scene for the next frame at the current z-index.
2302    ///
2303    /// This method should only be called as part of the paint phase of element drawing.
2304    pub fn paint_underline(
2305        &mut self,
2306        origin: Point<Pixels>,
2307        width: Pixels,
2308        style: &UnderlineStyle,
2309    ) {
2310        debug_assert_eq!(
2311            self.window.draw_phase,
2312            DrawPhase::Paint,
2313            "this method can only be called during paint"
2314        );
2315
2316        let scale_factor = self.scale_factor();
2317        let height = if style.wavy {
2318            style.thickness * 3.
2319        } else {
2320            style.thickness
2321        };
2322        let bounds = Bounds {
2323            origin,
2324            size: size(width, height),
2325        };
2326        let content_mask = self.content_mask();
2327
2328        self.window.next_frame.scene.insert_primitive(Underline {
2329            order: 0,
2330            pad: 0,
2331            bounds: bounds.scale(scale_factor),
2332            content_mask: content_mask.scale(scale_factor),
2333            color: style.color.unwrap_or_default(),
2334            thickness: style.thickness.scale(scale_factor),
2335            wavy: style.wavy,
2336        });
2337    }
2338
2339    /// Paint a strikethrough into the scene for the next frame at the current z-index.
2340    ///
2341    /// This method should only be called as part of the paint phase of element drawing.
2342    pub fn paint_strikethrough(
2343        &mut self,
2344        origin: Point<Pixels>,
2345        width: Pixels,
2346        style: &StrikethroughStyle,
2347    ) {
2348        debug_assert_eq!(
2349            self.window.draw_phase,
2350            DrawPhase::Paint,
2351            "this method can only be called during paint"
2352        );
2353
2354        let scale_factor = self.scale_factor();
2355        let height = style.thickness;
2356        let bounds = Bounds {
2357            origin,
2358            size: size(width, height),
2359        };
2360        let content_mask = self.content_mask();
2361
2362        self.window.next_frame.scene.insert_primitive(Underline {
2363            order: 0,
2364            pad: 0,
2365            bounds: bounds.scale(scale_factor),
2366            content_mask: content_mask.scale(scale_factor),
2367            thickness: style.thickness.scale(scale_factor),
2368            color: style.color.unwrap_or_default(),
2369            wavy: false,
2370        });
2371    }
2372
2373    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
2374    ///
2375    /// The y component of the origin is the baseline of the glyph.
2376    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2377    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2378    /// This method is only useful if you need to paint a single glyph that has already been shaped.
2379    ///
2380    /// This method should only be called as part of the paint phase of element drawing.
2381    pub fn paint_glyph(
2382        &mut self,
2383        origin: Point<Pixels>,
2384        font_id: FontId,
2385        glyph_id: GlyphId,
2386        font_size: Pixels,
2387        color: Hsla,
2388    ) -> Result<()> {
2389        debug_assert_eq!(
2390            self.window.draw_phase,
2391            DrawPhase::Paint,
2392            "this method can only be called during paint"
2393        );
2394
2395        let scale_factor = self.scale_factor();
2396        let glyph_origin = origin.scale(scale_factor);
2397        let subpixel_variant = Point {
2398            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2399            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2400        };
2401        let params = RenderGlyphParams {
2402            font_id,
2403            glyph_id,
2404            font_size,
2405            subpixel_variant,
2406            scale_factor,
2407            is_emoji: false,
2408        };
2409
2410        let raster_bounds = self.text_system().raster_bounds(&params)?;
2411        if !raster_bounds.is_zero() {
2412            let tile = self
2413                .window
2414                .sprite_atlas
2415                .get_or_insert_with(&params.clone().into(), &mut || {
2416                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
2417                    Ok(Some((size, Cow::Owned(bytes))))
2418                })?
2419                .expect("Callback above only errors or returns Some");
2420            let bounds = Bounds {
2421                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2422                size: tile.bounds.size.map(Into::into),
2423            };
2424            let content_mask = self.content_mask().scale(scale_factor);
2425            self.window
2426                .next_frame
2427                .scene
2428                .insert_primitive(MonochromeSprite {
2429                    order: 0,
2430                    pad: 0,
2431                    bounds,
2432                    content_mask,
2433                    color,
2434                    tile,
2435                    transformation: TransformationMatrix::unit(),
2436                });
2437        }
2438        Ok(())
2439    }
2440
2441    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
2442    ///
2443    /// The y component of the origin is the baseline of the glyph.
2444    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2445    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2446    /// This method is only useful if you need to paint a single emoji that has already been shaped.
2447    ///
2448    /// This method should only be called as part of the paint phase of element drawing.
2449    pub fn paint_emoji(
2450        &mut self,
2451        origin: Point<Pixels>,
2452        font_id: FontId,
2453        glyph_id: GlyphId,
2454        font_size: Pixels,
2455    ) -> Result<()> {
2456        debug_assert_eq!(
2457            self.window.draw_phase,
2458            DrawPhase::Paint,
2459            "this method can only be called during paint"
2460        );
2461
2462        let scale_factor = self.scale_factor();
2463        let glyph_origin = origin.scale(scale_factor);
2464        let params = RenderGlyphParams {
2465            font_id,
2466            glyph_id,
2467            font_size,
2468            // We don't render emojis with subpixel variants.
2469            subpixel_variant: Default::default(),
2470            scale_factor,
2471            is_emoji: true,
2472        };
2473
2474        let raster_bounds = self.text_system().raster_bounds(&params)?;
2475        if !raster_bounds.is_zero() {
2476            let tile = self
2477                .window
2478                .sprite_atlas
2479                .get_or_insert_with(&params.clone().into(), &mut || {
2480                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
2481                    Ok(Some((size, Cow::Owned(bytes))))
2482                })?
2483                .expect("Callback above only errors or returns Some");
2484
2485            let bounds = Bounds {
2486                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2487                size: tile.bounds.size.map(Into::into),
2488            };
2489            let content_mask = self.content_mask().scale(scale_factor);
2490
2491            self.window
2492                .next_frame
2493                .scene
2494                .insert_primitive(PolychromeSprite {
2495                    order: 0,
2496                    grayscale: false,
2497                    bounds,
2498                    corner_radii: Default::default(),
2499                    content_mask,
2500                    tile,
2501                });
2502        }
2503        Ok(())
2504    }
2505
2506    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
2507    ///
2508    /// This method should only be called as part of the paint phase of element drawing.
2509    pub fn paint_svg(
2510        &mut self,
2511        bounds: Bounds<Pixels>,
2512        path: SharedString,
2513        transformation: TransformationMatrix,
2514        color: Hsla,
2515    ) -> Result<()> {
2516        debug_assert_eq!(
2517            self.window.draw_phase,
2518            DrawPhase::Paint,
2519            "this method can only be called during paint"
2520        );
2521
2522        let scale_factor = self.scale_factor();
2523        let bounds = bounds.scale(scale_factor);
2524        // Render the SVG at twice the size to get a higher quality result.
2525        let params = RenderSvgParams {
2526            path,
2527            size: bounds
2528                .size
2529                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
2530        };
2531
2532        let Some(tile) =
2533            self.window
2534                .sprite_atlas
2535                .get_or_insert_with(&params.clone().into(), &mut || {
2536                    let Some(bytes) = self.svg_renderer.render(&params)? else {
2537                        return Ok(None);
2538                    };
2539                    Ok(Some((params.size, Cow::Owned(bytes))))
2540                })?
2541        else {
2542            return Ok(());
2543        };
2544        let content_mask = self.content_mask().scale(scale_factor);
2545
2546        self.window
2547            .next_frame
2548            .scene
2549            .insert_primitive(MonochromeSprite {
2550                order: 0,
2551                pad: 0,
2552                bounds,
2553                content_mask,
2554                color,
2555                tile,
2556                transformation,
2557            });
2558
2559        Ok(())
2560    }
2561
2562    /// Paint an image into the scene for the next frame at the current z-index.
2563    ///
2564    /// This method should only be called as part of the paint phase of element drawing.
2565    pub fn paint_image(
2566        &mut self,
2567        bounds: Bounds<Pixels>,
2568        corner_radii: Corners<Pixels>,
2569        data: Arc<ImageData>,
2570        grayscale: bool,
2571    ) -> Result<()> {
2572        debug_assert_eq!(
2573            self.window.draw_phase,
2574            DrawPhase::Paint,
2575            "this method can only be called during paint"
2576        );
2577
2578        let scale_factor = self.scale_factor();
2579        let bounds = bounds.scale(scale_factor);
2580        let params = RenderImageParams { image_id: data.id };
2581
2582        let tile = self
2583            .window
2584            .sprite_atlas
2585            .get_or_insert_with(&params.clone().into(), &mut || {
2586                Ok(Some((data.size(), Cow::Borrowed(data.as_bytes()))))
2587            })?
2588            .expect("Callback above only returns Some");
2589        let content_mask = self.content_mask().scale(scale_factor);
2590        let corner_radii = corner_radii.scale(scale_factor);
2591
2592        self.window
2593            .next_frame
2594            .scene
2595            .insert_primitive(PolychromeSprite {
2596                order: 0,
2597                grayscale,
2598                bounds,
2599                content_mask,
2600                corner_radii,
2601                tile,
2602            });
2603        Ok(())
2604    }
2605
2606    /// Paint a surface into the scene for the next frame at the current z-index.
2607    ///
2608    /// This method should only be called as part of the paint phase of element drawing.
2609    #[cfg(target_os = "macos")]
2610    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
2611        debug_assert_eq!(
2612            self.window.draw_phase,
2613            DrawPhase::Paint,
2614            "this method can only be called during paint"
2615        );
2616
2617        let scale_factor = self.scale_factor();
2618        let bounds = bounds.scale(scale_factor);
2619        let content_mask = self.content_mask().scale(scale_factor);
2620        self.window
2621            .next_frame
2622            .scene
2623            .insert_primitive(crate::Surface {
2624                order: 0,
2625                bounds,
2626                content_mask,
2627                image_buffer,
2628            });
2629    }
2630
2631    #[must_use]
2632    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
2633    /// layout is being requested, along with the layout ids of any children. This method is called during
2634    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
2635    ///
2636    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2637    pub fn request_layout(
2638        &mut self,
2639        style: Style,
2640        children: impl IntoIterator<Item = LayoutId>,
2641    ) -> LayoutId {
2642        debug_assert_eq!(
2643            self.window.draw_phase,
2644            DrawPhase::Prepaint,
2645            "this method can only be called during request_layout, or prepaint"
2646        );
2647
2648        self.app.layout_id_buffer.clear();
2649        self.app.layout_id_buffer.extend(children);
2650        let rem_size = self.rem_size();
2651
2652        self.window.layout_engine.as_mut().unwrap().request_layout(
2653            style,
2654            rem_size,
2655            &self.app.layout_id_buffer,
2656        )
2657    }
2658
2659    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
2660    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
2661    /// determine the element's size. One place this is used internally is when measuring text.
2662    ///
2663    /// The given closure is invoked at layout time with the known dimensions and available space and
2664    /// returns a `Size`.
2665    ///
2666    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2667    pub fn request_measured_layout<
2668        F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
2669            + 'static,
2670    >(
2671        &mut self,
2672        style: Style,
2673        measure: F,
2674    ) -> LayoutId {
2675        debug_assert_eq!(
2676            self.window.draw_phase,
2677            DrawPhase::Prepaint,
2678            "this method can only be called during request_layout, or prepaint"
2679        );
2680
2681        let rem_size = self.rem_size();
2682        self.window
2683            .layout_engine
2684            .as_mut()
2685            .unwrap()
2686            .request_measured_layout(style, rem_size, measure)
2687    }
2688
2689    /// Compute the layout for the given id within the given available space.
2690    /// This method is called for its side effect, typically by the framework prior to painting.
2691    /// After calling it, you can request the bounds of the given layout node id or any descendant.
2692    ///
2693    /// This method should only be called as part of the prepaint phase of element drawing.
2694    pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
2695        debug_assert_eq!(
2696            self.window.draw_phase,
2697            DrawPhase::Prepaint,
2698            "this method can only be called during request_layout, or prepaint"
2699        );
2700
2701        let mut layout_engine = self.window.layout_engine.take().unwrap();
2702        layout_engine.compute_layout(layout_id, available_space, self);
2703        self.window.layout_engine = Some(layout_engine);
2704    }
2705
2706    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
2707    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
2708    ///
2709    /// This method should only be called as part of element drawing.
2710    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
2711        debug_assert_eq!(
2712            self.window.draw_phase,
2713            DrawPhase::Prepaint,
2714            "this method can only be called during request_layout, prepaint, or paint"
2715        );
2716
2717        let mut bounds = self
2718            .window
2719            .layout_engine
2720            .as_mut()
2721            .unwrap()
2722            .layout_bounds(layout_id)
2723            .map(Into::into);
2724        bounds.origin += self.element_offset();
2725        bounds
2726    }
2727
2728    /// This method should be called during `prepaint`. You can use
2729    /// the returned [Hitbox] during `paint` or in an event handler
2730    /// to determine whether the inserted hitbox was the topmost.
2731    ///
2732    /// This method should only be called as part of the prepaint phase of element drawing.
2733    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, opaque: bool) -> Hitbox {
2734        debug_assert_eq!(
2735            self.window.draw_phase,
2736            DrawPhase::Prepaint,
2737            "this method can only be called during prepaint"
2738        );
2739
2740        let content_mask = self.content_mask();
2741        let window = &mut self.window;
2742        let id = window.next_hitbox_id;
2743        window.next_hitbox_id.0 += 1;
2744        let hitbox = Hitbox {
2745            id,
2746            bounds,
2747            content_mask,
2748            opaque,
2749        };
2750        window.next_frame.hitboxes.push(hitbox.clone());
2751        hitbox
2752    }
2753
2754    /// Sets the key context for the current element. This context will be used to translate
2755    /// keybindings into actions.
2756    ///
2757    /// This method should only be called as part of the paint phase of element drawing.
2758    pub fn set_key_context(&mut self, context: KeyContext) {
2759        debug_assert_eq!(
2760            self.window.draw_phase,
2761            DrawPhase::Paint,
2762            "this method can only be called during paint"
2763        );
2764        self.window
2765            .next_frame
2766            .dispatch_tree
2767            .set_key_context(context);
2768    }
2769
2770    /// Sets the focus handle for the current element. This handle will be used to manage focus state
2771    /// and keyboard event dispatch for the element.
2772    ///
2773    /// This method should only be called as part of the paint phase of element drawing.
2774    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle) {
2775        debug_assert_eq!(
2776            self.window.draw_phase,
2777            DrawPhase::Paint,
2778            "this method can only be called during paint"
2779        );
2780        self.window
2781            .next_frame
2782            .dispatch_tree
2783            .set_focus_id(focus_handle.id);
2784    }
2785
2786    /// Sets the view id for the current element, which will be used to manage view caching.
2787    ///
2788    /// This method should only be called as part of element prepaint. We plan on removing this
2789    /// method eventually when we solve some issues that require us to construct editor elements
2790    /// directly instead of always using editors via views.
2791    pub fn set_view_id(&mut self, view_id: EntityId) {
2792        debug_assert_eq!(
2793            self.window.draw_phase,
2794            DrawPhase::Prepaint,
2795            "this method can only be called during prepaint"
2796        );
2797        self.window.next_frame.dispatch_tree.set_view_id(view_id);
2798    }
2799
2800    /// Get the last view id for the current element
2801    pub fn parent_view_id(&mut self) -> Option<EntityId> {
2802        self.window.next_frame.dispatch_tree.parent_view_id()
2803    }
2804
2805    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
2806    /// platform to receive textual input with proper integration with concerns such
2807    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
2808    /// rendered.
2809    ///
2810    /// This method should only be called as part of the paint phase of element drawing.
2811    ///
2812    /// [element_input_handler]: crate::ElementInputHandler
2813    pub fn handle_input(&mut self, focus_handle: &FocusHandle, input_handler: impl InputHandler) {
2814        debug_assert_eq!(
2815            self.window.draw_phase,
2816            DrawPhase::Paint,
2817            "this method can only be called during paint"
2818        );
2819
2820        if focus_handle.is_focused(self) {
2821            let cx = self.to_async();
2822            self.window
2823                .next_frame
2824                .input_handlers
2825                .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
2826        }
2827    }
2828
2829    /// Register a mouse event listener on the window for the next frame. The type of event
2830    /// is determined by the first parameter of the given listener. When the next frame is rendered
2831    /// the listener will be cleared.
2832    ///
2833    /// This method should only be called as part of the paint phase of element drawing.
2834    pub fn on_mouse_event<Event: MouseEvent>(
2835        &mut self,
2836        mut handler: impl FnMut(&Event, DispatchPhase, &mut WindowContext) + 'static,
2837    ) {
2838        debug_assert_eq!(
2839            self.window.draw_phase,
2840            DrawPhase::Paint,
2841            "this method can only be called during paint"
2842        );
2843
2844        self.window.next_frame.mouse_listeners.push(Some(Box::new(
2845            move |event: &dyn Any, phase: DispatchPhase, cx: &mut WindowContext<'_>| {
2846                if let Some(event) = event.downcast_ref() {
2847                    handler(event, phase, cx)
2848                }
2849            },
2850        )));
2851    }
2852
2853    /// Register a key event listener on the window for the next frame. The type of event
2854    /// is determined by the first parameter of the given listener. When the next frame is rendered
2855    /// the listener will be cleared.
2856    ///
2857    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2858    /// a specific need to register a global listener.
2859    ///
2860    /// This method should only be called as part of the paint phase of element drawing.
2861    pub fn on_key_event<Event: KeyEvent>(
2862        &mut self,
2863        listener: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
2864    ) {
2865        debug_assert_eq!(
2866            self.window.draw_phase,
2867            DrawPhase::Paint,
2868            "this method can only be called during paint"
2869        );
2870
2871        self.window.next_frame.dispatch_tree.on_key_event(Rc::new(
2872            move |event: &dyn Any, phase, cx: &mut WindowContext<'_>| {
2873                if let Some(event) = event.downcast_ref::<Event>() {
2874                    listener(event, phase, cx)
2875                }
2876            },
2877        ));
2878    }
2879
2880    /// Register a modifiers changed event listener on the window for the next frame.
2881    ///
2882    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2883    /// a specific need to register a global listener.
2884    ///
2885    /// This method should only be called as part of the paint phase of element drawing.
2886    pub fn on_modifiers_changed(
2887        &mut self,
2888        listener: impl Fn(&ModifiersChangedEvent, &mut WindowContext) + 'static,
2889    ) {
2890        debug_assert_eq!(
2891            self.window.draw_phase,
2892            DrawPhase::Paint,
2893            "this method can only be called during paint"
2894        );
2895
2896        self.window
2897            .next_frame
2898            .dispatch_tree
2899            .on_modifiers_changed(Rc::new(
2900                move |event: &ModifiersChangedEvent, cx: &mut WindowContext<'_>| {
2901                    listener(event, cx)
2902                },
2903            ));
2904    }
2905
2906    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2907    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
2908    /// Returns a subscription and persists until the subscription is dropped.
2909    pub fn on_focus_in(
2910        &mut self,
2911        handle: &FocusHandle,
2912        mut listener: impl FnMut(&mut WindowContext) + 'static,
2913    ) -> Subscription {
2914        let focus_id = handle.id;
2915        let (subscription, activate) =
2916            self.window.new_focus_listener(Box::new(move |event, cx| {
2917                if event.is_focus_in(focus_id) {
2918                    listener(cx);
2919                }
2920                true
2921            }));
2922        self.app.defer(move |_| activate());
2923        subscription
2924    }
2925
2926    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2927    /// Returns a subscription and persists until the subscription is dropped.
2928    pub fn on_focus_out(
2929        &mut self,
2930        handle: &FocusHandle,
2931        mut listener: impl FnMut(FocusOutEvent, &mut WindowContext) + 'static,
2932    ) -> Subscription {
2933        let focus_id = handle.id;
2934        let (subscription, activate) =
2935            self.window.new_focus_listener(Box::new(move |event, cx| {
2936                if let Some(blurred_id) = event.previous_focus_path.last().copied() {
2937                    if event.is_focus_out(focus_id) {
2938                        let event = FocusOutEvent {
2939                            blurred: WeakFocusHandle {
2940                                id: blurred_id,
2941                                handles: Arc::downgrade(&cx.window.focus_handles),
2942                            },
2943                        };
2944                        listener(event, cx)
2945                    }
2946                }
2947                true
2948            }));
2949        self.app.defer(move |_| activate());
2950        subscription
2951    }
2952
2953    fn reset_cursor_style(&self) {
2954        // Set the cursor only if we're the active window.
2955        if self.is_window_active() {
2956            let style = self
2957                .window
2958                .rendered_frame
2959                .cursor_styles
2960                .iter()
2961                .rev()
2962                .find(|request| request.hitbox_id.is_hovered(self))
2963                .map(|request| request.style)
2964                .unwrap_or(CursorStyle::Arrow);
2965            self.platform.set_cursor_style(style);
2966        }
2967    }
2968
2969    /// Dispatch a given keystroke as though the user had typed it.
2970    /// You can create a keystroke with Keystroke::parse("").
2971    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke) -> bool {
2972        let keystroke = keystroke.with_simulated_ime();
2973        let result = self.dispatch_event(PlatformInput::KeyDown(KeyDownEvent {
2974            keystroke: keystroke.clone(),
2975            is_held: false,
2976        }));
2977        if !result.propagate {
2978            return true;
2979        }
2980
2981        if let Some(input) = keystroke.ime_key {
2982            if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
2983                input_handler.dispatch_input(&input, self);
2984                self.window.platform_window.set_input_handler(input_handler);
2985                return true;
2986            }
2987        }
2988
2989        false
2990    }
2991
2992    /// Represent this action as a key binding string, to display in the UI.
2993    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
2994        self.bindings_for_action(action)
2995            .into_iter()
2996            .next()
2997            .map(|binding| {
2998                binding
2999                    .keystrokes()
3000                    .iter()
3001                    .map(ToString::to_string)
3002                    .collect::<Vec<_>>()
3003                    .join(" ")
3004            })
3005            .unwrap_or_else(|| action.name().to_string())
3006    }
3007
3008    /// Dispatch a mouse or keyboard event on the window.
3009    #[profiling::function]
3010    pub fn dispatch_event(&mut self, event: PlatformInput) -> DispatchEventResult {
3011        self.window.last_input_timestamp.set(Instant::now());
3012        // Handlers may set this to false by calling `stop_propagation`.
3013        self.app.propagate_event = true;
3014        // Handlers may set this to true by calling `prevent_default`.
3015        self.window.default_prevented = false;
3016
3017        let event = match event {
3018            // Track the mouse position with our own state, since accessing the platform
3019            // API for the mouse position can only occur on the main thread.
3020            PlatformInput::MouseMove(mouse_move) => {
3021                self.window.mouse_position = mouse_move.position;
3022                self.window.modifiers = mouse_move.modifiers;
3023                PlatformInput::MouseMove(mouse_move)
3024            }
3025            PlatformInput::MouseDown(mouse_down) => {
3026                self.window.mouse_position = mouse_down.position;
3027                self.window.modifiers = mouse_down.modifiers;
3028                PlatformInput::MouseDown(mouse_down)
3029            }
3030            PlatformInput::MouseUp(mouse_up) => {
3031                self.window.mouse_position = mouse_up.position;
3032                self.window.modifiers = mouse_up.modifiers;
3033                PlatformInput::MouseUp(mouse_up)
3034            }
3035            PlatformInput::MouseExited(mouse_exited) => {
3036                self.window.modifiers = mouse_exited.modifiers;
3037                PlatformInput::MouseExited(mouse_exited)
3038            }
3039            PlatformInput::ModifiersChanged(modifiers_changed) => {
3040                self.window.modifiers = modifiers_changed.modifiers;
3041                PlatformInput::ModifiersChanged(modifiers_changed)
3042            }
3043            PlatformInput::ScrollWheel(scroll_wheel) => {
3044                self.window.mouse_position = scroll_wheel.position;
3045                self.window.modifiers = scroll_wheel.modifiers;
3046                PlatformInput::ScrollWheel(scroll_wheel)
3047            }
3048            // Translate dragging and dropping of external files from the operating system
3049            // to internal drag and drop events.
3050            PlatformInput::FileDrop(file_drop) => match file_drop {
3051                FileDropEvent::Entered { position, paths } => {
3052                    self.window.mouse_position = position;
3053                    if self.active_drag.is_none() {
3054                        self.active_drag = Some(AnyDrag {
3055                            value: Box::new(paths.clone()),
3056                            view: self.new_view(|_| paths).into(),
3057                            cursor_offset: position,
3058                        });
3059                    }
3060                    PlatformInput::MouseMove(MouseMoveEvent {
3061                        position,
3062                        pressed_button: Some(MouseButton::Left),
3063                        modifiers: Modifiers::default(),
3064                    })
3065                }
3066                FileDropEvent::Pending { position } => {
3067                    self.window.mouse_position = position;
3068                    PlatformInput::MouseMove(MouseMoveEvent {
3069                        position,
3070                        pressed_button: Some(MouseButton::Left),
3071                        modifiers: Modifiers::default(),
3072                    })
3073                }
3074                FileDropEvent::Submit { position } => {
3075                    self.activate(true);
3076                    self.window.mouse_position = position;
3077                    PlatformInput::MouseUp(MouseUpEvent {
3078                        button: MouseButton::Left,
3079                        position,
3080                        modifiers: Modifiers::default(),
3081                        click_count: 1,
3082                    })
3083                }
3084                FileDropEvent::Exited => {
3085                    self.active_drag.take();
3086                    PlatformInput::FileDrop(FileDropEvent::Exited)
3087                }
3088            },
3089            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
3090        };
3091
3092        if let Some(any_mouse_event) = event.mouse_event() {
3093            self.dispatch_mouse_event(any_mouse_event);
3094        } else if let Some(any_key_event) = event.keyboard_event() {
3095            self.dispatch_key_event(any_key_event);
3096        }
3097
3098        DispatchEventResult {
3099            propagate: self.app.propagate_event,
3100            default_prevented: self.window.default_prevented,
3101        }
3102    }
3103
3104    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
3105        let hit_test = self.window.rendered_frame.hit_test(self.mouse_position());
3106        if hit_test != self.window.mouse_hit_test {
3107            self.window.mouse_hit_test = hit_test;
3108            self.reset_cursor_style();
3109        }
3110
3111        let mut mouse_listeners = mem::take(&mut self.window.rendered_frame.mouse_listeners);
3112
3113        // Capture phase, events bubble from back to front. Handlers for this phase are used for
3114        // special purposes, such as detecting events outside of a given Bounds.
3115        for listener in &mut mouse_listeners {
3116            let listener = listener.as_mut().unwrap();
3117            listener(event, DispatchPhase::Capture, self);
3118            if !self.app.propagate_event {
3119                break;
3120            }
3121        }
3122
3123        // Bubble phase, where most normal handlers do their work.
3124        if self.app.propagate_event {
3125            for listener in mouse_listeners.iter_mut().rev() {
3126                let listener = listener.as_mut().unwrap();
3127                listener(event, DispatchPhase::Bubble, self);
3128                if !self.app.propagate_event {
3129                    break;
3130                }
3131            }
3132        }
3133
3134        self.window.rendered_frame.mouse_listeners = mouse_listeners;
3135
3136        if self.has_active_drag() {
3137            if event.is::<MouseMoveEvent>() {
3138                // If this was a mouse move event, redraw the window so that the
3139                // active drag can follow the mouse cursor.
3140                self.refresh();
3141            } else if event.is::<MouseUpEvent>() {
3142                // If this was a mouse up event, cancel the active drag and redraw
3143                // the window.
3144                self.active_drag = None;
3145                self.refresh();
3146            }
3147        }
3148    }
3149
3150    fn dispatch_key_event(&mut self, event: &dyn Any) {
3151        if self.window.dirty.get() {
3152            self.draw();
3153        }
3154
3155        let node_id = self
3156            .window
3157            .focus
3158            .and_then(|focus_id| {
3159                self.window
3160                    .rendered_frame
3161                    .dispatch_tree
3162                    .focusable_node_id(focus_id)
3163            })
3164            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3165
3166        let dispatch_path = self
3167            .window
3168            .rendered_frame
3169            .dispatch_tree
3170            .dispatch_path(node_id);
3171
3172        let mut bindings: SmallVec<[KeyBinding; 1]> = SmallVec::new();
3173        let mut pending = false;
3174        let mut keystroke: Option<Keystroke> = None;
3175
3176        if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
3177            if event.modifiers.number_of_modifiers() == 0
3178                && self.window.pending_modifier.modifiers.number_of_modifiers() == 1
3179                && !self.window.pending_modifier.saw_keystroke
3180            {
3181                if event.modifiers.number_of_modifiers() == 0 {
3182                    let key = match self.window.pending_modifier.modifiers {
3183                        modifiers if modifiers.shift => Some("shift"),
3184                        modifiers if modifiers.control => Some("control"),
3185                        modifiers if modifiers.alt => Some("alt"),
3186                        modifiers if modifiers.platform => Some("platform"),
3187                        modifiers if modifiers.function => Some("function"),
3188                        _ => None,
3189                    };
3190                    if let Some(key) = key {
3191                        let key = Keystroke {
3192                            key: key.to_string(),
3193                            ime_key: None,
3194                            modifiers: Modifiers::default(),
3195                        };
3196                        let KeymatchResult {
3197                            bindings: modifier_bindings,
3198                            pending: pending_bindings,
3199                        } = self
3200                            .window
3201                            .rendered_frame
3202                            .dispatch_tree
3203                            .dispatch_key(&key, &dispatch_path);
3204
3205                        keystroke = Some(key);
3206                        bindings = modifier_bindings;
3207                        pending = pending_bindings;
3208                    }
3209                }
3210            }
3211            if self.window.pending_modifier.modifiers.number_of_modifiers() == 0
3212                && event.modifiers.number_of_modifiers() == 1
3213            {
3214                self.window.pending_modifier.saw_keystroke = false
3215            }
3216            self.window.pending_modifier.modifiers = event.modifiers
3217        } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3218            self.window.pending_modifier.saw_keystroke = true;
3219            let KeymatchResult {
3220                bindings: key_down_bindings,
3221                pending: key_down_pending,
3222            } = self
3223                .window
3224                .rendered_frame
3225                .dispatch_tree
3226                .dispatch_key(&key_down_event.keystroke, &dispatch_path);
3227
3228            keystroke = Some(key_down_event.keystroke.clone());
3229
3230            bindings = key_down_bindings;
3231            pending = key_down_pending;
3232        }
3233
3234        if keystroke.is_none() {
3235            self.finish_dispatch_key_event(event, dispatch_path);
3236            return;
3237        }
3238
3239        if pending {
3240            let mut currently_pending = self.window.pending_input.take().unwrap_or_default();
3241            if currently_pending.focus.is_some() && currently_pending.focus != self.window.focus {
3242                currently_pending = PendingInput::default();
3243            }
3244            currently_pending.focus = self.window.focus;
3245            if let Some(keystroke) = keystroke {
3246                currently_pending.keystrokes.push(keystroke.clone());
3247            }
3248            for binding in bindings {
3249                currently_pending.bindings.push(binding);
3250            }
3251
3252            currently_pending.timer = Some(self.spawn(|mut cx| async move {
3253                cx.background_executor.timer(Duration::from_secs(1)).await;
3254                cx.update(move |cx| {
3255                    cx.clear_pending_keystrokes();
3256                    let Some(currently_pending) = cx.window.pending_input.take() else {
3257                        return;
3258                    };
3259                    cx.replay_pending_input(currently_pending);
3260                    cx.pending_input_changed();
3261                })
3262                .log_err();
3263            }));
3264
3265            self.window.pending_input = Some(currently_pending);
3266            self.pending_input_changed();
3267
3268            self.propagate_event = false;
3269            return;
3270        } else if let Some(currently_pending) = self.window.pending_input.take() {
3271            self.pending_input_changed();
3272            if bindings
3273                .iter()
3274                .all(|binding| !currently_pending.used_by_binding(binding))
3275            {
3276                self.replay_pending_input(currently_pending)
3277            }
3278        }
3279
3280        if !bindings.is_empty() {
3281            self.clear_pending_keystrokes();
3282        }
3283
3284        self.propagate_event = true;
3285        for binding in bindings {
3286            self.dispatch_action_on_node(node_id, binding.action.as_ref());
3287            if !self.propagate_event {
3288                self.dispatch_keystroke_observers(event, Some(binding.action));
3289                return;
3290            }
3291        }
3292
3293        self.finish_dispatch_key_event(event, dispatch_path)
3294    }
3295
3296    fn finish_dispatch_key_event(
3297        &mut self,
3298        event: &dyn Any,
3299        dispatch_path: SmallVec<[DispatchNodeId; 32]>,
3300    ) {
3301        self.dispatch_key_down_up_event(event, &dispatch_path);
3302        if !self.propagate_event {
3303            return;
3304        }
3305
3306        self.dispatch_modifiers_changed_event(event, &dispatch_path);
3307        if !self.propagate_event {
3308            return;
3309        }
3310
3311        self.dispatch_keystroke_observers(event, None);
3312    }
3313
3314    fn pending_input_changed(&mut self) {
3315        self.window
3316            .pending_input_observers
3317            .clone()
3318            .retain(&(), |callback| callback(self));
3319    }
3320
3321    fn dispatch_key_down_up_event(
3322        &mut self,
3323        event: &dyn Any,
3324        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3325    ) {
3326        // Capture phase
3327        for node_id in dispatch_path {
3328            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3329
3330            for key_listener in node.key_listeners.clone() {
3331                key_listener(event, DispatchPhase::Capture, self);
3332                if !self.propagate_event {
3333                    return;
3334                }
3335            }
3336        }
3337
3338        // Bubble phase
3339        for node_id in dispatch_path.iter().rev() {
3340            // Handle low level key events
3341            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3342            for key_listener in node.key_listeners.clone() {
3343                key_listener(event, DispatchPhase::Bubble, self);
3344                if !self.propagate_event {
3345                    return;
3346                }
3347            }
3348        }
3349    }
3350
3351    fn dispatch_modifiers_changed_event(
3352        &mut self,
3353        event: &dyn Any,
3354        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3355    ) {
3356        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
3357            return;
3358        };
3359        for node_id in dispatch_path.iter().rev() {
3360            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3361            for listener in node.modifiers_changed_listeners.clone() {
3362                listener(event, self);
3363                if !self.propagate_event {
3364                    return;
3365                }
3366            }
3367        }
3368    }
3369
3370    /// Determine whether a potential multi-stroke key binding is in progress on this window.
3371    pub fn has_pending_keystrokes(&self) -> bool {
3372        self.window
3373            .rendered_frame
3374            .dispatch_tree
3375            .has_pending_keystrokes()
3376    }
3377
3378    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
3379    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
3380        self.window
3381            .pending_input
3382            .as_ref()
3383            .map(|pending_input| pending_input.keystrokes.as_slice())
3384    }
3385
3386    fn replay_pending_input(&mut self, currently_pending: PendingInput) {
3387        let node_id = self
3388            .window
3389            .focus
3390            .and_then(|focus_id| {
3391                self.window
3392                    .rendered_frame
3393                    .dispatch_tree
3394                    .focusable_node_id(focus_id)
3395            })
3396            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3397
3398        if self.window.focus != currently_pending.focus {
3399            return;
3400        }
3401
3402        let input = currently_pending.input();
3403
3404        self.propagate_event = true;
3405        for binding in currently_pending.bindings {
3406            self.dispatch_action_on_node(node_id, binding.action.as_ref());
3407            if !self.propagate_event {
3408                return;
3409            }
3410        }
3411
3412        let dispatch_path = self
3413            .window
3414            .rendered_frame
3415            .dispatch_tree
3416            .dispatch_path(node_id);
3417
3418        for keystroke in currently_pending.keystrokes {
3419            let event = KeyDownEvent {
3420                keystroke,
3421                is_held: false,
3422            };
3423
3424            self.dispatch_key_down_up_event(&event, &dispatch_path);
3425            if !self.propagate_event {
3426                return;
3427            }
3428        }
3429
3430        if !input.is_empty() {
3431            if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
3432                input_handler.dispatch_input(&input, self);
3433                self.window.platform_window.set_input_handler(input_handler)
3434            }
3435        }
3436    }
3437
3438    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: &dyn Action) {
3439        let dispatch_path = self
3440            .window
3441            .rendered_frame
3442            .dispatch_tree
3443            .dispatch_path(node_id);
3444
3445        // Capture phase for global actions.
3446        self.propagate_event = true;
3447        if let Some(mut global_listeners) = self
3448            .global_action_listeners
3449            .remove(&action.as_any().type_id())
3450        {
3451            for listener in &global_listeners {
3452                listener(action.as_any(), DispatchPhase::Capture, self);
3453                if !self.propagate_event {
3454                    break;
3455                }
3456            }
3457
3458            global_listeners.extend(
3459                self.global_action_listeners
3460                    .remove(&action.as_any().type_id())
3461                    .unwrap_or_default(),
3462            );
3463
3464            self.global_action_listeners
3465                .insert(action.as_any().type_id(), global_listeners);
3466        }
3467
3468        if !self.propagate_event {
3469            return;
3470        }
3471
3472        // Capture phase for window actions.
3473        for node_id in &dispatch_path {
3474            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3475            for DispatchActionListener {
3476                action_type,
3477                listener,
3478            } in node.action_listeners.clone()
3479            {
3480                let any_action = action.as_any();
3481                if action_type == any_action.type_id() {
3482                    listener(any_action, DispatchPhase::Capture, self);
3483
3484                    if !self.propagate_event {
3485                        return;
3486                    }
3487                }
3488            }
3489        }
3490
3491        // Bubble phase for window actions.
3492        for node_id in dispatch_path.iter().rev() {
3493            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3494            for DispatchActionListener {
3495                action_type,
3496                listener,
3497            } in node.action_listeners.clone()
3498            {
3499                let any_action = action.as_any();
3500                if action_type == any_action.type_id() {
3501                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3502                    listener(any_action, DispatchPhase::Bubble, self);
3503
3504                    if !self.propagate_event {
3505                        return;
3506                    }
3507                }
3508            }
3509        }
3510
3511        // Bubble phase for global actions.
3512        if let Some(mut global_listeners) = self
3513            .global_action_listeners
3514            .remove(&action.as_any().type_id())
3515        {
3516            for listener in global_listeners.iter().rev() {
3517                self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3518
3519                listener(action.as_any(), DispatchPhase::Bubble, self);
3520                if !self.propagate_event {
3521                    break;
3522                }
3523            }
3524
3525            global_listeners.extend(
3526                self.global_action_listeners
3527                    .remove(&action.as_any().type_id())
3528                    .unwrap_or_default(),
3529            );
3530
3531            self.global_action_listeners
3532                .insert(action.as_any().type_id(), global_listeners);
3533        }
3534    }
3535
3536    /// Register the given handler to be invoked whenever the global of the given type
3537    /// is updated.
3538    pub fn observe_global<G: Global>(
3539        &mut self,
3540        f: impl Fn(&mut WindowContext<'_>) + 'static,
3541    ) -> Subscription {
3542        let window_handle = self.window.handle;
3543        let (subscription, activate) = self.global_observers.insert(
3544            TypeId::of::<G>(),
3545            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
3546        );
3547        self.app.defer(move |_| activate());
3548        subscription
3549    }
3550
3551    /// Focus the current window and bring it to the foreground at the platform level.
3552    pub fn activate_window(&self) {
3553        self.window.platform_window.activate();
3554    }
3555
3556    /// Minimize the current window at the platform level.
3557    pub fn minimize_window(&self) {
3558        self.window.platform_window.minimize();
3559    }
3560
3561    /// Toggle full screen status on the current window at the platform level.
3562    pub fn toggle_fullscreen(&self) {
3563        self.window.platform_window.toggle_fullscreen();
3564    }
3565
3566    /// Present a platform dialog.
3567    /// The provided message will be presented, along with buttons for each answer.
3568    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
3569    pub fn prompt(
3570        &mut self,
3571        level: PromptLevel,
3572        message: &str,
3573        detail: Option<&str>,
3574        answers: &[&str],
3575    ) -> oneshot::Receiver<usize> {
3576        let prompt_builder = self.app.prompt_builder.take();
3577        let Some(prompt_builder) = prompt_builder else {
3578            unreachable!("Re-entrant window prompting is not supported by GPUI");
3579        };
3580
3581        let receiver = match &prompt_builder {
3582            PromptBuilder::Default => self
3583                .window
3584                .platform_window
3585                .prompt(level, message, detail, answers)
3586                .unwrap_or_else(|| {
3587                    self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3588                }),
3589            PromptBuilder::Custom(_) => {
3590                self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3591            }
3592        };
3593
3594        self.app.prompt_builder = Some(prompt_builder);
3595
3596        receiver
3597    }
3598
3599    fn build_custom_prompt(
3600        &mut self,
3601        prompt_builder: &PromptBuilder,
3602        level: PromptLevel,
3603        message: &str,
3604        detail: Option<&str>,
3605        answers: &[&str],
3606    ) -> oneshot::Receiver<usize> {
3607        let (sender, receiver) = oneshot::channel();
3608        let handle = PromptHandle::new(sender);
3609        let handle = (prompt_builder)(level, message, detail, answers, handle, self);
3610        self.window.prompt = Some(handle);
3611        receiver
3612    }
3613
3614    /// Returns all available actions for the focused element.
3615    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
3616        let node_id = self
3617            .window
3618            .focus
3619            .and_then(|focus_id| {
3620                self.window
3621                    .rendered_frame
3622                    .dispatch_tree
3623                    .focusable_node_id(focus_id)
3624            })
3625            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3626
3627        let mut actions = self
3628            .window
3629            .rendered_frame
3630            .dispatch_tree
3631            .available_actions(node_id);
3632        for action_type in self.global_action_listeners.keys() {
3633            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
3634                let action = self.actions.build_action_type(action_type).ok();
3635                if let Some(action) = action {
3636                    actions.insert(ix, action);
3637                }
3638            }
3639        }
3640        actions
3641    }
3642
3643    /// Returns key bindings that invoke the given action on the currently focused element.
3644    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
3645        self.window
3646            .rendered_frame
3647            .dispatch_tree
3648            .bindings_for_action(
3649                action,
3650                &self.window.rendered_frame.dispatch_tree.context_stack,
3651            )
3652    }
3653
3654    /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
3655    pub fn bindings_for_action_in(
3656        &self,
3657        action: &dyn Action,
3658        focus_handle: &FocusHandle,
3659    ) -> Vec<KeyBinding> {
3660        let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
3661
3662        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
3663            return vec![];
3664        };
3665        let context_stack: Vec<_> = dispatch_tree
3666            .dispatch_path(node_id)
3667            .into_iter()
3668            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
3669            .collect();
3670        dispatch_tree.bindings_for_action(action, &context_stack)
3671    }
3672
3673    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
3674    pub fn listener_for<V: Render, E>(
3675        &self,
3676        view: &View<V>,
3677        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
3678    ) -> impl Fn(&E, &mut WindowContext) + 'static {
3679        let view = view.downgrade();
3680        move |e: &E, cx: &mut WindowContext| {
3681            view.update(cx, |view, cx| f(view, e, cx)).ok();
3682        }
3683    }
3684
3685    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
3686    pub fn handler_for<V: Render>(
3687        &self,
3688        view: &View<V>,
3689        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
3690    ) -> impl Fn(&mut WindowContext) {
3691        let view = view.downgrade();
3692        move |cx: &mut WindowContext| {
3693            view.update(cx, |view, cx| f(view, cx)).ok();
3694        }
3695    }
3696
3697    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
3698    /// If the callback returns false, the window won't be closed.
3699    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
3700        let mut this = self.to_async();
3701        self.window
3702            .platform_window
3703            .on_should_close(Box::new(move || this.update(|cx| f(cx)).unwrap_or(true)))
3704    }
3705
3706    /// Register an action listener on the window for the next frame. The type of action
3707    /// is determined by the first parameter of the given listener. When the next frame is rendered
3708    /// the listener will be cleared.
3709    ///
3710    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
3711    /// a specific need to register a global listener.
3712    pub fn on_action(
3713        &mut self,
3714        action_type: TypeId,
3715        listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
3716    ) {
3717        self.window
3718            .next_frame
3719            .dispatch_tree
3720            .on_action(action_type, Rc::new(listener));
3721    }
3722}
3723
3724#[cfg(target_os = "windows")]
3725impl WindowContext<'_> {
3726    /// Returns the raw HWND handle for the window.
3727    pub fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND {
3728        self.window.platform_window.get_raw_handle()
3729    }
3730}
3731
3732impl Context for WindowContext<'_> {
3733    type Result<T> = T;
3734
3735    fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
3736    where
3737        T: 'static,
3738    {
3739        let slot = self.app.entities.reserve();
3740        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
3741        self.entities.insert(slot, model)
3742    }
3743
3744    fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
3745        self.app.reserve_model()
3746    }
3747
3748    fn insert_model<T: 'static>(
3749        &mut self,
3750        reservation: crate::Reservation<T>,
3751        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
3752    ) -> Self::Result<Model<T>> {
3753        self.app.insert_model(reservation, build_model)
3754    }
3755
3756    fn update_model<T: 'static, R>(
3757        &mut self,
3758        model: &Model<T>,
3759        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
3760    ) -> R {
3761        let mut entity = self.entities.lease(model);
3762        let result = update(
3763            &mut *entity,
3764            &mut ModelContext::new(&mut *self.app, model.downgrade()),
3765        );
3766        self.entities.end_lease(entity);
3767        result
3768    }
3769
3770    fn read_model<T, R>(
3771        &self,
3772        handle: &Model<T>,
3773        read: impl FnOnce(&T, &AppContext) -> R,
3774    ) -> Self::Result<R>
3775    where
3776        T: 'static,
3777    {
3778        let entity = self.entities.read(handle);
3779        read(entity, &*self.app)
3780    }
3781
3782    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
3783    where
3784        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
3785    {
3786        if window == self.window.handle {
3787            let root_view = self.window.root_view.clone().unwrap();
3788            Ok(update(root_view, self))
3789        } else {
3790            window.update(self.app, update)
3791        }
3792    }
3793
3794    fn read_window<T, R>(
3795        &self,
3796        window: &WindowHandle<T>,
3797        read: impl FnOnce(View<T>, &AppContext) -> R,
3798    ) -> Result<R>
3799    where
3800        T: 'static,
3801    {
3802        if window.any_handle == self.window.handle {
3803            let root_view = self
3804                .window
3805                .root_view
3806                .clone()
3807                .unwrap()
3808                .downcast::<T>()
3809                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3810            Ok(read(root_view, self))
3811        } else {
3812            self.app.read_window(window, read)
3813        }
3814    }
3815}
3816
3817impl VisualContext for WindowContext<'_> {
3818    fn new_view<V>(
3819        &mut self,
3820        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3821    ) -> Self::Result<View<V>>
3822    where
3823        V: 'static + Render,
3824    {
3825        let slot = self.app.entities.reserve();
3826        let view = View {
3827            model: slot.clone(),
3828        };
3829        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
3830        let entity = build_view_state(&mut cx);
3831        cx.entities.insert(slot, entity);
3832
3833        // Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
3834        fn notify_observers(cx: &mut WindowContext, tid: TypeId, view: AnyView) {
3835            cx.new_view_observers.clone().retain(&tid, |observer| {
3836                let any_view = view.clone();
3837                (observer)(any_view, cx);
3838                true
3839            });
3840        }
3841        notify_observers(self, TypeId::of::<V>(), AnyView::from(view.clone()));
3842
3843        view
3844    }
3845
3846    /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
3847    fn update_view<T: 'static, R>(
3848        &mut self,
3849        view: &View<T>,
3850        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
3851    ) -> Self::Result<R> {
3852        let mut lease = self.app.entities.lease(&view.model);
3853        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
3854        let result = update(&mut *lease, &mut cx);
3855        cx.app.entities.end_lease(lease);
3856        result
3857    }
3858
3859    fn replace_root_view<V>(
3860        &mut self,
3861        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3862    ) -> Self::Result<View<V>>
3863    where
3864        V: 'static + Render,
3865    {
3866        let view = self.new_view(build_view);
3867        self.window.root_view = Some(view.clone().into());
3868        self.refresh();
3869        view
3870    }
3871
3872    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
3873        self.update_view(view, |view, cx| {
3874            view.focus_handle(cx).clone().focus(cx);
3875        })
3876    }
3877
3878    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
3879    where
3880        V: ManagedView,
3881    {
3882        self.update_view(view, |_, cx| cx.emit(DismissEvent))
3883    }
3884}
3885
3886impl<'a> std::ops::Deref for WindowContext<'a> {
3887    type Target = AppContext;
3888
3889    fn deref(&self) -> &Self::Target {
3890        self.app
3891    }
3892}
3893
3894impl<'a> std::ops::DerefMut for WindowContext<'a> {
3895    fn deref_mut(&mut self) -> &mut Self::Target {
3896        self.app
3897    }
3898}
3899
3900impl<'a> Borrow<AppContext> for WindowContext<'a> {
3901    fn borrow(&self) -> &AppContext {
3902        self.app
3903    }
3904}
3905
3906impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
3907    fn borrow_mut(&mut self) -> &mut AppContext {
3908        self.app
3909    }
3910}
3911
3912/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
3913pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
3914    #[doc(hidden)]
3915    fn app_mut(&mut self) -> &mut AppContext {
3916        self.borrow_mut()
3917    }
3918
3919    #[doc(hidden)]
3920    fn app(&self) -> &AppContext {
3921        self.borrow()
3922    }
3923
3924    #[doc(hidden)]
3925    fn window(&self) -> &Window {
3926        self.borrow()
3927    }
3928
3929    #[doc(hidden)]
3930    fn window_mut(&mut self) -> &mut Window {
3931        self.borrow_mut()
3932    }
3933}
3934
3935impl Borrow<Window> for WindowContext<'_> {
3936    fn borrow(&self) -> &Window {
3937        self.window
3938    }
3939}
3940
3941impl BorrowMut<Window> for WindowContext<'_> {
3942    fn borrow_mut(&mut self) -> &mut Window {
3943        self.window
3944    }
3945}
3946
3947impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
3948
3949/// Provides access to application state that is specialized for a particular [`View`].
3950/// Allows you to interact with focus, emit events, etc.
3951/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
3952/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
3953pub struct ViewContext<'a, V> {
3954    window_cx: WindowContext<'a>,
3955    view: &'a View<V>,
3956}
3957
3958impl<V> Borrow<AppContext> for ViewContext<'_, V> {
3959    fn borrow(&self) -> &AppContext {
3960        &*self.window_cx.app
3961    }
3962}
3963
3964impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
3965    fn borrow_mut(&mut self) -> &mut AppContext {
3966        &mut *self.window_cx.app
3967    }
3968}
3969
3970impl<V> Borrow<Window> for ViewContext<'_, V> {
3971    fn borrow(&self) -> &Window {
3972        &*self.window_cx.window
3973    }
3974}
3975
3976impl<V> BorrowMut<Window> for ViewContext<'_, V> {
3977    fn borrow_mut(&mut self) -> &mut Window {
3978        &mut *self.window_cx.window
3979    }
3980}
3981
3982impl<'a, V: 'static> ViewContext<'a, V> {
3983    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
3984        Self {
3985            window_cx: WindowContext::new(app, window),
3986            view,
3987        }
3988    }
3989
3990    /// Get the entity_id of this view.
3991    pub fn entity_id(&self) -> EntityId {
3992        self.view.entity_id()
3993    }
3994
3995    /// Get the view pointer underlying this context.
3996    pub fn view(&self) -> &View<V> {
3997        self.view
3998    }
3999
4000    /// Get the model underlying this view.
4001    pub fn model(&self) -> &Model<V> {
4002        &self.view.model
4003    }
4004
4005    /// Access the underlying window context.
4006    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
4007        &mut self.window_cx
4008    }
4009
4010    /// Sets a given callback to be run on the next frame.
4011    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
4012    where
4013        V: 'static,
4014    {
4015        let view = self.view().clone();
4016        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
4017    }
4018
4019    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
4020    /// that are currently on the stack to be returned to the app.
4021    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
4022        let view = self.view().downgrade();
4023        self.window_cx.defer(move |cx| {
4024            view.update(cx, f).ok();
4025        });
4026    }
4027
4028    /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
4029    pub fn observe<V2, E>(
4030        &mut self,
4031        entity: &E,
4032        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
4033    ) -> Subscription
4034    where
4035        V2: 'static,
4036        V: 'static,
4037        E: Entity<V2>,
4038    {
4039        let view = self.view().downgrade();
4040        let entity_id = entity.entity_id();
4041        let entity = entity.downgrade();
4042        let window_handle = self.window.handle;
4043        self.app.new_observer(
4044            entity_id,
4045            Box::new(move |cx| {
4046                window_handle
4047                    .update(cx, |_, cx| {
4048                        if let Some(handle) = E::upgrade_from(&entity) {
4049                            view.update(cx, |this, cx| on_notify(this, handle, cx))
4050                                .is_ok()
4051                        } else {
4052                            false
4053                        }
4054                    })
4055                    .unwrap_or(false)
4056            }),
4057        )
4058    }
4059
4060    /// Subscribe to events emitted by another model or view.
4061    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
4062    /// 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.
4063    pub fn subscribe<V2, E, Evt>(
4064        &mut self,
4065        entity: &E,
4066        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
4067    ) -> Subscription
4068    where
4069        V2: EventEmitter<Evt>,
4070        E: Entity<V2>,
4071        Evt: 'static,
4072    {
4073        let view = self.view().downgrade();
4074        let entity_id = entity.entity_id();
4075        let handle = entity.downgrade();
4076        let window_handle = self.window.handle;
4077        self.app.new_subscription(
4078            entity_id,
4079            (
4080                TypeId::of::<Evt>(),
4081                Box::new(move |event, cx| {
4082                    window_handle
4083                        .update(cx, |_, cx| {
4084                            if let Some(handle) = E::upgrade_from(&handle) {
4085                                let event = event.downcast_ref().expect("invalid event type");
4086                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
4087                                    .is_ok()
4088                            } else {
4089                                false
4090                            }
4091                        })
4092                        .unwrap_or(false)
4093                }),
4094            ),
4095        )
4096    }
4097
4098    /// Register a callback to be invoked when the view is released.
4099    ///
4100    /// The callback receives a handle to the view's window. This handle may be
4101    /// invalid, if the window was closed before the view was released.
4102    pub fn on_release(
4103        &mut self,
4104        on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
4105    ) -> Subscription {
4106        let window_handle = self.window.handle;
4107        let (subscription, activate) = self.app.release_listeners.insert(
4108            self.view.model.entity_id,
4109            Box::new(move |this, cx| {
4110                let this = this.downcast_mut().expect("invalid entity type");
4111                on_release(this, window_handle, cx)
4112            }),
4113        );
4114        activate();
4115        subscription
4116    }
4117
4118    /// Register a callback to be invoked when the given Model or View is released.
4119    pub fn observe_release<V2, E>(
4120        &mut self,
4121        entity: &E,
4122        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
4123    ) -> Subscription
4124    where
4125        V: 'static,
4126        V2: 'static,
4127        E: Entity<V2>,
4128    {
4129        let view = self.view().downgrade();
4130        let entity_id = entity.entity_id();
4131        let window_handle = self.window.handle;
4132        let (subscription, activate) = self.app.release_listeners.insert(
4133            entity_id,
4134            Box::new(move |entity, cx| {
4135                let entity = entity.downcast_mut().expect("invalid entity type");
4136                let _ = window_handle.update(cx, |_, cx| {
4137                    view.update(cx, |this, cx| on_release(this, entity, cx))
4138                });
4139            }),
4140        );
4141        activate();
4142        subscription
4143    }
4144
4145    /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
4146    /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
4147    pub fn notify(&mut self) {
4148        self.window_cx.notify(self.view.entity_id());
4149    }
4150
4151    /// Register a callback to be invoked when the window is resized.
4152    pub fn observe_window_bounds(
4153        &mut self,
4154        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4155    ) -> Subscription {
4156        let view = self.view.downgrade();
4157        let (subscription, activate) = self.window.bounds_observers.insert(
4158            (),
4159            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4160        );
4161        activate();
4162        subscription
4163    }
4164
4165    /// Register a callback to be invoked when the window is activated or deactivated.
4166    pub fn observe_window_activation(
4167        &mut self,
4168        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4169    ) -> Subscription {
4170        let view = self.view.downgrade();
4171        let (subscription, activate) = self.window.activation_observers.insert(
4172            (),
4173            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4174        );
4175        activate();
4176        subscription
4177    }
4178
4179    /// Registers a callback to be invoked when the window appearance changes.
4180    pub fn observe_window_appearance(
4181        &mut self,
4182        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4183    ) -> Subscription {
4184        let view = self.view.downgrade();
4185        let (subscription, activate) = self.window.appearance_observers.insert(
4186            (),
4187            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4188        );
4189        activate();
4190        subscription
4191    }
4192
4193    /// Register a callback to be invoked when the window's pending input changes.
4194    pub fn observe_pending_input(
4195        &mut self,
4196        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4197    ) -> Subscription {
4198        let view = self.view.downgrade();
4199        let (subscription, activate) = self.window.pending_input_observers.insert(
4200            (),
4201            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4202        );
4203        activate();
4204        subscription
4205    }
4206
4207    /// Register a listener to be called when the given focus handle receives focus.
4208    /// Returns a subscription and persists until the subscription is dropped.
4209    pub fn on_focus(
4210        &mut self,
4211        handle: &FocusHandle,
4212        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4213    ) -> Subscription {
4214        let view = self.view.downgrade();
4215        let focus_id = handle.id;
4216        let (subscription, activate) =
4217            self.window.new_focus_listener(Box::new(move |event, cx| {
4218                view.update(cx, |view, cx| {
4219                    if event.previous_focus_path.last() != Some(&focus_id)
4220                        && event.current_focus_path.last() == Some(&focus_id)
4221                    {
4222                        listener(view, cx)
4223                    }
4224                })
4225                .is_ok()
4226            }));
4227        self.app.defer(|_| activate());
4228        subscription
4229    }
4230
4231    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
4232    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
4233    /// Returns a subscription and persists until the subscription is dropped.
4234    pub fn on_focus_in(
4235        &mut self,
4236        handle: &FocusHandle,
4237        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4238    ) -> Subscription {
4239        let view = self.view.downgrade();
4240        let focus_id = handle.id;
4241        let (subscription, activate) =
4242            self.window.new_focus_listener(Box::new(move |event, cx| {
4243                view.update(cx, |view, cx| {
4244                    if event.is_focus_in(focus_id) {
4245                        listener(view, cx)
4246                    }
4247                })
4248                .is_ok()
4249            }));
4250        self.app.defer(move |_| activate());
4251        subscription
4252    }
4253
4254    /// Register a listener to be called when the given focus handle loses focus.
4255    /// Returns a subscription and persists until the subscription is dropped.
4256    pub fn on_blur(
4257        &mut self,
4258        handle: &FocusHandle,
4259        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4260    ) -> Subscription {
4261        let view = self.view.downgrade();
4262        let focus_id = handle.id;
4263        let (subscription, activate) =
4264            self.window.new_focus_listener(Box::new(move |event, cx| {
4265                view.update(cx, |view, cx| {
4266                    if event.previous_focus_path.last() == Some(&focus_id)
4267                        && event.current_focus_path.last() != Some(&focus_id)
4268                    {
4269                        listener(view, cx)
4270                    }
4271                })
4272                .is_ok()
4273            }));
4274        self.app.defer(move |_| activate());
4275        subscription
4276    }
4277
4278    /// Register a listener to be called when nothing in the window has focus.
4279    /// This typically happens when the node that was focused is removed from the tree,
4280    /// and this callback lets you chose a default place to restore the users focus.
4281    /// Returns a subscription and persists until the subscription is dropped.
4282    pub fn on_focus_lost(
4283        &mut self,
4284        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4285    ) -> Subscription {
4286        let view = self.view.downgrade();
4287        let (subscription, activate) = self.window.focus_lost_listeners.insert(
4288            (),
4289            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
4290        );
4291        activate();
4292        subscription
4293    }
4294
4295    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
4296    /// Returns a subscription and persists until the subscription is dropped.
4297    pub fn on_focus_out(
4298        &mut self,
4299        handle: &FocusHandle,
4300        mut listener: impl FnMut(&mut V, FocusOutEvent, &mut ViewContext<V>) + 'static,
4301    ) -> Subscription {
4302        let view = self.view.downgrade();
4303        let focus_id = handle.id;
4304        let (subscription, activate) =
4305            self.window.new_focus_listener(Box::new(move |event, cx| {
4306                view.update(cx, |view, cx| {
4307                    if let Some(blurred_id) = event.previous_focus_path.last().copied() {
4308                        if event.is_focus_out(focus_id) {
4309                            let event = FocusOutEvent {
4310                                blurred: WeakFocusHandle {
4311                                    id: blurred_id,
4312                                    handles: Arc::downgrade(&cx.window.focus_handles),
4313                                },
4314                            };
4315                            listener(view, event, cx)
4316                        }
4317                    }
4318                })
4319                .is_ok()
4320            }));
4321        self.app.defer(move |_| activate());
4322        subscription
4323    }
4324
4325    /// Schedule a future to be run asynchronously.
4326    /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
4327    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
4328    /// The returned future will be polled on the main thread.
4329    pub fn spawn<Fut, R>(
4330        &mut self,
4331        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
4332    ) -> Task<R>
4333    where
4334        R: 'static,
4335        Fut: Future<Output = R> + 'static,
4336    {
4337        let view = self.view().downgrade();
4338        self.window_cx.spawn(|cx| f(view, cx))
4339    }
4340
4341    /// Register a callback to be invoked when the given global state changes.
4342    pub fn observe_global<G: Global>(
4343        &mut self,
4344        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
4345    ) -> Subscription {
4346        let window_handle = self.window.handle;
4347        let view = self.view().downgrade();
4348        let (subscription, activate) = self.global_observers.insert(
4349            TypeId::of::<G>(),
4350            Box::new(move |cx| {
4351                window_handle
4352                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
4353                    .unwrap_or(false)
4354            }),
4355        );
4356        self.app.defer(move |_| activate());
4357        subscription
4358    }
4359
4360    /// Register a callback to be invoked when the given Action type is dispatched to the window.
4361    pub fn on_action(
4362        &mut self,
4363        action_type: TypeId,
4364        listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
4365    ) {
4366        let handle = self.view().clone();
4367        self.window_cx
4368            .on_action(action_type, move |action, phase, cx| {
4369                handle.update(cx, |view, cx| {
4370                    listener(view, action, phase, cx);
4371                })
4372            });
4373    }
4374
4375    /// Emit an event to be handled by any other views that have subscribed via [ViewContext::subscribe].
4376    pub fn emit<Evt>(&mut self, event: Evt)
4377    where
4378        Evt: 'static,
4379        V: EventEmitter<Evt>,
4380    {
4381        let emitter = self.view.model.entity_id;
4382        self.app.push_effect(Effect::Emit {
4383            emitter,
4384            event_type: TypeId::of::<Evt>(),
4385            event: Box::new(event),
4386        });
4387    }
4388
4389    /// Move focus to the current view, assuming it implements [`FocusableView`].
4390    pub fn focus_self(&mut self)
4391    where
4392        V: FocusableView,
4393    {
4394        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
4395    }
4396
4397    /// Convenience method for accessing view state in an event callback.
4398    ///
4399    /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
4400    /// but it's often useful to be able to access view state in these
4401    /// callbacks. This method provides a convenient way to do so.
4402    pub fn listener<E>(
4403        &self,
4404        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
4405    ) -> impl Fn(&E, &mut WindowContext) + 'static {
4406        let view = self.view().downgrade();
4407        move |e: &E, cx: &mut WindowContext| {
4408            view.update(cx, |view, cx| f(view, e, cx)).ok();
4409        }
4410    }
4411}
4412
4413impl<V> Context for ViewContext<'_, V> {
4414    type Result<U> = U;
4415
4416    fn new_model<T: 'static>(
4417        &mut self,
4418        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4419    ) -> Model<T> {
4420        self.window_cx.new_model(build_model)
4421    }
4422
4423    fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
4424        self.window_cx.reserve_model()
4425    }
4426
4427    fn insert_model<T: 'static>(
4428        &mut self,
4429        reservation: crate::Reservation<T>,
4430        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4431    ) -> Self::Result<Model<T>> {
4432        self.window_cx.insert_model(reservation, build_model)
4433    }
4434
4435    fn update_model<T: 'static, R>(
4436        &mut self,
4437        model: &Model<T>,
4438        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
4439    ) -> R {
4440        self.window_cx.update_model(model, update)
4441    }
4442
4443    fn read_model<T, R>(
4444        &self,
4445        handle: &Model<T>,
4446        read: impl FnOnce(&T, &AppContext) -> R,
4447    ) -> Self::Result<R>
4448    where
4449        T: 'static,
4450    {
4451        self.window_cx.read_model(handle, read)
4452    }
4453
4454    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
4455    where
4456        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
4457    {
4458        self.window_cx.update_window(window, update)
4459    }
4460
4461    fn read_window<T, R>(
4462        &self,
4463        window: &WindowHandle<T>,
4464        read: impl FnOnce(View<T>, &AppContext) -> R,
4465    ) -> Result<R>
4466    where
4467        T: 'static,
4468    {
4469        self.window_cx.read_window(window, read)
4470    }
4471}
4472
4473impl<V: 'static> VisualContext for ViewContext<'_, V> {
4474    fn new_view<W: Render + 'static>(
4475        &mut self,
4476        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4477    ) -> Self::Result<View<W>> {
4478        self.window_cx.new_view(build_view_state)
4479    }
4480
4481    fn update_view<V2: 'static, R>(
4482        &mut self,
4483        view: &View<V2>,
4484        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
4485    ) -> Self::Result<R> {
4486        self.window_cx.update_view(view, update)
4487    }
4488
4489    fn replace_root_view<W>(
4490        &mut self,
4491        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4492    ) -> Self::Result<View<W>>
4493    where
4494        W: 'static + Render,
4495    {
4496        self.window_cx.replace_root_view(build_view)
4497    }
4498
4499    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
4500        self.window_cx.focus_view(view)
4501    }
4502
4503    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
4504        self.window_cx.dismiss_view(view)
4505    }
4506}
4507
4508impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
4509    type Target = WindowContext<'a>;
4510
4511    fn deref(&self) -> &Self::Target {
4512        &self.window_cx
4513    }
4514}
4515
4516impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
4517    fn deref_mut(&mut self) -> &mut Self::Target {
4518        &mut self.window_cx
4519    }
4520}
4521
4522// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
4523slotmap::new_key_type! {
4524    /// A unique identifier for a window.
4525    pub struct WindowId;
4526}
4527
4528impl WindowId {
4529    /// Converts this window ID to a `u64`.
4530    pub fn as_u64(&self) -> u64 {
4531        self.0.as_ffi()
4532    }
4533}
4534
4535/// A handle to a window with a specific root view type.
4536/// Note that this does not keep the window alive on its own.
4537#[derive(Deref, DerefMut)]
4538pub struct WindowHandle<V> {
4539    #[deref]
4540    #[deref_mut]
4541    pub(crate) any_handle: AnyWindowHandle,
4542    state_type: PhantomData<V>,
4543}
4544
4545impl<V: 'static + Render> WindowHandle<V> {
4546    /// Creates a new handle from a window ID.
4547    /// This does not check if the root type of the window is `V`.
4548    pub fn new(id: WindowId) -> Self {
4549        WindowHandle {
4550            any_handle: AnyWindowHandle {
4551                id,
4552                state_type: TypeId::of::<V>(),
4553            },
4554            state_type: PhantomData,
4555        }
4556    }
4557
4558    /// Get the root view out of this window.
4559    ///
4560    /// This will fail if the window is closed or if the root view's type does not match `V`.
4561    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
4562    where
4563        C: Context,
4564    {
4565        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
4566            root_view
4567                .downcast::<V>()
4568                .map_err(|_| anyhow!("the type of the window's root view has changed"))
4569        }))
4570    }
4571
4572    /// Updates the root view of this window.
4573    ///
4574    /// This will fail if the window has been closed or if the root view's type does not match
4575    pub fn update<C, R>(
4576        &self,
4577        cx: &mut C,
4578        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
4579    ) -> Result<R>
4580    where
4581        C: Context,
4582    {
4583        cx.update_window(self.any_handle, |root_view, cx| {
4584            let view = root_view
4585                .downcast::<V>()
4586                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4587            Ok(cx.update_view(&view, update))
4588        })?
4589    }
4590
4591    /// Read the root view out of this window.
4592    ///
4593    /// This will fail if the window is closed or if the root view's type does not match `V`.
4594    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
4595        let x = cx
4596            .windows
4597            .get(self.id)
4598            .and_then(|window| {
4599                window
4600                    .as_ref()
4601                    .and_then(|window| window.root_view.clone())
4602                    .map(|root_view| root_view.downcast::<V>())
4603            })
4604            .ok_or_else(|| anyhow!("window not found"))?
4605            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4606
4607        Ok(x.read(cx))
4608    }
4609
4610    /// Read the root view out of this window, with a callback
4611    ///
4612    /// This will fail if the window is closed or if the root view's type does not match `V`.
4613    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
4614    where
4615        C: Context,
4616    {
4617        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
4618    }
4619
4620    /// Read the root view pointer off of this window.
4621    ///
4622    /// This will fail if the window is closed or if the root view's type does not match `V`.
4623    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
4624    where
4625        C: Context,
4626    {
4627        cx.read_window(self, |root_view, _cx| root_view.clone())
4628    }
4629
4630    /// Check if this window is 'active'.
4631    ///
4632    /// Will return `None` if the window is closed or currently
4633    /// borrowed.
4634    pub fn is_active(&self, cx: &mut AppContext) -> Option<bool> {
4635        cx.update_window(self.any_handle, |_, cx| cx.is_window_active())
4636            .ok()
4637    }
4638}
4639
4640impl<V> Copy for WindowHandle<V> {}
4641
4642impl<V> Clone for WindowHandle<V> {
4643    fn clone(&self) -> Self {
4644        *self
4645    }
4646}
4647
4648impl<V> PartialEq for WindowHandle<V> {
4649    fn eq(&self, other: &Self) -> bool {
4650        self.any_handle == other.any_handle
4651    }
4652}
4653
4654impl<V> Eq for WindowHandle<V> {}
4655
4656impl<V> Hash for WindowHandle<V> {
4657    fn hash<H: Hasher>(&self, state: &mut H) {
4658        self.any_handle.hash(state);
4659    }
4660}
4661
4662impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
4663    fn from(val: WindowHandle<V>) -> Self {
4664        val.any_handle
4665    }
4666}
4667
4668unsafe impl<V> Send for WindowHandle<V> {}
4669unsafe impl<V> Sync for WindowHandle<V> {}
4670
4671/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
4672#[derive(Copy, Clone, PartialEq, Eq, Hash)]
4673pub struct AnyWindowHandle {
4674    pub(crate) id: WindowId,
4675    state_type: TypeId,
4676}
4677
4678impl AnyWindowHandle {
4679    /// Get the ID of this window.
4680    pub fn window_id(&self) -> WindowId {
4681        self.id
4682    }
4683
4684    /// Attempt to convert this handle to a window handle with a specific root view type.
4685    /// If the types do not match, this will return `None`.
4686    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
4687        if TypeId::of::<T>() == self.state_type {
4688            Some(WindowHandle {
4689                any_handle: *self,
4690                state_type: PhantomData,
4691            })
4692        } else {
4693            None
4694        }
4695    }
4696
4697    /// Updates the state of the root view of this window.
4698    ///
4699    /// This will fail if the window has been closed.
4700    pub fn update<C, R>(
4701        self,
4702        cx: &mut C,
4703        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
4704    ) -> Result<R>
4705    where
4706        C: Context,
4707    {
4708        cx.update_window(self, update)
4709    }
4710
4711    /// Read the state of the root view of this window.
4712    ///
4713    /// This will fail if the window has been closed.
4714    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
4715    where
4716        C: Context,
4717        T: 'static,
4718    {
4719        let view = self
4720            .downcast::<T>()
4721            .context("the type of the window's root view has changed")?;
4722
4723        cx.read_window(&view, read)
4724    }
4725}
4726
4727/// An identifier for an [`Element`](crate::Element).
4728///
4729/// Can be constructed with a string, a number, or both, as well
4730/// as other internal representations.
4731#[derive(Clone, Debug, Eq, PartialEq, Hash)]
4732pub enum ElementId {
4733    /// The ID of a View element
4734    View(EntityId),
4735    /// An integer ID.
4736    Integer(usize),
4737    /// A string based ID.
4738    Name(SharedString),
4739    /// A UUID.
4740    Uuid(Uuid),
4741    /// An ID that's equated with a focus handle.
4742    FocusHandle(FocusId),
4743    /// A combination of a name and an integer.
4744    NamedInteger(SharedString, usize),
4745}
4746
4747impl Display for ElementId {
4748    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4749        match self {
4750            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
4751            ElementId::Integer(ix) => write!(f, "{}", ix)?,
4752            ElementId::Name(name) => write!(f, "{}", name)?,
4753            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
4754            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
4755            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
4756        }
4757
4758        Ok(())
4759    }
4760}
4761
4762impl TryInto<SharedString> for ElementId {
4763    type Error = anyhow::Error;
4764
4765    fn try_into(self) -> anyhow::Result<SharedString> {
4766        if let ElementId::Name(name) = self {
4767            Ok(name)
4768        } else {
4769            Err(anyhow!("element id is not string"))
4770        }
4771    }
4772}
4773
4774impl From<usize> for ElementId {
4775    fn from(id: usize) -> Self {
4776        ElementId::Integer(id)
4777    }
4778}
4779
4780impl From<i32> for ElementId {
4781    fn from(id: i32) -> Self {
4782        Self::Integer(id as usize)
4783    }
4784}
4785
4786impl From<SharedString> for ElementId {
4787    fn from(name: SharedString) -> Self {
4788        ElementId::Name(name)
4789    }
4790}
4791
4792impl From<&'static str> for ElementId {
4793    fn from(name: &'static str) -> Self {
4794        ElementId::Name(name.into())
4795    }
4796}
4797
4798impl<'a> From<&'a FocusHandle> for ElementId {
4799    fn from(handle: &'a FocusHandle) -> Self {
4800        ElementId::FocusHandle(handle.id)
4801    }
4802}
4803
4804impl From<(&'static str, EntityId)> for ElementId {
4805    fn from((name, id): (&'static str, EntityId)) -> Self {
4806        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
4807    }
4808}
4809
4810impl From<(&'static str, usize)> for ElementId {
4811    fn from((name, id): (&'static str, usize)) -> Self {
4812        ElementId::NamedInteger(name.into(), id)
4813    }
4814}
4815
4816impl From<(&'static str, u64)> for ElementId {
4817    fn from((name, id): (&'static str, u64)) -> Self {
4818        ElementId::NamedInteger(name.into(), id as usize)
4819    }
4820}
4821
4822impl From<Uuid> for ElementId {
4823    fn from(value: Uuid) -> Self {
4824        Self::Uuid(value)
4825    }
4826}
4827
4828impl From<(&'static str, u32)> for ElementId {
4829    fn from((name, id): (&'static str, u32)) -> Self {
4830        ElementId::NamedInteger(name.into(), id as usize)
4831    }
4832}
4833
4834/// A rectangle to be rendered in the window at the given position and size.
4835/// Passed as an argument [`WindowContext::paint_quad`].
4836#[derive(Clone)]
4837pub struct PaintQuad {
4838    /// The bounds of the quad within the window.
4839    pub bounds: Bounds<Pixels>,
4840    /// The radii of the quad's corners.
4841    pub corner_radii: Corners<Pixels>,
4842    /// The background color of the quad.
4843    pub background: Hsla,
4844    /// The widths of the quad's borders.
4845    pub border_widths: Edges<Pixels>,
4846    /// The color of the quad's borders.
4847    pub border_color: Hsla,
4848}
4849
4850impl PaintQuad {
4851    /// Sets the corner radii of the quad.
4852    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
4853        PaintQuad {
4854            corner_radii: corner_radii.into(),
4855            ..self
4856        }
4857    }
4858
4859    /// Sets the border widths of the quad.
4860    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
4861        PaintQuad {
4862            border_widths: border_widths.into(),
4863            ..self
4864        }
4865    }
4866
4867    /// Sets the border color of the quad.
4868    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
4869        PaintQuad {
4870            border_color: border_color.into(),
4871            ..self
4872        }
4873    }
4874
4875    /// Sets the background color of the quad.
4876    pub fn background(self, background: impl Into<Hsla>) -> Self {
4877        PaintQuad {
4878            background: background.into(),
4879            ..self
4880        }
4881    }
4882}
4883
4884/// Creates a quad with the given parameters.
4885pub fn quad(
4886    bounds: Bounds<Pixels>,
4887    corner_radii: impl Into<Corners<Pixels>>,
4888    background: impl Into<Hsla>,
4889    border_widths: impl Into<Edges<Pixels>>,
4890    border_color: impl Into<Hsla>,
4891) -> PaintQuad {
4892    PaintQuad {
4893        bounds,
4894        corner_radii: corner_radii.into(),
4895        background: background.into(),
4896        border_widths: border_widths.into(),
4897        border_color: border_color.into(),
4898    }
4899}
4900
4901/// Creates a filled quad with the given bounds and background color.
4902pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
4903    PaintQuad {
4904        bounds: bounds.into(),
4905        corner_radii: (0.).into(),
4906        background: background.into(),
4907        border_widths: (0.).into(),
4908        border_color: transparent_black(),
4909    }
4910}
4911
4912/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
4913pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
4914    PaintQuad {
4915        bounds: bounds.into(),
4916        corner_radii: (0.).into(),
4917        background: transparent_black(),
4918        border_widths: (1.).into(),
4919        border_color: border_color.into(),
4920    }
4921}