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