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    /// Updates the window's title at the platform level.
1147    pub fn set_window_title(&mut self, title: &str) {
1148        self.window.platform_window.set_title(title);
1149    }
1150
1151    /// Sets the application identifier.
1152    pub fn set_app_id(&mut self, app_id: &str) {
1153        self.window.platform_window.set_app_id(app_id);
1154    }
1155
1156    /// Sets the window background appearance.
1157    pub fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance) {
1158        self.window
1159            .platform_window
1160            .set_background_appearance(background_appearance);
1161    }
1162
1163    /// Mark the window as dirty at the platform level.
1164    pub fn set_window_edited(&mut self, edited: bool) {
1165        self.window.platform_window.set_edited(edited);
1166    }
1167
1168    /// Determine the display on which the window is visible.
1169    pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1170        self.platform
1171            .displays()
1172            .into_iter()
1173            .find(|display| display.id() == self.window.display_id)
1174    }
1175
1176    /// Show the platform character palette.
1177    pub fn show_character_palette(&self) {
1178        self.window.platform_window.show_character_palette();
1179    }
1180
1181    /// The scale factor of the display associated with the window. For example, it could
1182    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
1183    /// be rendered as two pixels on screen.
1184    pub fn scale_factor(&self) -> f32 {
1185        self.window.scale_factor
1186    }
1187
1188    /// The size of an em for the base font of the application. Adjusting this value allows the
1189    /// UI to scale, just like zooming a web page.
1190    pub fn rem_size(&self) -> Pixels {
1191        self.window.rem_size
1192    }
1193
1194    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
1195    /// UI to scale, just like zooming a web page.
1196    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
1197        self.window.rem_size = rem_size.into();
1198    }
1199
1200    /// The line height associated with the current text style.
1201    pub fn line_height(&self) -> Pixels {
1202        let rem_size = self.rem_size();
1203        let text_style = self.text_style();
1204        text_style
1205            .line_height
1206            .to_pixels(text_style.font_size, rem_size)
1207    }
1208
1209    /// Call to prevent the default action of an event. Currently only used to prevent
1210    /// parent elements from becoming focused on mouse down.
1211    pub fn prevent_default(&mut self) {
1212        self.window.default_prevented = true;
1213    }
1214
1215    /// Obtain whether default has been prevented for the event currently being dispatched.
1216    pub fn default_prevented(&self) -> bool {
1217        self.window.default_prevented
1218    }
1219
1220    /// Determine whether the given action is available along the dispatch path to the currently focused element.
1221    pub fn is_action_available(&self, action: &dyn Action) -> bool {
1222        let target = self
1223            .focused()
1224            .and_then(|focused_handle| {
1225                self.window
1226                    .rendered_frame
1227                    .dispatch_tree
1228                    .focusable_node_id(focused_handle.id)
1229            })
1230            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1231        self.window
1232            .rendered_frame
1233            .dispatch_tree
1234            .is_action_available(action, target)
1235    }
1236
1237    /// The position of the mouse relative to the window.
1238    pub fn mouse_position(&self) -> Point<Pixels> {
1239        self.window.mouse_position
1240    }
1241
1242    /// The current state of the keyboard's modifiers
1243    pub fn modifiers(&self) -> Modifiers {
1244        self.window.modifiers
1245    }
1246
1247    fn complete_frame(&self) {
1248        self.window.platform_window.completed_frame();
1249    }
1250
1251    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
1252    /// the contents of the new [Scene], use [present].
1253    #[profiling::function]
1254    pub fn draw(&mut self) {
1255        self.window.dirty.set(false);
1256        self.window.requested_autoscroll = None;
1257
1258        // Restore the previously-used input handler.
1259        if let Some(input_handler) = self.window.platform_window.take_input_handler() {
1260            self.window
1261                .rendered_frame
1262                .input_handlers
1263                .push(Some(input_handler));
1264        }
1265
1266        self.draw_roots();
1267        self.window.dirty_views.clear();
1268
1269        self.window
1270            .next_frame
1271            .dispatch_tree
1272            .preserve_pending_keystrokes(
1273                &mut self.window.rendered_frame.dispatch_tree,
1274                self.window.focus,
1275            );
1276        self.window.next_frame.focus = self.window.focus;
1277        self.window.next_frame.window_active = self.window.active.get();
1278
1279        // Register requested input handler with the platform window.
1280        if let Some(input_handler) = self.window.next_frame.input_handlers.pop() {
1281            self.window
1282                .platform_window
1283                .set_input_handler(input_handler.unwrap());
1284        }
1285
1286        self.window.layout_engine.as_mut().unwrap().clear();
1287        self.text_system().finish_frame();
1288        self.window
1289            .next_frame
1290            .finish(&mut self.window.rendered_frame);
1291        ELEMENT_ARENA.with_borrow_mut(|element_arena| {
1292            let percentage = (element_arena.len() as f32 / element_arena.capacity() as f32) * 100.;
1293            if percentage >= 80. {
1294                log::warn!("elevated element arena occupation: {}.", percentage);
1295            }
1296            element_arena.clear();
1297        });
1298
1299        self.window.draw_phase = DrawPhase::Focus;
1300        let previous_focus_path = self.window.rendered_frame.focus_path();
1301        let previous_window_active = self.window.rendered_frame.window_active;
1302        mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1303        self.window.next_frame.clear();
1304        let current_focus_path = self.window.rendered_frame.focus_path();
1305        let current_window_active = self.window.rendered_frame.window_active;
1306
1307        if previous_focus_path != current_focus_path
1308            || previous_window_active != current_window_active
1309        {
1310            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1311                self.window
1312                    .focus_lost_listeners
1313                    .clone()
1314                    .retain(&(), |listener| listener(self));
1315            }
1316
1317            let event = FocusEvent {
1318                previous_focus_path: if previous_window_active {
1319                    previous_focus_path
1320                } else {
1321                    Default::default()
1322                },
1323                current_focus_path: if current_window_active {
1324                    current_focus_path
1325                } else {
1326                    Default::default()
1327                },
1328            };
1329            self.window
1330                .focus_listeners
1331                .clone()
1332                .retain(&(), |listener| listener(&event, self));
1333        }
1334
1335        self.reset_cursor_style();
1336        self.window.refreshing = false;
1337        self.window.draw_phase = DrawPhase::None;
1338        self.window.needs_present.set(true);
1339    }
1340
1341    #[profiling::function]
1342    fn present(&self) {
1343        self.window
1344            .platform_window
1345            .draw(&self.window.rendered_frame.scene);
1346        self.window.needs_present.set(false);
1347        profiling::finish_frame!();
1348    }
1349
1350    fn draw_roots(&mut self) {
1351        self.window.draw_phase = DrawPhase::Prepaint;
1352        self.window.tooltip_bounds.take();
1353
1354        // Layout all root elements.
1355        let mut root_element = self.window.root_view.as_ref().unwrap().clone().into_any();
1356        root_element.prepaint_as_root(Point::default(), self.window.viewport_size.into(), self);
1357
1358        let mut sorted_deferred_draws =
1359            (0..self.window.next_frame.deferred_draws.len()).collect::<SmallVec<[_; 8]>>();
1360        sorted_deferred_draws.sort_by_key(|ix| self.window.next_frame.deferred_draws[*ix].priority);
1361        self.prepaint_deferred_draws(&sorted_deferred_draws);
1362
1363        let mut prompt_element = None;
1364        let mut active_drag_element = None;
1365        let mut tooltip_element = None;
1366        if let Some(prompt) = self.window.prompt.take() {
1367            let mut element = prompt.view.any_view().into_any();
1368            element.prepaint_as_root(Point::default(), self.window.viewport_size.into(), self);
1369            prompt_element = Some(element);
1370            self.window.prompt = Some(prompt);
1371        } else if let Some(active_drag) = self.app.active_drag.take() {
1372            let mut element = active_drag.view.clone().into_any();
1373            let offset = self.mouse_position() - active_drag.cursor_offset;
1374            element.prepaint_as_root(offset, AvailableSpace::min_size(), self);
1375            active_drag_element = Some(element);
1376            self.app.active_drag = Some(active_drag);
1377        } else {
1378            tooltip_element = self.prepaint_tooltip();
1379        }
1380
1381        self.window.mouse_hit_test = self.window.next_frame.hit_test(self.window.mouse_position);
1382
1383        // Now actually paint the elements.
1384        self.window.draw_phase = DrawPhase::Paint;
1385        root_element.paint(self);
1386
1387        self.paint_deferred_draws(&sorted_deferred_draws);
1388
1389        if let Some(mut prompt_element) = prompt_element {
1390            prompt_element.paint(self)
1391        } else if let Some(mut drag_element) = active_drag_element {
1392            drag_element.paint(self);
1393        } else if let Some(mut tooltip_element) = tooltip_element {
1394            tooltip_element.paint(self);
1395        }
1396    }
1397
1398    fn prepaint_tooltip(&mut self) -> Option<AnyElement> {
1399        let tooltip_request = self.window.next_frame.tooltip_requests.last().cloned()?;
1400        let tooltip_request = tooltip_request.unwrap();
1401        let mut element = tooltip_request.tooltip.view.clone().into_any();
1402        let mouse_position = tooltip_request.tooltip.mouse_position;
1403        let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self);
1404
1405        let mut tooltip_bounds = Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
1406        let window_bounds = Bounds {
1407            origin: Point::default(),
1408            size: self.viewport_size(),
1409        };
1410
1411        if tooltip_bounds.right() > window_bounds.right() {
1412            let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
1413            if new_x >= Pixels::ZERO {
1414                tooltip_bounds.origin.x = new_x;
1415            } else {
1416                tooltip_bounds.origin.x = cmp::max(
1417                    Pixels::ZERO,
1418                    tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
1419                );
1420            }
1421        }
1422
1423        if tooltip_bounds.bottom() > window_bounds.bottom() {
1424            let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
1425            if new_y >= Pixels::ZERO {
1426                tooltip_bounds.origin.y = new_y;
1427            } else {
1428                tooltip_bounds.origin.y = cmp::max(
1429                    Pixels::ZERO,
1430                    tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
1431                );
1432            }
1433        }
1434
1435        self.with_absolute_element_offset(tooltip_bounds.origin, |cx| element.prepaint(cx));
1436
1437        self.window.tooltip_bounds = Some(TooltipBounds {
1438            id: tooltip_request.id,
1439            bounds: tooltip_bounds,
1440        });
1441        Some(element)
1442    }
1443
1444    fn prepaint_deferred_draws(&mut self, deferred_draw_indices: &[usize]) {
1445        assert_eq!(self.window.element_id_stack.len(), 0);
1446
1447        let mut deferred_draws = mem::take(&mut self.window.next_frame.deferred_draws);
1448        for deferred_draw_ix in deferred_draw_indices {
1449            let deferred_draw = &mut deferred_draws[*deferred_draw_ix];
1450            self.window
1451                .element_id_stack
1452                .clone_from(&deferred_draw.element_id_stack);
1453            self.window
1454                .text_style_stack
1455                .clone_from(&deferred_draw.text_style_stack);
1456            self.window
1457                .next_frame
1458                .dispatch_tree
1459                .set_active_node(deferred_draw.parent_node);
1460
1461            let prepaint_start = self.prepaint_index();
1462            if let Some(element) = deferred_draw.element.as_mut() {
1463                self.with_absolute_element_offset(deferred_draw.absolute_offset, |cx| {
1464                    element.prepaint(cx)
1465                });
1466            } else {
1467                self.reuse_prepaint(deferred_draw.prepaint_range.clone());
1468            }
1469            let prepaint_end = self.prepaint_index();
1470            deferred_draw.prepaint_range = prepaint_start..prepaint_end;
1471        }
1472        assert_eq!(
1473            self.window.next_frame.deferred_draws.len(),
1474            0,
1475            "cannot call defer_draw during deferred drawing"
1476        );
1477        self.window.next_frame.deferred_draws = deferred_draws;
1478        self.window.element_id_stack.clear();
1479        self.window.text_style_stack.clear();
1480    }
1481
1482    fn paint_deferred_draws(&mut self, deferred_draw_indices: &[usize]) {
1483        assert_eq!(self.window.element_id_stack.len(), 0);
1484
1485        let mut deferred_draws = mem::take(&mut self.window.next_frame.deferred_draws);
1486        for deferred_draw_ix in deferred_draw_indices {
1487            let mut deferred_draw = &mut deferred_draws[*deferred_draw_ix];
1488            self.window
1489                .element_id_stack
1490                .clone_from(&deferred_draw.element_id_stack);
1491            self.window
1492                .next_frame
1493                .dispatch_tree
1494                .set_active_node(deferred_draw.parent_node);
1495
1496            let paint_start = self.paint_index();
1497            if let Some(element) = deferred_draw.element.as_mut() {
1498                element.paint(self);
1499            } else {
1500                self.reuse_paint(deferred_draw.paint_range.clone());
1501            }
1502            let paint_end = self.paint_index();
1503            deferred_draw.paint_range = paint_start..paint_end;
1504        }
1505        self.window.next_frame.deferred_draws = deferred_draws;
1506        self.window.element_id_stack.clear();
1507    }
1508
1509    pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
1510        PrepaintStateIndex {
1511            hitboxes_index: self.window.next_frame.hitboxes.len(),
1512            tooltips_index: self.window.next_frame.tooltip_requests.len(),
1513            deferred_draws_index: self.window.next_frame.deferred_draws.len(),
1514            dispatch_tree_index: self.window.next_frame.dispatch_tree.len(),
1515            accessed_element_states_index: self.window.next_frame.accessed_element_states.len(),
1516            line_layout_index: self.window.text_system.layout_index(),
1517        }
1518    }
1519
1520    pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
1521        let window = &mut self.window;
1522        window.next_frame.hitboxes.extend(
1523            window.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
1524                .iter()
1525                .cloned(),
1526        );
1527        window.next_frame.tooltip_requests.extend(
1528            window.rendered_frame.tooltip_requests
1529                [range.start.tooltips_index..range.end.tooltips_index]
1530                .iter_mut()
1531                .map(|request| request.take()),
1532        );
1533        window.next_frame.accessed_element_states.extend(
1534            window.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
1535                ..range.end.accessed_element_states_index]
1536                .iter()
1537                .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
1538        );
1539        window
1540            .text_system
1541            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
1542
1543        let reused_subtree = window.next_frame.dispatch_tree.reuse_subtree(
1544            range.start.dispatch_tree_index..range.end.dispatch_tree_index,
1545            &mut window.rendered_frame.dispatch_tree,
1546        );
1547        window.next_frame.deferred_draws.extend(
1548            window.rendered_frame.deferred_draws
1549                [range.start.deferred_draws_index..range.end.deferred_draws_index]
1550                .iter()
1551                .map(|deferred_draw| DeferredDraw {
1552                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
1553                    element_id_stack: deferred_draw.element_id_stack.clone(),
1554                    text_style_stack: deferred_draw.text_style_stack.clone(),
1555                    priority: deferred_draw.priority,
1556                    element: None,
1557                    absolute_offset: deferred_draw.absolute_offset,
1558                    prepaint_range: deferred_draw.prepaint_range.clone(),
1559                    paint_range: deferred_draw.paint_range.clone(),
1560                }),
1561        );
1562    }
1563
1564    pub(crate) fn paint_index(&self) -> PaintIndex {
1565        PaintIndex {
1566            scene_index: self.window.next_frame.scene.len(),
1567            mouse_listeners_index: self.window.next_frame.mouse_listeners.len(),
1568            input_handlers_index: self.window.next_frame.input_handlers.len(),
1569            cursor_styles_index: self.window.next_frame.cursor_styles.len(),
1570            accessed_element_states_index: self.window.next_frame.accessed_element_states.len(),
1571            line_layout_index: self.window.text_system.layout_index(),
1572        }
1573    }
1574
1575    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
1576        let window = &mut self.window;
1577
1578        window.next_frame.cursor_styles.extend(
1579            window.rendered_frame.cursor_styles
1580                [range.start.cursor_styles_index..range.end.cursor_styles_index]
1581                .iter()
1582                .cloned(),
1583        );
1584        window.next_frame.input_handlers.extend(
1585            window.rendered_frame.input_handlers
1586                [range.start.input_handlers_index..range.end.input_handlers_index]
1587                .iter_mut()
1588                .map(|handler| handler.take()),
1589        );
1590        window.next_frame.mouse_listeners.extend(
1591            window.rendered_frame.mouse_listeners
1592                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
1593                .iter_mut()
1594                .map(|listener| listener.take()),
1595        );
1596        window.next_frame.accessed_element_states.extend(
1597            window.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
1598                ..range.end.accessed_element_states_index]
1599                .iter()
1600                .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
1601        );
1602        window
1603            .text_system
1604            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
1605        window.next_frame.scene.replay(
1606            range.start.scene_index..range.end.scene_index,
1607            &window.rendered_frame.scene,
1608        );
1609    }
1610
1611    /// Push a text style onto the stack, and call a function with that style active.
1612    /// Use [`AppContext::text_style`] to get the current, combined text style. This method
1613    /// should only be called as part of element drawing.
1614    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
1615    where
1616        F: FnOnce(&mut Self) -> R,
1617    {
1618        debug_assert!(
1619            matches!(
1620                self.window.draw_phase,
1621                DrawPhase::Prepaint | DrawPhase::Paint
1622            ),
1623            "this method can only be called during request_layout, prepaint, or paint"
1624        );
1625        if let Some(style) = style {
1626            self.window.text_style_stack.push(style);
1627            let result = f(self);
1628            self.window.text_style_stack.pop();
1629            result
1630        } else {
1631            f(self)
1632        }
1633    }
1634
1635    /// Updates the cursor style at the platform level. This method should only be called
1636    /// during the prepaint phase of element drawing.
1637    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
1638        debug_assert_eq!(
1639            self.window.draw_phase,
1640            DrawPhase::Paint,
1641            "this method can only be called during paint"
1642        );
1643        self.window
1644            .next_frame
1645            .cursor_styles
1646            .push(CursorStyleRequest {
1647                hitbox_id: hitbox.id,
1648                style,
1649            });
1650    }
1651
1652    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
1653    /// during the paint phase of element drawing.
1654    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
1655        debug_assert_eq!(
1656            self.window.draw_phase,
1657            DrawPhase::Prepaint,
1658            "this method can only be called during prepaint"
1659        );
1660        let id = TooltipId(post_inc(&mut self.window.next_tooltip_id.0));
1661        self.window
1662            .next_frame
1663            .tooltip_requests
1664            .push(Some(TooltipRequest { id, tooltip }));
1665        id
1666    }
1667
1668    /// Invoke the given function with the given content mask after intersecting it
1669    /// with the current mask. This method should only be called during element drawing.
1670    pub fn with_content_mask<R>(
1671        &mut self,
1672        mask: Option<ContentMask<Pixels>>,
1673        f: impl FnOnce(&mut Self) -> R,
1674    ) -> R {
1675        debug_assert!(
1676            matches!(
1677                self.window.draw_phase,
1678                DrawPhase::Prepaint | DrawPhase::Paint
1679            ),
1680            "this method can only be called during request_layout, prepaint, or paint"
1681        );
1682        if let Some(mask) = mask {
1683            let mask = mask.intersect(&self.content_mask());
1684            self.window_mut().content_mask_stack.push(mask);
1685            let result = f(self);
1686            self.window_mut().content_mask_stack.pop();
1687            result
1688        } else {
1689            f(self)
1690        }
1691    }
1692
1693    /// Updates the global element offset relative to the current offset. This is used to implement
1694    /// scrolling. This method should only be called during the prepaint phase of element drawing.
1695    pub fn with_element_offset<R>(
1696        &mut self,
1697        offset: Point<Pixels>,
1698        f: impl FnOnce(&mut Self) -> R,
1699    ) -> R {
1700        debug_assert_eq!(
1701            self.window.draw_phase,
1702            DrawPhase::Prepaint,
1703            "this method can only be called during request_layout, or prepaint"
1704        );
1705
1706        if offset.is_zero() {
1707            return f(self);
1708        };
1709
1710        let abs_offset = self.element_offset() + offset;
1711        self.with_absolute_element_offset(abs_offset, f)
1712    }
1713
1714    /// Updates the global element offset based on the given offset. This is used to implement
1715    /// drag handles and other manual painting of elements. This method should only be called during
1716    /// the prepaint phase of element drawing.
1717    pub fn with_absolute_element_offset<R>(
1718        &mut self,
1719        offset: Point<Pixels>,
1720        f: impl FnOnce(&mut Self) -> R,
1721    ) -> R {
1722        debug_assert_eq!(
1723            self.window.draw_phase,
1724            DrawPhase::Prepaint,
1725            "this method can only be called during request_layout, or prepaint"
1726        );
1727        self.window_mut().element_offset_stack.push(offset);
1728        let result = f(self);
1729        self.window_mut().element_offset_stack.pop();
1730        result
1731    }
1732
1733    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
1734    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
1735    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
1736    /// element offset and prepaint again. See [`List`] for an example. This method should only be
1737    /// called during the prepaint phase of element drawing.
1738    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
1739        debug_assert_eq!(
1740            self.window.draw_phase,
1741            DrawPhase::Prepaint,
1742            "this method can only be called during prepaint"
1743        );
1744        let index = self.prepaint_index();
1745        let result = f(self);
1746        if result.is_err() {
1747            self.window
1748                .next_frame
1749                .hitboxes
1750                .truncate(index.hitboxes_index);
1751            self.window
1752                .next_frame
1753                .tooltip_requests
1754                .truncate(index.tooltips_index);
1755            self.window
1756                .next_frame
1757                .deferred_draws
1758                .truncate(index.deferred_draws_index);
1759            self.window
1760                .next_frame
1761                .dispatch_tree
1762                .truncate(index.dispatch_tree_index);
1763            self.window
1764                .next_frame
1765                .accessed_element_states
1766                .truncate(index.accessed_element_states_index);
1767            self.window
1768                .text_system
1769                .truncate_layouts(index.line_layout_index);
1770        }
1771        result
1772    }
1773
1774    /// When you call this method during [`prepaint`], containing elements will attempt to
1775    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
1776    /// [`prepaint`] again with a new set of bounds. See [`List`] for an example of an element
1777    /// that supports this method being called on the elements it contains. This method should only be
1778    /// called during the prepaint phase of element drawing.
1779    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
1780        debug_assert_eq!(
1781            self.window.draw_phase,
1782            DrawPhase::Prepaint,
1783            "this method can only be called during prepaint"
1784        );
1785        self.window.requested_autoscroll = Some(bounds);
1786    }
1787
1788    /// This method can be called from a containing element such as [`List`] to support the autoscroll behavior
1789    /// described in [`request_autoscroll`].
1790    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
1791        debug_assert_eq!(
1792            self.window.draw_phase,
1793            DrawPhase::Prepaint,
1794            "this method can only be called during prepaint"
1795        );
1796        self.window.requested_autoscroll.take()
1797    }
1798
1799    /// Remove an asset from GPUI's cache
1800    pub fn remove_cached_asset<A: Asset + 'static>(
1801        &mut self,
1802        source: &A::Source,
1803    ) -> Option<A::Output> {
1804        self.asset_cache.remove::<A>(source)
1805    }
1806
1807    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1808    /// Your view will be re-drawn once the asset has finished loading.
1809    ///
1810    /// Note that the multiple calls to this method will only result in one `Asset::load` call.
1811    /// The results of that call will be cached, and returned on subsequent uses of this API.
1812    ///
1813    /// Use [Self::remove_cached_asset] to reload your asset.
1814    pub fn use_cached_asset<A: Asset + 'static>(
1815        &mut self,
1816        source: &A::Source,
1817    ) -> Option<A::Output> {
1818        self.asset_cache.get::<A>(source).or_else(|| {
1819            if let Some(asset) = self.use_asset::<A>(source) {
1820                self.asset_cache
1821                    .insert::<A>(source.to_owned(), asset.clone());
1822                Some(asset)
1823            } else {
1824                None
1825            }
1826        })
1827    }
1828
1829    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1830    /// Your view will be re-drawn once the asset has finished loading.
1831    ///
1832    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
1833    /// time.
1834    ///
1835    /// This asset will not be cached by default, see [Self::use_cached_asset]
1836    pub fn use_asset<A: Asset + 'static>(&mut self, source: &A::Source) -> Option<A::Output> {
1837        let asset_id = (TypeId::of::<A>(), hash(source));
1838        let mut is_first = false;
1839        let task = self
1840            .loading_assets
1841            .remove(&asset_id)
1842            .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
1843            .unwrap_or_else(|| {
1844                is_first = true;
1845                let future = A::load(source.clone(), self);
1846                let task = self.background_executor().spawn(future).shared();
1847                task
1848            });
1849
1850        task.clone().now_or_never().or_else(|| {
1851            if is_first {
1852                let parent_id = self.parent_view_id();
1853                self.spawn({
1854                    let task = task.clone();
1855                    |mut cx| async move {
1856                        task.await;
1857
1858                        cx.on_next_frame(move |cx| {
1859                            if let Some(parent_id) = parent_id {
1860                                cx.notify(parent_id)
1861                            } else {
1862                                cx.refresh()
1863                            }
1864                        });
1865                    }
1866                })
1867                .detach();
1868            }
1869
1870            self.loading_assets.insert(asset_id, Box::new(task));
1871
1872            None
1873        })
1874    }
1875
1876    /// Obtain the current element offset. This method should only be called during the
1877    /// prepaint phase of element drawing.
1878    pub fn element_offset(&self) -> Point<Pixels> {
1879        debug_assert_eq!(
1880            self.window.draw_phase,
1881            DrawPhase::Prepaint,
1882            "this method can only be called during prepaint"
1883        );
1884        self.window()
1885            .element_offset_stack
1886            .last()
1887            .copied()
1888            .unwrap_or_default()
1889    }
1890
1891    /// Obtain the current content mask. This method should only be called during element drawing.
1892    pub fn content_mask(&self) -> ContentMask<Pixels> {
1893        debug_assert!(
1894            matches!(
1895                self.window.draw_phase,
1896                DrawPhase::Prepaint | DrawPhase::Paint
1897            ),
1898            "this method can only be called during prepaint, or paint"
1899        );
1900        self.window()
1901            .content_mask_stack
1902            .last()
1903            .cloned()
1904            .unwrap_or_else(|| ContentMask {
1905                bounds: Bounds {
1906                    origin: Point::default(),
1907                    size: self.window().viewport_size,
1908                },
1909            })
1910    }
1911
1912    /// Provide elements in the called function with a new namespace in which their identiers must be unique.
1913    /// This can be used within a custom element to distinguish multiple sets of child elements.
1914    pub fn with_element_namespace<R>(
1915        &mut self,
1916        element_id: impl Into<ElementId>,
1917        f: impl FnOnce(&mut Self) -> R,
1918    ) -> R {
1919        self.window.element_id_stack.push(element_id.into());
1920        let result = f(self);
1921        self.window.element_id_stack.pop();
1922        result
1923    }
1924
1925    /// Updates or initializes state for an element with the given id that lives across multiple
1926    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
1927    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1928    /// when drawing the next frame. This method should only be called as part of element drawing.
1929    pub fn with_element_state<S, R>(
1930        &mut self,
1931        global_id: &GlobalElementId,
1932        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1933    ) -> R
1934    where
1935        S: 'static,
1936    {
1937        debug_assert!(
1938            matches!(
1939                self.window.draw_phase,
1940                DrawPhase::Prepaint | DrawPhase::Paint
1941            ),
1942            "this method can only be called during request_layout, prepaint, or paint"
1943        );
1944
1945        let key = (GlobalElementId(global_id.0.clone()), TypeId::of::<S>());
1946        self.window
1947            .next_frame
1948            .accessed_element_states
1949            .push((GlobalElementId(key.0.clone()), TypeId::of::<S>()));
1950
1951        if let Some(any) = self
1952            .window
1953            .next_frame
1954            .element_states
1955            .remove(&key)
1956            .or_else(|| self.window.rendered_frame.element_states.remove(&key))
1957        {
1958            let ElementStateBox {
1959                inner,
1960                #[cfg(debug_assertions)]
1961                type_name,
1962            } = any;
1963            // Using the extra inner option to avoid needing to reallocate a new box.
1964            let mut state_box = inner
1965                .downcast::<Option<S>>()
1966                .map_err(|_| {
1967                    #[cfg(debug_assertions)]
1968                    {
1969                        anyhow::anyhow!(
1970                            "invalid element state type for id, requested {:?}, actual: {:?}",
1971                            std::any::type_name::<S>(),
1972                            type_name
1973                        )
1974                    }
1975
1976                    #[cfg(not(debug_assertions))]
1977                    {
1978                        anyhow::anyhow!(
1979                            "invalid element state type for id, requested {:?}",
1980                            std::any::type_name::<S>(),
1981                        )
1982                    }
1983                })
1984                .unwrap();
1985
1986            let state = state_box.take().expect(
1987                "reentrant call to with_element_state for the same state type and element id",
1988            );
1989            let (result, state) = f(Some(state), self);
1990            state_box.replace(state);
1991            self.window.next_frame.element_states.insert(
1992                key,
1993                ElementStateBox {
1994                    inner: state_box,
1995                    #[cfg(debug_assertions)]
1996                    type_name,
1997                },
1998            );
1999            result
2000        } else {
2001            let (result, state) = f(None, self);
2002            self.window.next_frame.element_states.insert(
2003                key,
2004                ElementStateBox {
2005                    inner: Box::new(Some(state)),
2006                    #[cfg(debug_assertions)]
2007                    type_name: std::any::type_name::<S>(),
2008                },
2009            );
2010            result
2011        }
2012    }
2013
2014    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
2015    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
2016    /// when the element is guaranteed to have an id.
2017    pub fn with_optional_element_state<S, R>(
2018        &mut self,
2019        global_id: Option<&GlobalElementId>,
2020        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
2021    ) -> R
2022    where
2023        S: 'static,
2024    {
2025        debug_assert!(
2026            matches!(
2027                self.window.draw_phase,
2028                DrawPhase::Prepaint | DrawPhase::Paint
2029            ),
2030            "this method can only be called during request_layout, prepaint, or paint"
2031        );
2032
2033        if let Some(global_id) = global_id {
2034            self.with_element_state(global_id, |state, cx| {
2035                let (result, state) = f(Some(state), cx);
2036                let state =
2037                    state.expect("you must return some state when you pass some element id");
2038                (result, state)
2039            })
2040        } else {
2041            let (result, state) = f(None, self);
2042            debug_assert!(
2043                state.is_none(),
2044                "you must not return an element state when passing None for the global id"
2045            );
2046            result
2047        }
2048    }
2049
2050    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
2051    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
2052    /// with higher values being drawn on top.
2053    ///
2054    /// This method should only be called as part of the prepaint phase of element drawing.
2055    pub fn defer_draw(
2056        &mut self,
2057        element: AnyElement,
2058        absolute_offset: Point<Pixels>,
2059        priority: usize,
2060    ) {
2061        let window = &mut self.window;
2062        debug_assert_eq!(
2063            window.draw_phase,
2064            DrawPhase::Prepaint,
2065            "this method can only be called during request_layout or prepaint"
2066        );
2067        let parent_node = window.next_frame.dispatch_tree.active_node_id().unwrap();
2068        window.next_frame.deferred_draws.push(DeferredDraw {
2069            parent_node,
2070            element_id_stack: window.element_id_stack.clone(),
2071            text_style_stack: window.text_style_stack.clone(),
2072            priority,
2073            element: Some(element),
2074            absolute_offset,
2075            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
2076            paint_range: PaintIndex::default()..PaintIndex::default(),
2077        });
2078    }
2079
2080    /// Creates a new painting layer for the specified bounds. A "layer" is a batch
2081    /// of geometry that are non-overlapping and have the same draw order. This is typically used
2082    /// for performance reasons.
2083    ///
2084    /// This method should only be called as part of the paint phase of element drawing.
2085    pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
2086        debug_assert_eq!(
2087            self.window.draw_phase,
2088            DrawPhase::Paint,
2089            "this method can only be called during paint"
2090        );
2091
2092        let scale_factor = self.scale_factor();
2093        let content_mask = self.content_mask();
2094        let clipped_bounds = bounds.intersect(&content_mask.bounds);
2095        if !clipped_bounds.is_empty() {
2096            self.window
2097                .next_frame
2098                .scene
2099                .push_layer(clipped_bounds.scale(scale_factor));
2100        }
2101
2102        let result = f(self);
2103
2104        if !clipped_bounds.is_empty() {
2105            self.window.next_frame.scene.pop_layer();
2106        }
2107
2108        result
2109    }
2110
2111    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
2112    ///
2113    /// This method should only be called as part of the paint phase of element drawing.
2114    pub fn paint_shadows(
2115        &mut self,
2116        bounds: Bounds<Pixels>,
2117        corner_radii: Corners<Pixels>,
2118        shadows: &[BoxShadow],
2119    ) {
2120        debug_assert_eq!(
2121            self.window.draw_phase,
2122            DrawPhase::Paint,
2123            "this method can only be called during paint"
2124        );
2125
2126        let scale_factor = self.scale_factor();
2127        let content_mask = self.content_mask();
2128        for shadow in shadows {
2129            let mut shadow_bounds = bounds;
2130            shadow_bounds.origin += shadow.offset;
2131            shadow_bounds.dilate(shadow.spread_radius);
2132            self.window.next_frame.scene.insert_primitive(Shadow {
2133                order: 0,
2134                blur_radius: shadow.blur_radius.scale(scale_factor),
2135                bounds: shadow_bounds.scale(scale_factor),
2136                content_mask: content_mask.scale(scale_factor),
2137                corner_radii: corner_radii.scale(scale_factor),
2138                color: shadow.color,
2139            });
2140        }
2141    }
2142
2143    /// Paint one or more quads into the scene for the next frame at the current stacking context.
2144    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
2145    /// see [`fill`](crate::fill), [`outline`](crate::outline), and [`quad`](crate::quad) to construct this type.
2146    ///
2147    /// This method should only be called as part of the paint phase of element drawing.
2148    pub fn paint_quad(&mut self, quad: PaintQuad) {
2149        debug_assert_eq!(
2150            self.window.draw_phase,
2151            DrawPhase::Paint,
2152            "this method can only be called during paint"
2153        );
2154
2155        let scale_factor = self.scale_factor();
2156        let content_mask = self.content_mask();
2157        self.window.next_frame.scene.insert_primitive(Quad {
2158            order: 0,
2159            pad: 0,
2160            bounds: quad.bounds.scale(scale_factor),
2161            content_mask: content_mask.scale(scale_factor),
2162            background: quad.background,
2163            border_color: quad.border_color,
2164            corner_radii: quad.corner_radii.scale(scale_factor),
2165            border_widths: quad.border_widths.scale(scale_factor),
2166        });
2167    }
2168
2169    /// Paint the given `Path` into the scene for the next frame at the current z-index.
2170    ///
2171    /// This method should only be called as part of the paint phase of element drawing.
2172    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
2173        debug_assert_eq!(
2174            self.window.draw_phase,
2175            DrawPhase::Paint,
2176            "this method can only be called during paint"
2177        );
2178
2179        let scale_factor = self.scale_factor();
2180        let content_mask = self.content_mask();
2181        path.content_mask = content_mask;
2182        path.color = color.into();
2183        self.window
2184            .next_frame
2185            .scene
2186            .insert_primitive(path.scale(scale_factor));
2187    }
2188
2189    /// Paint an underline into the scene for the next frame at the current z-index.
2190    ///
2191    /// This method should only be called as part of the paint phase of element drawing.
2192    pub fn paint_underline(
2193        &mut self,
2194        origin: Point<Pixels>,
2195        width: Pixels,
2196        style: &UnderlineStyle,
2197    ) {
2198        debug_assert_eq!(
2199            self.window.draw_phase,
2200            DrawPhase::Paint,
2201            "this method can only be called during paint"
2202        );
2203
2204        let scale_factor = self.scale_factor();
2205        let height = if style.wavy {
2206            style.thickness * 3.
2207        } else {
2208            style.thickness
2209        };
2210        let bounds = Bounds {
2211            origin,
2212            size: size(width, height),
2213        };
2214        let content_mask = self.content_mask();
2215
2216        self.window.next_frame.scene.insert_primitive(Underline {
2217            order: 0,
2218            pad: 0,
2219            bounds: bounds.scale(scale_factor),
2220            content_mask: content_mask.scale(scale_factor),
2221            color: style.color.unwrap_or_default(),
2222            thickness: style.thickness.scale(scale_factor),
2223            wavy: style.wavy,
2224        });
2225    }
2226
2227    /// Paint a strikethrough into the scene for the next frame at the current z-index.
2228    ///
2229    /// This method should only be called as part of the paint phase of element drawing.
2230    pub fn paint_strikethrough(
2231        &mut self,
2232        origin: Point<Pixels>,
2233        width: Pixels,
2234        style: &StrikethroughStyle,
2235    ) {
2236        debug_assert_eq!(
2237            self.window.draw_phase,
2238            DrawPhase::Paint,
2239            "this method can only be called during paint"
2240        );
2241
2242        let scale_factor = self.scale_factor();
2243        let height = style.thickness;
2244        let bounds = Bounds {
2245            origin,
2246            size: size(width, height),
2247        };
2248        let content_mask = self.content_mask();
2249
2250        self.window.next_frame.scene.insert_primitive(Underline {
2251            order: 0,
2252            pad: 0,
2253            bounds: bounds.scale(scale_factor),
2254            content_mask: content_mask.scale(scale_factor),
2255            thickness: style.thickness.scale(scale_factor),
2256            color: style.color.unwrap_or_default(),
2257            wavy: false,
2258        });
2259    }
2260
2261    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
2262    ///
2263    /// The y component of the origin is the baseline of the glyph.
2264    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2265    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2266    /// This method is only useful if you need to paint a single glyph that has already been shaped.
2267    ///
2268    /// This method should only be called as part of the paint phase of element drawing.
2269    pub fn paint_glyph(
2270        &mut self,
2271        origin: Point<Pixels>,
2272        font_id: FontId,
2273        glyph_id: GlyphId,
2274        font_size: Pixels,
2275        color: Hsla,
2276    ) -> Result<()> {
2277        debug_assert_eq!(
2278            self.window.draw_phase,
2279            DrawPhase::Paint,
2280            "this method can only be called during paint"
2281        );
2282
2283        let scale_factor = self.scale_factor();
2284        let glyph_origin = origin.scale(scale_factor);
2285        let subpixel_variant = Point {
2286            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2287            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2288        };
2289        let params = RenderGlyphParams {
2290            font_id,
2291            glyph_id,
2292            font_size,
2293            subpixel_variant,
2294            scale_factor,
2295            is_emoji: false,
2296        };
2297
2298        let raster_bounds = self.text_system().raster_bounds(&params)?;
2299        if !raster_bounds.is_zero() {
2300            let tile =
2301                self.window
2302                    .sprite_atlas
2303                    .get_or_insert_with(&params.clone().into(), &mut || {
2304                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
2305                        Ok((size, Cow::Owned(bytes)))
2306                    })?;
2307            let bounds = Bounds {
2308                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2309                size: tile.bounds.size.map(Into::into),
2310            };
2311            let content_mask = self.content_mask().scale(scale_factor);
2312            self.window
2313                .next_frame
2314                .scene
2315                .insert_primitive(MonochromeSprite {
2316                    order: 0,
2317                    pad: 0,
2318                    bounds,
2319                    content_mask,
2320                    color,
2321                    tile,
2322                    transformation: TransformationMatrix::unit(),
2323                });
2324        }
2325        Ok(())
2326    }
2327
2328    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
2329    ///
2330    /// The y component of the origin is the baseline of the glyph.
2331    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2332    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2333    /// This method is only useful if you need to paint a single emoji that has already been shaped.
2334    ///
2335    /// This method should only be called as part of the paint phase of element drawing.
2336    pub fn paint_emoji(
2337        &mut self,
2338        origin: Point<Pixels>,
2339        font_id: FontId,
2340        glyph_id: GlyphId,
2341        font_size: Pixels,
2342    ) -> Result<()> {
2343        debug_assert_eq!(
2344            self.window.draw_phase,
2345            DrawPhase::Paint,
2346            "this method can only be called during paint"
2347        );
2348
2349        let scale_factor = self.scale_factor();
2350        let glyph_origin = origin.scale(scale_factor);
2351        let params = RenderGlyphParams {
2352            font_id,
2353            glyph_id,
2354            font_size,
2355            // We don't render emojis with subpixel variants.
2356            subpixel_variant: Default::default(),
2357            scale_factor,
2358            is_emoji: true,
2359        };
2360
2361        let raster_bounds = self.text_system().raster_bounds(&params)?;
2362        if !raster_bounds.is_zero() {
2363            let tile =
2364                self.window
2365                    .sprite_atlas
2366                    .get_or_insert_with(&params.clone().into(), &mut || {
2367                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
2368                        Ok((size, Cow::Owned(bytes)))
2369                    })?;
2370            let bounds = Bounds {
2371                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2372                size: tile.bounds.size.map(Into::into),
2373            };
2374            let content_mask = self.content_mask().scale(scale_factor);
2375
2376            self.window
2377                .next_frame
2378                .scene
2379                .insert_primitive(PolychromeSprite {
2380                    order: 0,
2381                    grayscale: false,
2382                    bounds,
2383                    corner_radii: Default::default(),
2384                    content_mask,
2385                    tile,
2386                });
2387        }
2388        Ok(())
2389    }
2390
2391    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
2392    ///
2393    /// This method should only be called as part of the paint phase of element drawing.
2394    pub fn paint_svg(
2395        &mut self,
2396        bounds: Bounds<Pixels>,
2397        path: SharedString,
2398        transformation: TransformationMatrix,
2399        color: Hsla,
2400    ) -> Result<()> {
2401        debug_assert_eq!(
2402            self.window.draw_phase,
2403            DrawPhase::Paint,
2404            "this method can only be called during paint"
2405        );
2406
2407        let scale_factor = self.scale_factor();
2408        let bounds = bounds.scale(scale_factor);
2409        // Render the SVG at twice the size to get a higher quality result.
2410        let params = RenderSvgParams {
2411            path,
2412            size: bounds
2413                .size
2414                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
2415        };
2416
2417        let tile =
2418            self.window
2419                .sprite_atlas
2420                .get_or_insert_with(&params.clone().into(), &mut || {
2421                    let bytes = self.svg_renderer.render(&params)?;
2422                    Ok((params.size, Cow::Owned(bytes)))
2423                })?;
2424        let content_mask = self.content_mask().scale(scale_factor);
2425
2426        self.window
2427            .next_frame
2428            .scene
2429            .insert_primitive(MonochromeSprite {
2430                order: 0,
2431                pad: 0,
2432                bounds,
2433                content_mask,
2434                color,
2435                tile,
2436                transformation,
2437            });
2438
2439        Ok(())
2440    }
2441
2442    /// Paint an image into the scene for the next frame at the current z-index.
2443    ///
2444    /// This method should only be called as part of the paint phase of element drawing.
2445    pub fn paint_image(
2446        &mut self,
2447        bounds: Bounds<Pixels>,
2448        corner_radii: Corners<Pixels>,
2449        data: Arc<ImageData>,
2450        grayscale: bool,
2451    ) -> Result<()> {
2452        debug_assert_eq!(
2453            self.window.draw_phase,
2454            DrawPhase::Paint,
2455            "this method can only be called during paint"
2456        );
2457
2458        let scale_factor = self.scale_factor();
2459        let bounds = bounds.scale(scale_factor);
2460        let params = RenderImageParams { image_id: data.id };
2461
2462        let tile = self
2463            .window
2464            .sprite_atlas
2465            .get_or_insert_with(&params.clone().into(), &mut || {
2466                Ok((data.size(), Cow::Borrowed(data.as_bytes())))
2467            })?;
2468        let content_mask = self.content_mask().scale(scale_factor);
2469        let corner_radii = corner_radii.scale(scale_factor);
2470
2471        self.window
2472            .next_frame
2473            .scene
2474            .insert_primitive(PolychromeSprite {
2475                order: 0,
2476                grayscale,
2477                bounds,
2478                content_mask,
2479                corner_radii,
2480                tile,
2481            });
2482        Ok(())
2483    }
2484
2485    /// Paint a surface into the scene for the next frame at the current z-index.
2486    ///
2487    /// This method should only be called as part of the paint phase of element drawing.
2488    #[cfg(target_os = "macos")]
2489    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
2490        debug_assert_eq!(
2491            self.window.draw_phase,
2492            DrawPhase::Paint,
2493            "this method can only be called during paint"
2494        );
2495
2496        let scale_factor = self.scale_factor();
2497        let bounds = bounds.scale(scale_factor);
2498        let content_mask = self.content_mask().scale(scale_factor);
2499        self.window
2500            .next_frame
2501            .scene
2502            .insert_primitive(crate::Surface {
2503                order: 0,
2504                bounds,
2505                content_mask,
2506                image_buffer,
2507            });
2508    }
2509
2510    #[must_use]
2511    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
2512    /// layout is being requested, along with the layout ids of any children. This method is called during
2513    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
2514    ///
2515    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2516    pub fn request_layout(
2517        &mut self,
2518        style: Style,
2519        children: impl IntoIterator<Item = LayoutId>,
2520    ) -> LayoutId {
2521        debug_assert_eq!(
2522            self.window.draw_phase,
2523            DrawPhase::Prepaint,
2524            "this method can only be called during request_layout, or prepaint"
2525        );
2526
2527        self.app.layout_id_buffer.clear();
2528        self.app.layout_id_buffer.extend(children);
2529        let rem_size = self.rem_size();
2530
2531        self.window.layout_engine.as_mut().unwrap().request_layout(
2532            style,
2533            rem_size,
2534            &self.app.layout_id_buffer,
2535        )
2536    }
2537
2538    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
2539    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
2540    /// determine the element's size. One place this is used internally is when measuring text.
2541    ///
2542    /// The given closure is invoked at layout time with the known dimensions and available space and
2543    /// returns a `Size`.
2544    ///
2545    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2546    pub fn request_measured_layout<
2547        F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
2548            + 'static,
2549    >(
2550        &mut self,
2551        style: Style,
2552        measure: F,
2553    ) -> LayoutId {
2554        debug_assert_eq!(
2555            self.window.draw_phase,
2556            DrawPhase::Prepaint,
2557            "this method can only be called during request_layout, or prepaint"
2558        );
2559
2560        let rem_size = self.rem_size();
2561        self.window
2562            .layout_engine
2563            .as_mut()
2564            .unwrap()
2565            .request_measured_layout(style, rem_size, measure)
2566    }
2567
2568    /// Compute the layout for the given id within the given available space.
2569    /// This method is called for its side effect, typically by the framework prior to painting.
2570    /// After calling it, you can request the bounds of the given layout node id or any descendant.
2571    ///
2572    /// This method should only be called as part of the prepaint phase of element drawing.
2573    pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
2574        debug_assert_eq!(
2575            self.window.draw_phase,
2576            DrawPhase::Prepaint,
2577            "this method can only be called during request_layout, or prepaint"
2578        );
2579
2580        let mut layout_engine = self.window.layout_engine.take().unwrap();
2581        layout_engine.compute_layout(layout_id, available_space, self);
2582        self.window.layout_engine = Some(layout_engine);
2583    }
2584
2585    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
2586    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
2587    ///
2588    /// This method should only be called as part of element drawing.
2589    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
2590        debug_assert_eq!(
2591            self.window.draw_phase,
2592            DrawPhase::Prepaint,
2593            "this method can only be called during request_layout, prepaint, or paint"
2594        );
2595
2596        let mut bounds = self
2597            .window
2598            .layout_engine
2599            .as_mut()
2600            .unwrap()
2601            .layout_bounds(layout_id)
2602            .map(Into::into);
2603        bounds.origin += self.element_offset();
2604        bounds
2605    }
2606
2607    /// This method should be called during `prepaint`. You can use
2608    /// the returned [Hitbox] during `paint` or in an event handler
2609    /// to determine whether the inserted hitbox was the topmost.
2610    ///
2611    /// This method should only be called as part of the prepaint phase of element drawing.
2612    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, opaque: bool) -> Hitbox {
2613        debug_assert_eq!(
2614            self.window.draw_phase,
2615            DrawPhase::Prepaint,
2616            "this method can only be called during prepaint"
2617        );
2618
2619        let content_mask = self.content_mask();
2620        let window = &mut self.window;
2621        let id = window.next_hitbox_id;
2622        window.next_hitbox_id.0 += 1;
2623        let hitbox = Hitbox {
2624            id,
2625            bounds,
2626            content_mask,
2627            opaque,
2628        };
2629        window.next_frame.hitboxes.push(hitbox.clone());
2630        hitbox
2631    }
2632
2633    /// Sets the key context for the current element. This context will be used to translate
2634    /// keybindings into actions.
2635    ///
2636    /// This method should only be called as part of the paint phase of element drawing.
2637    pub fn set_key_context(&mut self, context: KeyContext) {
2638        debug_assert_eq!(
2639            self.window.draw_phase,
2640            DrawPhase::Paint,
2641            "this method can only be called during paint"
2642        );
2643        self.window
2644            .next_frame
2645            .dispatch_tree
2646            .set_key_context(context);
2647    }
2648
2649    /// Sets the focus handle for the current element. This handle will be used to manage focus state
2650    /// and keyboard event dispatch for the element.
2651    ///
2652    /// This method should only be called as part of the paint phase of element drawing.
2653    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle) {
2654        debug_assert_eq!(
2655            self.window.draw_phase,
2656            DrawPhase::Paint,
2657            "this method can only be called during paint"
2658        );
2659        self.window
2660            .next_frame
2661            .dispatch_tree
2662            .set_focus_id(focus_handle.id);
2663    }
2664
2665    /// Sets the view id for the current element, which will be used to manage view caching.
2666    ///
2667    /// This method should only be called as part of element prepaint. We plan on removing this
2668    /// method eventually when we solve some issues that require us to construct editor elements
2669    /// directly instead of always using editors via views.
2670    pub fn set_view_id(&mut self, view_id: EntityId) {
2671        debug_assert_eq!(
2672            self.window.draw_phase,
2673            DrawPhase::Prepaint,
2674            "this method can only be called during prepaint"
2675        );
2676        self.window.next_frame.dispatch_tree.set_view_id(view_id);
2677    }
2678
2679    /// Get the last view id for the current element
2680    pub fn parent_view_id(&mut self) -> Option<EntityId> {
2681        self.window.next_frame.dispatch_tree.parent_view_id()
2682    }
2683
2684    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
2685    /// platform to receive textual input with proper integration with concerns such
2686    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
2687    /// rendered.
2688    ///
2689    /// This method should only be called as part of the paint phase of element drawing.
2690    ///
2691    /// [element_input_handler]: crate::ElementInputHandler
2692    pub fn handle_input(&mut self, focus_handle: &FocusHandle, input_handler: impl InputHandler) {
2693        debug_assert_eq!(
2694            self.window.draw_phase,
2695            DrawPhase::Paint,
2696            "this method can only be called during paint"
2697        );
2698
2699        if focus_handle.is_focused(self) {
2700            let cx = self.to_async();
2701            self.window
2702                .next_frame
2703                .input_handlers
2704                .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
2705        }
2706    }
2707
2708    /// Register a mouse event listener on the window for the next frame. The type of event
2709    /// is determined by the first parameter of the given listener. When the next frame is rendered
2710    /// the listener will be cleared.
2711    ///
2712    /// This method should only be called as part of the paint phase of element drawing.
2713    pub fn on_mouse_event<Event: MouseEvent>(
2714        &mut self,
2715        mut handler: impl FnMut(&Event, DispatchPhase, &mut WindowContext) + 'static,
2716    ) {
2717        debug_assert_eq!(
2718            self.window.draw_phase,
2719            DrawPhase::Paint,
2720            "this method can only be called during paint"
2721        );
2722
2723        self.window.next_frame.mouse_listeners.push(Some(Box::new(
2724            move |event: &dyn Any, phase: DispatchPhase, cx: &mut WindowContext<'_>| {
2725                if let Some(event) = event.downcast_ref() {
2726                    handler(event, phase, cx)
2727                }
2728            },
2729        )));
2730    }
2731
2732    /// Register a key event listener on the window for the next frame. The type of event
2733    /// is determined by the first parameter of the given listener. When the next frame is rendered
2734    /// the listener will be cleared.
2735    ///
2736    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2737    /// a specific need to register a global listener.
2738    ///
2739    /// This method should only be called as part of the paint phase of element drawing.
2740    pub fn on_key_event<Event: KeyEvent>(
2741        &mut self,
2742        listener: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
2743    ) {
2744        debug_assert_eq!(
2745            self.window.draw_phase,
2746            DrawPhase::Paint,
2747            "this method can only be called during paint"
2748        );
2749
2750        self.window.next_frame.dispatch_tree.on_key_event(Rc::new(
2751            move |event: &dyn Any, phase, cx: &mut WindowContext<'_>| {
2752                if let Some(event) = event.downcast_ref::<Event>() {
2753                    listener(event, phase, cx)
2754                }
2755            },
2756        ));
2757    }
2758
2759    /// Register a modifiers changed event listener on the window for the next frame.
2760    ///
2761    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2762    /// a specific need to register a global listener.
2763    ///
2764    /// This method should only be called as part of the paint phase of element drawing.
2765    pub fn on_modifiers_changed(
2766        &mut self,
2767        listener: impl Fn(&ModifiersChangedEvent, &mut WindowContext) + 'static,
2768    ) {
2769        debug_assert_eq!(
2770            self.window.draw_phase,
2771            DrawPhase::Paint,
2772            "this method can only be called during paint"
2773        );
2774
2775        self.window
2776            .next_frame
2777            .dispatch_tree
2778            .on_modifiers_changed(Rc::new(
2779                move |event: &ModifiersChangedEvent, cx: &mut WindowContext<'_>| {
2780                    listener(event, cx)
2781                },
2782            ));
2783    }
2784
2785    fn reset_cursor_style(&self) {
2786        // Set the cursor only if we're the active window.
2787        if self.is_window_active() {
2788            let style = self
2789                .window
2790                .rendered_frame
2791                .cursor_styles
2792                .iter()
2793                .rev()
2794                .find(|request| request.hitbox_id.is_hovered(self))
2795                .map(|request| request.style)
2796                .unwrap_or(CursorStyle::Arrow);
2797            self.platform.set_cursor_style(style);
2798        }
2799    }
2800
2801    /// Dispatch a given keystroke as though the user had typed it.
2802    /// You can create a keystroke with Keystroke::parse("").
2803    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke) -> bool {
2804        let keystroke = keystroke.with_simulated_ime();
2805        let result = self.dispatch_event(PlatformInput::KeyDown(KeyDownEvent {
2806            keystroke: keystroke.clone(),
2807            is_held: false,
2808        }));
2809        if !result.propagate {
2810            return true;
2811        }
2812
2813        if let Some(input) = keystroke.ime_key {
2814            if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
2815                input_handler.dispatch_input(&input, self);
2816                self.window.platform_window.set_input_handler(input_handler);
2817                return true;
2818            }
2819        }
2820
2821        false
2822    }
2823
2824    /// Represent this action as a key binding string, to display in the UI.
2825    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
2826        self.bindings_for_action(action)
2827            .into_iter()
2828            .next()
2829            .map(|binding| {
2830                binding
2831                    .keystrokes()
2832                    .iter()
2833                    .map(ToString::to_string)
2834                    .collect::<Vec<_>>()
2835                    .join(" ")
2836            })
2837            .unwrap_or_else(|| action.name().to_string())
2838    }
2839
2840    /// Dispatch a mouse or keyboard event on the window.
2841    #[profiling::function]
2842    pub fn dispatch_event(&mut self, event: PlatformInput) -> DispatchEventResult {
2843        self.window.last_input_timestamp.set(Instant::now());
2844        // Handlers may set this to false by calling `stop_propagation`.
2845        self.app.propagate_event = true;
2846        // Handlers may set this to true by calling `prevent_default`.
2847        self.window.default_prevented = false;
2848
2849        let event = match event {
2850            // Track the mouse position with our own state, since accessing the platform
2851            // API for the mouse position can only occur on the main thread.
2852            PlatformInput::MouseMove(mouse_move) => {
2853                self.window.mouse_position = mouse_move.position;
2854                self.window.modifiers = mouse_move.modifiers;
2855                PlatformInput::MouseMove(mouse_move)
2856            }
2857            PlatformInput::MouseDown(mouse_down) => {
2858                self.window.mouse_position = mouse_down.position;
2859                self.window.modifiers = mouse_down.modifiers;
2860                PlatformInput::MouseDown(mouse_down)
2861            }
2862            PlatformInput::MouseUp(mouse_up) => {
2863                self.window.mouse_position = mouse_up.position;
2864                self.window.modifiers = mouse_up.modifiers;
2865                PlatformInput::MouseUp(mouse_up)
2866            }
2867            PlatformInput::MouseExited(mouse_exited) => {
2868                self.window.modifiers = mouse_exited.modifiers;
2869                PlatformInput::MouseExited(mouse_exited)
2870            }
2871            PlatformInput::ModifiersChanged(modifiers_changed) => {
2872                self.window.modifiers = modifiers_changed.modifiers;
2873                PlatformInput::ModifiersChanged(modifiers_changed)
2874            }
2875            PlatformInput::ScrollWheel(scroll_wheel) => {
2876                self.window.mouse_position = scroll_wheel.position;
2877                self.window.modifiers = scroll_wheel.modifiers;
2878                PlatformInput::ScrollWheel(scroll_wheel)
2879            }
2880            // Translate dragging and dropping of external files from the operating system
2881            // to internal drag and drop events.
2882            PlatformInput::FileDrop(file_drop) => match file_drop {
2883                FileDropEvent::Entered { position, paths } => {
2884                    self.window.mouse_position = position;
2885                    if self.active_drag.is_none() {
2886                        self.active_drag = Some(AnyDrag {
2887                            value: Box::new(paths.clone()),
2888                            view: self.new_view(|_| paths).into(),
2889                            cursor_offset: position,
2890                        });
2891                    }
2892                    PlatformInput::MouseMove(MouseMoveEvent {
2893                        position,
2894                        pressed_button: Some(MouseButton::Left),
2895                        modifiers: Modifiers::default(),
2896                    })
2897                }
2898                FileDropEvent::Pending { position } => {
2899                    self.window.mouse_position = position;
2900                    PlatformInput::MouseMove(MouseMoveEvent {
2901                        position,
2902                        pressed_button: Some(MouseButton::Left),
2903                        modifiers: Modifiers::default(),
2904                    })
2905                }
2906                FileDropEvent::Submit { position } => {
2907                    self.activate(true);
2908                    self.window.mouse_position = position;
2909                    PlatformInput::MouseUp(MouseUpEvent {
2910                        button: MouseButton::Left,
2911                        position,
2912                        modifiers: Modifiers::default(),
2913                        click_count: 1,
2914                    })
2915                }
2916                FileDropEvent::Exited => {
2917                    self.active_drag.take();
2918                    PlatformInput::FileDrop(FileDropEvent::Exited)
2919                }
2920            },
2921            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
2922        };
2923
2924        if let Some(any_mouse_event) = event.mouse_event() {
2925            self.dispatch_mouse_event(any_mouse_event);
2926        } else if let Some(any_key_event) = event.keyboard_event() {
2927            self.dispatch_key_event(any_key_event);
2928        }
2929
2930        DispatchEventResult {
2931            propagate: self.app.propagate_event,
2932            default_prevented: self.window.default_prevented,
2933        }
2934    }
2935
2936    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
2937        let hit_test = self.window.rendered_frame.hit_test(self.mouse_position());
2938        if hit_test != self.window.mouse_hit_test {
2939            self.window.mouse_hit_test = hit_test;
2940            self.reset_cursor_style();
2941        }
2942
2943        let mut mouse_listeners = mem::take(&mut self.window.rendered_frame.mouse_listeners);
2944
2945        // Capture phase, events bubble from back to front. Handlers for this phase are used for
2946        // special purposes, such as detecting events outside of a given Bounds.
2947        for listener in &mut mouse_listeners {
2948            let listener = listener.as_mut().unwrap();
2949            listener(event, DispatchPhase::Capture, self);
2950            if !self.app.propagate_event {
2951                break;
2952            }
2953        }
2954
2955        // Bubble phase, where most normal handlers do their work.
2956        if self.app.propagate_event {
2957            for listener in mouse_listeners.iter_mut().rev() {
2958                let listener = listener.as_mut().unwrap();
2959                listener(event, DispatchPhase::Bubble, self);
2960                if !self.app.propagate_event {
2961                    break;
2962                }
2963            }
2964        }
2965
2966        self.window.rendered_frame.mouse_listeners = mouse_listeners;
2967
2968        if self.has_active_drag() {
2969            if event.is::<MouseMoveEvent>() {
2970                // If this was a mouse move event, redraw the window so that the
2971                // active drag can follow the mouse cursor.
2972                self.refresh();
2973            } else if event.is::<MouseUpEvent>() {
2974                // If this was a mouse up event, cancel the active drag and redraw
2975                // the window.
2976                self.active_drag = None;
2977                self.refresh();
2978            }
2979        }
2980    }
2981
2982    fn dispatch_key_event(&mut self, event: &dyn Any) {
2983        if self.window.dirty.get() {
2984            self.draw();
2985        }
2986
2987        let node_id = self
2988            .window
2989            .focus
2990            .and_then(|focus_id| {
2991                self.window
2992                    .rendered_frame
2993                    .dispatch_tree
2994                    .focusable_node_id(focus_id)
2995            })
2996            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
2997
2998        let dispatch_path = self
2999            .window
3000            .rendered_frame
3001            .dispatch_tree
3002            .dispatch_path(node_id);
3003
3004        if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3005            let KeymatchResult { bindings, pending } = self
3006                .window
3007                .rendered_frame
3008                .dispatch_tree
3009                .dispatch_key(&key_down_event.keystroke, &dispatch_path);
3010
3011            if pending {
3012                let mut currently_pending = self.window.pending_input.take().unwrap_or_default();
3013                if currently_pending.focus.is_some() && currently_pending.focus != self.window.focus
3014                {
3015                    currently_pending = PendingInput::default();
3016                }
3017                currently_pending.focus = self.window.focus;
3018                currently_pending
3019                    .keystrokes
3020                    .push(key_down_event.keystroke.clone());
3021                for binding in bindings {
3022                    currently_pending.bindings.push(binding);
3023                }
3024
3025                currently_pending.timer = Some(self.spawn(|mut cx| async move {
3026                    cx.background_executor.timer(Duration::from_secs(1)).await;
3027                    cx.update(move |cx| {
3028                        cx.clear_pending_keystrokes();
3029                        let Some(currently_pending) = cx.window.pending_input.take() else {
3030                            return;
3031                        };
3032                        cx.replay_pending_input(currently_pending)
3033                    })
3034                    .log_err();
3035                }));
3036
3037                self.window.pending_input = Some(currently_pending);
3038
3039                self.propagate_event = false;
3040                return;
3041            } else if let Some(currently_pending) = self.window.pending_input.take() {
3042                if bindings
3043                    .iter()
3044                    .all(|binding| !currently_pending.used_by_binding(binding))
3045                {
3046                    self.replay_pending_input(currently_pending)
3047                }
3048            }
3049
3050            if !bindings.is_empty() {
3051                self.clear_pending_keystrokes();
3052            }
3053
3054            self.propagate_event = true;
3055            for binding in bindings {
3056                self.dispatch_action_on_node(node_id, binding.action.as_ref());
3057                if !self.propagate_event {
3058                    self.dispatch_keystroke_observers(event, Some(binding.action));
3059                    return;
3060                }
3061            }
3062        }
3063
3064        self.dispatch_key_down_up_event(event, &dispatch_path);
3065        if !self.propagate_event {
3066            return;
3067        }
3068
3069        self.dispatch_modifiers_changed_event(event, &dispatch_path);
3070        if !self.propagate_event {
3071            return;
3072        }
3073
3074        self.dispatch_keystroke_observers(event, None);
3075    }
3076
3077    fn dispatch_key_down_up_event(
3078        &mut self,
3079        event: &dyn Any,
3080        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3081    ) {
3082        // Capture phase
3083        for node_id in dispatch_path {
3084            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3085
3086            for key_listener in node.key_listeners.clone() {
3087                key_listener(event, DispatchPhase::Capture, self);
3088                if !self.propagate_event {
3089                    return;
3090                }
3091            }
3092        }
3093
3094        // Bubble phase
3095        for node_id in dispatch_path.iter().rev() {
3096            // Handle low level key events
3097            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3098            for key_listener in node.key_listeners.clone() {
3099                key_listener(event, DispatchPhase::Bubble, self);
3100                if !self.propagate_event {
3101                    return;
3102                }
3103            }
3104        }
3105    }
3106
3107    fn dispatch_modifiers_changed_event(
3108        &mut self,
3109        event: &dyn Any,
3110        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3111    ) {
3112        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
3113            return;
3114        };
3115        for node_id in dispatch_path.iter().rev() {
3116            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3117            for listener in node.modifiers_changed_listeners.clone() {
3118                listener(event, self);
3119                if !self.propagate_event {
3120                    return;
3121                }
3122            }
3123        }
3124    }
3125
3126    /// Determine whether a potential multi-stroke key binding is in progress on this window.
3127    pub fn has_pending_keystrokes(&self) -> bool {
3128        self.window
3129            .rendered_frame
3130            .dispatch_tree
3131            .has_pending_keystrokes()
3132    }
3133
3134    fn replay_pending_input(&mut self, currently_pending: PendingInput) {
3135        let node_id = self
3136            .window
3137            .focus
3138            .and_then(|focus_id| {
3139                self.window
3140                    .rendered_frame
3141                    .dispatch_tree
3142                    .focusable_node_id(focus_id)
3143            })
3144            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3145
3146        if self.window.focus != currently_pending.focus {
3147            return;
3148        }
3149
3150        let input = currently_pending.input();
3151
3152        self.propagate_event = true;
3153        for binding in currently_pending.bindings {
3154            self.dispatch_action_on_node(node_id, binding.action.as_ref());
3155            if !self.propagate_event {
3156                return;
3157            }
3158        }
3159
3160        let dispatch_path = self
3161            .window
3162            .rendered_frame
3163            .dispatch_tree
3164            .dispatch_path(node_id);
3165
3166        for keystroke in currently_pending.keystrokes {
3167            let event = KeyDownEvent {
3168                keystroke,
3169                is_held: false,
3170            };
3171
3172            self.dispatch_key_down_up_event(&event, &dispatch_path);
3173            if !self.propagate_event {
3174                return;
3175            }
3176        }
3177
3178        if !input.is_empty() {
3179            if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
3180                input_handler.dispatch_input(&input, self);
3181                self.window.platform_window.set_input_handler(input_handler)
3182            }
3183        }
3184    }
3185
3186    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: &dyn Action) {
3187        let dispatch_path = self
3188            .window
3189            .rendered_frame
3190            .dispatch_tree
3191            .dispatch_path(node_id);
3192
3193        // Capture phase for global actions.
3194        self.propagate_event = true;
3195        if let Some(mut global_listeners) = self
3196            .global_action_listeners
3197            .remove(&action.as_any().type_id())
3198        {
3199            for listener in &global_listeners {
3200                listener(action.as_any(), DispatchPhase::Capture, self);
3201                if !self.propagate_event {
3202                    break;
3203                }
3204            }
3205
3206            global_listeners.extend(
3207                self.global_action_listeners
3208                    .remove(&action.as_any().type_id())
3209                    .unwrap_or_default(),
3210            );
3211
3212            self.global_action_listeners
3213                .insert(action.as_any().type_id(), global_listeners);
3214        }
3215
3216        if !self.propagate_event {
3217            return;
3218        }
3219
3220        // Capture phase for window actions.
3221        for node_id in &dispatch_path {
3222            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3223            for DispatchActionListener {
3224                action_type,
3225                listener,
3226            } in node.action_listeners.clone()
3227            {
3228                let any_action = action.as_any();
3229                if action_type == any_action.type_id() {
3230                    listener(any_action, DispatchPhase::Capture, self);
3231
3232                    if !self.propagate_event {
3233                        return;
3234                    }
3235                }
3236            }
3237        }
3238
3239        // Bubble phase for window actions.
3240        for node_id in dispatch_path.iter().rev() {
3241            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3242            for DispatchActionListener {
3243                action_type,
3244                listener,
3245            } in node.action_listeners.clone()
3246            {
3247                let any_action = action.as_any();
3248                if action_type == any_action.type_id() {
3249                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3250                    listener(any_action, DispatchPhase::Bubble, self);
3251
3252                    if !self.propagate_event {
3253                        return;
3254                    }
3255                }
3256            }
3257        }
3258
3259        // Bubble phase for global actions.
3260        if let Some(mut global_listeners) = self
3261            .global_action_listeners
3262            .remove(&action.as_any().type_id())
3263        {
3264            for listener in global_listeners.iter().rev() {
3265                self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3266
3267                listener(action.as_any(), DispatchPhase::Bubble, self);
3268                if !self.propagate_event {
3269                    break;
3270                }
3271            }
3272
3273            global_listeners.extend(
3274                self.global_action_listeners
3275                    .remove(&action.as_any().type_id())
3276                    .unwrap_or_default(),
3277            );
3278
3279            self.global_action_listeners
3280                .insert(action.as_any().type_id(), global_listeners);
3281        }
3282    }
3283
3284    /// Register the given handler to be invoked whenever the global of the given type
3285    /// is updated.
3286    pub fn observe_global<G: Global>(
3287        &mut self,
3288        f: impl Fn(&mut WindowContext<'_>) + 'static,
3289    ) -> Subscription {
3290        let window_handle = self.window.handle;
3291        let (subscription, activate) = self.global_observers.insert(
3292            TypeId::of::<G>(),
3293            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
3294        );
3295        self.app.defer(move |_| activate());
3296        subscription
3297    }
3298
3299    /// Focus the current window and bring it to the foreground at the platform level.
3300    pub fn activate_window(&self) {
3301        self.window.platform_window.activate();
3302    }
3303
3304    /// Minimize the current window at the platform level.
3305    pub fn minimize_window(&self) {
3306        self.window.platform_window.minimize();
3307    }
3308
3309    /// Toggle full screen status on the current window at the platform level.
3310    pub fn toggle_fullscreen(&self) {
3311        self.window.platform_window.toggle_fullscreen();
3312    }
3313
3314    /// Present a platform dialog.
3315    /// The provided message will be presented, along with buttons for each answer.
3316    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
3317    pub fn prompt(
3318        &mut self,
3319        level: PromptLevel,
3320        message: &str,
3321        detail: Option<&str>,
3322        answers: &[&str],
3323    ) -> oneshot::Receiver<usize> {
3324        let prompt_builder = self.app.prompt_builder.take();
3325        let Some(prompt_builder) = prompt_builder else {
3326            unreachable!("Re-entrant window prompting is not supported by GPUI");
3327        };
3328
3329        let receiver = match &prompt_builder {
3330            PromptBuilder::Default => self
3331                .window
3332                .platform_window
3333                .prompt(level, message, detail, answers)
3334                .unwrap_or_else(|| {
3335                    self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3336                }),
3337            PromptBuilder::Custom(_) => {
3338                self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3339            }
3340        };
3341
3342        self.app.prompt_builder = Some(prompt_builder);
3343
3344        receiver
3345    }
3346
3347    fn build_custom_prompt(
3348        &mut self,
3349        prompt_builder: &PromptBuilder,
3350        level: PromptLevel,
3351        message: &str,
3352        detail: Option<&str>,
3353        answers: &[&str],
3354    ) -> oneshot::Receiver<usize> {
3355        let (sender, receiver) = oneshot::channel();
3356        let handle = PromptHandle::new(sender);
3357        let handle = (prompt_builder)(level, message, detail, answers, handle, self);
3358        self.window.prompt = Some(handle);
3359        receiver
3360    }
3361
3362    /// Returns all available actions for the focused element.
3363    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
3364        let node_id = self
3365            .window
3366            .focus
3367            .and_then(|focus_id| {
3368                self.window
3369                    .rendered_frame
3370                    .dispatch_tree
3371                    .focusable_node_id(focus_id)
3372            })
3373            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3374
3375        let mut actions = self
3376            .window
3377            .rendered_frame
3378            .dispatch_tree
3379            .available_actions(node_id);
3380        for action_type in self.global_action_listeners.keys() {
3381            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
3382                let action = self.actions.build_action_type(action_type).ok();
3383                if let Some(action) = action {
3384                    actions.insert(ix, action);
3385                }
3386            }
3387        }
3388        actions
3389    }
3390
3391    /// Returns key bindings that invoke the given action on the currently focused element.
3392    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
3393        self.window
3394            .rendered_frame
3395            .dispatch_tree
3396            .bindings_for_action(
3397                action,
3398                &self.window.rendered_frame.dispatch_tree.context_stack,
3399            )
3400    }
3401
3402    /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
3403    pub fn bindings_for_action_in(
3404        &self,
3405        action: &dyn Action,
3406        focus_handle: &FocusHandle,
3407    ) -> Vec<KeyBinding> {
3408        let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
3409
3410        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
3411            return vec![];
3412        };
3413        let context_stack: Vec<_> = dispatch_tree
3414            .dispatch_path(node_id)
3415            .into_iter()
3416            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
3417            .collect();
3418        dispatch_tree.bindings_for_action(action, &context_stack)
3419    }
3420
3421    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
3422    pub fn listener_for<V: Render, E>(
3423        &self,
3424        view: &View<V>,
3425        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
3426    ) -> impl Fn(&E, &mut WindowContext) + 'static {
3427        let view = view.downgrade();
3428        move |e: &E, cx: &mut WindowContext| {
3429            view.update(cx, |view, cx| f(view, e, cx)).ok();
3430        }
3431    }
3432
3433    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
3434    pub fn handler_for<V: Render>(
3435        &self,
3436        view: &View<V>,
3437        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
3438    ) -> impl Fn(&mut WindowContext) {
3439        let view = view.downgrade();
3440        move |cx: &mut WindowContext| {
3441            view.update(cx, |view, cx| f(view, cx)).ok();
3442        }
3443    }
3444
3445    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
3446    /// If the callback returns false, the window won't be closed.
3447    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
3448        let mut this = self.to_async();
3449        self.window
3450            .platform_window
3451            .on_should_close(Box::new(move || this.update(|cx| f(cx)).unwrap_or(true)))
3452    }
3453
3454    /// Register an action listener on the window for the next frame. The type of action
3455    /// is determined by the first parameter of the given listener. When the next frame is rendered
3456    /// the listener will be cleared.
3457    ///
3458    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
3459    /// a specific need to register a global listener.
3460    pub fn on_action(
3461        &mut self,
3462        action_type: TypeId,
3463        listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
3464    ) {
3465        self.window
3466            .next_frame
3467            .dispatch_tree
3468            .on_action(action_type, Rc::new(listener));
3469    }
3470}
3471
3472#[cfg(target_os = "windows")]
3473impl WindowContext<'_> {
3474    /// Returns the raw HWND handle for the window.
3475    pub fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND {
3476        self.window.platform_window.get_raw_handle()
3477    }
3478}
3479
3480impl Context for WindowContext<'_> {
3481    type Result<T> = T;
3482
3483    fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
3484    where
3485        T: 'static,
3486    {
3487        let slot = self.app.entities.reserve();
3488        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
3489        self.entities.insert(slot, model)
3490    }
3491
3492    fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
3493        self.app.reserve_model()
3494    }
3495
3496    fn insert_model<T: 'static>(
3497        &mut self,
3498        reservation: crate::Reservation<T>,
3499        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
3500    ) -> Self::Result<Model<T>> {
3501        self.app.insert_model(reservation, build_model)
3502    }
3503
3504    fn update_model<T: 'static, R>(
3505        &mut self,
3506        model: &Model<T>,
3507        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
3508    ) -> R {
3509        let mut entity = self.entities.lease(model);
3510        let result = update(
3511            &mut *entity,
3512            &mut ModelContext::new(&mut *self.app, model.downgrade()),
3513        );
3514        self.entities.end_lease(entity);
3515        result
3516    }
3517
3518    fn read_model<T, R>(
3519        &self,
3520        handle: &Model<T>,
3521        read: impl FnOnce(&T, &AppContext) -> R,
3522    ) -> Self::Result<R>
3523    where
3524        T: 'static,
3525    {
3526        let entity = self.entities.read(handle);
3527        read(entity, &*self.app)
3528    }
3529
3530    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
3531    where
3532        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
3533    {
3534        if window == self.window.handle {
3535            let root_view = self.window.root_view.clone().unwrap();
3536            Ok(update(root_view, self))
3537        } else {
3538            window.update(self.app, update)
3539        }
3540    }
3541
3542    fn read_window<T, R>(
3543        &self,
3544        window: &WindowHandle<T>,
3545        read: impl FnOnce(View<T>, &AppContext) -> R,
3546    ) -> Result<R>
3547    where
3548        T: 'static,
3549    {
3550        if window.any_handle == self.window.handle {
3551            let root_view = self
3552                .window
3553                .root_view
3554                .clone()
3555                .unwrap()
3556                .downcast::<T>()
3557                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3558            Ok(read(root_view, self))
3559        } else {
3560            self.app.read_window(window, read)
3561        }
3562    }
3563}
3564
3565impl VisualContext for WindowContext<'_> {
3566    fn new_view<V>(
3567        &mut self,
3568        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3569    ) -> Self::Result<View<V>>
3570    where
3571        V: 'static + Render,
3572    {
3573        let slot = self.app.entities.reserve();
3574        let view = View {
3575            model: slot.clone(),
3576        };
3577        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
3578        let entity = build_view_state(&mut cx);
3579        cx.entities.insert(slot, entity);
3580
3581        // Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
3582        fn notify_observers(cx: &mut WindowContext, tid: TypeId, view: AnyView) {
3583            cx.new_view_observers.clone().retain(&tid, |observer| {
3584                let any_view = view.clone();
3585                (observer)(any_view, cx);
3586                true
3587            });
3588        }
3589        notify_observers(self, TypeId::of::<V>(), AnyView::from(view.clone()));
3590
3591        view
3592    }
3593
3594    /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
3595    fn update_view<T: 'static, R>(
3596        &mut self,
3597        view: &View<T>,
3598        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
3599    ) -> Self::Result<R> {
3600        let mut lease = self.app.entities.lease(&view.model);
3601        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
3602        let result = update(&mut *lease, &mut cx);
3603        cx.app.entities.end_lease(lease);
3604        result
3605    }
3606
3607    fn replace_root_view<V>(
3608        &mut self,
3609        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3610    ) -> Self::Result<View<V>>
3611    where
3612        V: 'static + Render,
3613    {
3614        let view = self.new_view(build_view);
3615        self.window.root_view = Some(view.clone().into());
3616        self.refresh();
3617        view
3618    }
3619
3620    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
3621        self.update_view(view, |view, cx| {
3622            view.focus_handle(cx).clone().focus(cx);
3623        })
3624    }
3625
3626    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
3627    where
3628        V: ManagedView,
3629    {
3630        self.update_view(view, |_, cx| cx.emit(DismissEvent))
3631    }
3632}
3633
3634impl<'a> std::ops::Deref for WindowContext<'a> {
3635    type Target = AppContext;
3636
3637    fn deref(&self) -> &Self::Target {
3638        self.app
3639    }
3640}
3641
3642impl<'a> std::ops::DerefMut for WindowContext<'a> {
3643    fn deref_mut(&mut self) -> &mut Self::Target {
3644        self.app
3645    }
3646}
3647
3648impl<'a> Borrow<AppContext> for WindowContext<'a> {
3649    fn borrow(&self) -> &AppContext {
3650        self.app
3651    }
3652}
3653
3654impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
3655    fn borrow_mut(&mut self) -> &mut AppContext {
3656        self.app
3657    }
3658}
3659
3660/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
3661pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
3662    #[doc(hidden)]
3663    fn app_mut(&mut self) -> &mut AppContext {
3664        self.borrow_mut()
3665    }
3666
3667    #[doc(hidden)]
3668    fn app(&self) -> &AppContext {
3669        self.borrow()
3670    }
3671
3672    #[doc(hidden)]
3673    fn window(&self) -> &Window {
3674        self.borrow()
3675    }
3676
3677    #[doc(hidden)]
3678    fn window_mut(&mut self) -> &mut Window {
3679        self.borrow_mut()
3680    }
3681}
3682
3683impl Borrow<Window> for WindowContext<'_> {
3684    fn borrow(&self) -> &Window {
3685        self.window
3686    }
3687}
3688
3689impl BorrowMut<Window> for WindowContext<'_> {
3690    fn borrow_mut(&mut self) -> &mut Window {
3691        self.window
3692    }
3693}
3694
3695impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
3696
3697/// Provides access to application state that is specialized for a particular [`View`].
3698/// Allows you to interact with focus, emit events, etc.
3699/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
3700/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
3701pub struct ViewContext<'a, V> {
3702    window_cx: WindowContext<'a>,
3703    view: &'a View<V>,
3704}
3705
3706impl<V> Borrow<AppContext> for ViewContext<'_, V> {
3707    fn borrow(&self) -> &AppContext {
3708        &*self.window_cx.app
3709    }
3710}
3711
3712impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
3713    fn borrow_mut(&mut self) -> &mut AppContext {
3714        &mut *self.window_cx.app
3715    }
3716}
3717
3718impl<V> Borrow<Window> for ViewContext<'_, V> {
3719    fn borrow(&self) -> &Window {
3720        &*self.window_cx.window
3721    }
3722}
3723
3724impl<V> BorrowMut<Window> for ViewContext<'_, V> {
3725    fn borrow_mut(&mut self) -> &mut Window {
3726        &mut *self.window_cx.window
3727    }
3728}
3729
3730impl<'a, V: 'static> ViewContext<'a, V> {
3731    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
3732        Self {
3733            window_cx: WindowContext::new(app, window),
3734            view,
3735        }
3736    }
3737
3738    /// Get the entity_id of this view.
3739    pub fn entity_id(&self) -> EntityId {
3740        self.view.entity_id()
3741    }
3742
3743    /// Get the view pointer underlying this context.
3744    pub fn view(&self) -> &View<V> {
3745        self.view
3746    }
3747
3748    /// Get the model underlying this view.
3749    pub fn model(&self) -> &Model<V> {
3750        &self.view.model
3751    }
3752
3753    /// Access the underlying window context.
3754    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
3755        &mut self.window_cx
3756    }
3757
3758    /// Sets a given callback to be run on the next frame.
3759    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
3760    where
3761        V: 'static,
3762    {
3763        let view = self.view().clone();
3764        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
3765    }
3766
3767    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
3768    /// that are currently on the stack to be returned to the app.
3769    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
3770        let view = self.view().downgrade();
3771        self.window_cx.defer(move |cx| {
3772            view.update(cx, f).ok();
3773        });
3774    }
3775
3776    /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
3777    pub fn observe<V2, E>(
3778        &mut self,
3779        entity: &E,
3780        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
3781    ) -> Subscription
3782    where
3783        V2: 'static,
3784        V: 'static,
3785        E: Entity<V2>,
3786    {
3787        let view = self.view().downgrade();
3788        let entity_id = entity.entity_id();
3789        let entity = entity.downgrade();
3790        let window_handle = self.window.handle;
3791        self.app.new_observer(
3792            entity_id,
3793            Box::new(move |cx| {
3794                window_handle
3795                    .update(cx, |_, cx| {
3796                        if let Some(handle) = E::upgrade_from(&entity) {
3797                            view.update(cx, |this, cx| on_notify(this, handle, cx))
3798                                .is_ok()
3799                        } else {
3800                            false
3801                        }
3802                    })
3803                    .unwrap_or(false)
3804            }),
3805        )
3806    }
3807
3808    /// Subscribe to events emitted by another model or view.
3809    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
3810    /// 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.
3811    pub fn subscribe<V2, E, Evt>(
3812        &mut self,
3813        entity: &E,
3814        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
3815    ) -> Subscription
3816    where
3817        V2: EventEmitter<Evt>,
3818        E: Entity<V2>,
3819        Evt: 'static,
3820    {
3821        let view = self.view().downgrade();
3822        let entity_id = entity.entity_id();
3823        let handle = entity.downgrade();
3824        let window_handle = self.window.handle;
3825        self.app.new_subscription(
3826            entity_id,
3827            (
3828                TypeId::of::<Evt>(),
3829                Box::new(move |event, cx| {
3830                    window_handle
3831                        .update(cx, |_, cx| {
3832                            if let Some(handle) = E::upgrade_from(&handle) {
3833                                let event = event.downcast_ref().expect("invalid event type");
3834                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
3835                                    .is_ok()
3836                            } else {
3837                                false
3838                            }
3839                        })
3840                        .unwrap_or(false)
3841                }),
3842            ),
3843        )
3844    }
3845
3846    /// Register a callback to be invoked when the view is released.
3847    ///
3848    /// The callback receives a handle to the view's window. This handle may be
3849    /// invalid, if the window was closed before the view was released.
3850    pub fn on_release(
3851        &mut self,
3852        on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
3853    ) -> Subscription {
3854        let window_handle = self.window.handle;
3855        let (subscription, activate) = self.app.release_listeners.insert(
3856            self.view.model.entity_id,
3857            Box::new(move |this, cx| {
3858                let this = this.downcast_mut().expect("invalid entity type");
3859                on_release(this, window_handle, cx)
3860            }),
3861        );
3862        activate();
3863        subscription
3864    }
3865
3866    /// Register a callback to be invoked when the given Model or View is released.
3867    pub fn observe_release<V2, E>(
3868        &mut self,
3869        entity: &E,
3870        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
3871    ) -> Subscription
3872    where
3873        V: 'static,
3874        V2: 'static,
3875        E: Entity<V2>,
3876    {
3877        let view = self.view().downgrade();
3878        let entity_id = entity.entity_id();
3879        let window_handle = self.window.handle;
3880        let (subscription, activate) = self.app.release_listeners.insert(
3881            entity_id,
3882            Box::new(move |entity, cx| {
3883                let entity = entity.downcast_mut().expect("invalid entity type");
3884                let _ = window_handle.update(cx, |_, cx| {
3885                    view.update(cx, |this, cx| on_release(this, entity, cx))
3886                });
3887            }),
3888        );
3889        activate();
3890        subscription
3891    }
3892
3893    /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
3894    /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
3895    pub fn notify(&mut self) {
3896        self.window_cx.notify(self.view.entity_id());
3897    }
3898
3899    /// Register a callback to be invoked when the window is resized.
3900    pub fn observe_window_bounds(
3901        &mut self,
3902        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
3903    ) -> Subscription {
3904        let view = self.view.downgrade();
3905        let (subscription, activate) = self.window.bounds_observers.insert(
3906            (),
3907            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
3908        );
3909        activate();
3910        subscription
3911    }
3912
3913    /// Register a callback to be invoked when the window is activated or deactivated.
3914    pub fn observe_window_activation(
3915        &mut self,
3916        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
3917    ) -> Subscription {
3918        let view = self.view.downgrade();
3919        let (subscription, activate) = self.window.activation_observers.insert(
3920            (),
3921            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
3922        );
3923        activate();
3924        subscription
3925    }
3926
3927    /// Registers a callback to be invoked when the window appearance changes.
3928    pub fn observe_window_appearance(
3929        &mut self,
3930        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
3931    ) -> Subscription {
3932        let view = self.view.downgrade();
3933        let (subscription, activate) = self.window.appearance_observers.insert(
3934            (),
3935            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
3936        );
3937        activate();
3938        subscription
3939    }
3940
3941    /// Register a listener to be called when the given focus handle receives focus.
3942    /// Returns a subscription and persists until the subscription is dropped.
3943    pub fn on_focus(
3944        &mut self,
3945        handle: &FocusHandle,
3946        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
3947    ) -> Subscription {
3948        let view = self.view.downgrade();
3949        let focus_id = handle.id;
3950        let (subscription, activate) =
3951            self.window.new_focus_listener(Box::new(move |event, cx| {
3952                view.update(cx, |view, cx| {
3953                    if event.previous_focus_path.last() != Some(&focus_id)
3954                        && event.current_focus_path.last() == Some(&focus_id)
3955                    {
3956                        listener(view, cx)
3957                    }
3958                })
3959                .is_ok()
3960            }));
3961        self.app.defer(|_| activate());
3962        subscription
3963    }
3964
3965    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
3966    /// Returns a subscription and persists until the subscription is dropped.
3967    pub fn on_focus_in(
3968        &mut self,
3969        handle: &FocusHandle,
3970        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
3971    ) -> Subscription {
3972        let view = self.view.downgrade();
3973        let focus_id = handle.id;
3974        let (subscription, activate) =
3975            self.window.new_focus_listener(Box::new(move |event, cx| {
3976                view.update(cx, |view, cx| {
3977                    if !event.previous_focus_path.contains(&focus_id)
3978                        && event.current_focus_path.contains(&focus_id)
3979                    {
3980                        listener(view, cx)
3981                    }
3982                })
3983                .is_ok()
3984            }));
3985        self.app.defer(move |_| activate());
3986        subscription
3987    }
3988
3989    /// Register a listener to be called when the given focus handle loses focus.
3990    /// Returns a subscription and persists until the subscription is dropped.
3991    pub fn on_blur(
3992        &mut self,
3993        handle: &FocusHandle,
3994        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
3995    ) -> Subscription {
3996        let view = self.view.downgrade();
3997        let focus_id = handle.id;
3998        let (subscription, activate) =
3999            self.window.new_focus_listener(Box::new(move |event, cx| {
4000                view.update(cx, |view, cx| {
4001                    if event.previous_focus_path.last() == Some(&focus_id)
4002                        && event.current_focus_path.last() != Some(&focus_id)
4003                    {
4004                        listener(view, cx)
4005                    }
4006                })
4007                .is_ok()
4008            }));
4009        self.app.defer(move |_| activate());
4010        subscription
4011    }
4012
4013    /// Register a listener to be called when nothing in the window has focus.
4014    /// This typically happens when the node that was focused is removed from the tree,
4015    /// and this callback lets you chose a default place to restore the users focus.
4016    /// Returns a subscription and persists until the subscription is dropped.
4017    pub fn on_focus_lost(
4018        &mut self,
4019        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4020    ) -> Subscription {
4021        let view = self.view.downgrade();
4022        let (subscription, activate) = self.window.focus_lost_listeners.insert(
4023            (),
4024            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
4025        );
4026        activate();
4027        subscription
4028    }
4029
4030    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
4031    /// Returns a subscription and persists until the subscription is dropped.
4032    pub fn on_focus_out(
4033        &mut self,
4034        handle: &FocusHandle,
4035        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4036    ) -> Subscription {
4037        let view = self.view.downgrade();
4038        let focus_id = handle.id;
4039        let (subscription, activate) =
4040            self.window.new_focus_listener(Box::new(move |event, cx| {
4041                view.update(cx, |view, cx| {
4042                    if event.previous_focus_path.contains(&focus_id)
4043                        && !event.current_focus_path.contains(&focus_id)
4044                    {
4045                        listener(view, cx)
4046                    }
4047                })
4048                .is_ok()
4049            }));
4050        self.app.defer(move |_| activate());
4051        subscription
4052    }
4053
4054    /// Schedule a future to be run asynchronously.
4055    /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
4056    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
4057    /// The returned future will be polled on the main thread.
4058    pub fn spawn<Fut, R>(
4059        &mut self,
4060        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
4061    ) -> Task<R>
4062    where
4063        R: 'static,
4064        Fut: Future<Output = R> + 'static,
4065    {
4066        let view = self.view().downgrade();
4067        self.window_cx.spawn(|cx| f(view, cx))
4068    }
4069
4070    /// Register a callback to be invoked when the given global state changes.
4071    pub fn observe_global<G: Global>(
4072        &mut self,
4073        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
4074    ) -> Subscription {
4075        let window_handle = self.window.handle;
4076        let view = self.view().downgrade();
4077        let (subscription, activate) = self.global_observers.insert(
4078            TypeId::of::<G>(),
4079            Box::new(move |cx| {
4080                window_handle
4081                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
4082                    .unwrap_or(false)
4083            }),
4084        );
4085        self.app.defer(move |_| activate());
4086        subscription
4087    }
4088
4089    /// Register a callback to be invoked when the given Action type is dispatched to the window.
4090    pub fn on_action(
4091        &mut self,
4092        action_type: TypeId,
4093        listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
4094    ) {
4095        let handle = self.view().clone();
4096        self.window_cx
4097            .on_action(action_type, move |action, phase, cx| {
4098                handle.update(cx, |view, cx| {
4099                    listener(view, action, phase, cx);
4100                })
4101            });
4102    }
4103
4104    /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
4105    pub fn emit<Evt>(&mut self, event: Evt)
4106    where
4107        Evt: 'static,
4108        V: EventEmitter<Evt>,
4109    {
4110        let emitter = self.view.model.entity_id;
4111        self.app.push_effect(Effect::Emit {
4112            emitter,
4113            event_type: TypeId::of::<Evt>(),
4114            event: Box::new(event),
4115        });
4116    }
4117
4118    /// Move focus to the current view, assuming it implements [`FocusableView`].
4119    pub fn focus_self(&mut self)
4120    where
4121        V: FocusableView,
4122    {
4123        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
4124    }
4125
4126    /// Convenience method for accessing view state in an event callback.
4127    ///
4128    /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
4129    /// but it's often useful to be able to access view state in these
4130    /// callbacks. This method provides a convenient way to do so.
4131    pub fn listener<E>(
4132        &self,
4133        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
4134    ) -> impl Fn(&E, &mut WindowContext) + 'static {
4135        let view = self.view().downgrade();
4136        move |e: &E, cx: &mut WindowContext| {
4137            view.update(cx, |view, cx| f(view, e, cx)).ok();
4138        }
4139    }
4140}
4141
4142impl<V> Context for ViewContext<'_, V> {
4143    type Result<U> = U;
4144
4145    fn new_model<T: 'static>(
4146        &mut self,
4147        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4148    ) -> Model<T> {
4149        self.window_cx.new_model(build_model)
4150    }
4151
4152    fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
4153        self.window_cx.reserve_model()
4154    }
4155
4156    fn insert_model<T: 'static>(
4157        &mut self,
4158        reservation: crate::Reservation<T>,
4159        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4160    ) -> Self::Result<Model<T>> {
4161        self.window_cx.insert_model(reservation, build_model)
4162    }
4163
4164    fn update_model<T: 'static, R>(
4165        &mut self,
4166        model: &Model<T>,
4167        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
4168    ) -> R {
4169        self.window_cx.update_model(model, update)
4170    }
4171
4172    fn read_model<T, R>(
4173        &self,
4174        handle: &Model<T>,
4175        read: impl FnOnce(&T, &AppContext) -> R,
4176    ) -> Self::Result<R>
4177    where
4178        T: 'static,
4179    {
4180        self.window_cx.read_model(handle, read)
4181    }
4182
4183    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
4184    where
4185        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
4186    {
4187        self.window_cx.update_window(window, update)
4188    }
4189
4190    fn read_window<T, R>(
4191        &self,
4192        window: &WindowHandle<T>,
4193        read: impl FnOnce(View<T>, &AppContext) -> R,
4194    ) -> Result<R>
4195    where
4196        T: 'static,
4197    {
4198        self.window_cx.read_window(window, read)
4199    }
4200}
4201
4202impl<V: 'static> VisualContext for ViewContext<'_, V> {
4203    fn new_view<W: Render + 'static>(
4204        &mut self,
4205        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4206    ) -> Self::Result<View<W>> {
4207        self.window_cx.new_view(build_view_state)
4208    }
4209
4210    fn update_view<V2: 'static, R>(
4211        &mut self,
4212        view: &View<V2>,
4213        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
4214    ) -> Self::Result<R> {
4215        self.window_cx.update_view(view, update)
4216    }
4217
4218    fn replace_root_view<W>(
4219        &mut self,
4220        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4221    ) -> Self::Result<View<W>>
4222    where
4223        W: 'static + Render,
4224    {
4225        self.window_cx.replace_root_view(build_view)
4226    }
4227
4228    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
4229        self.window_cx.focus_view(view)
4230    }
4231
4232    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
4233        self.window_cx.dismiss_view(view)
4234    }
4235}
4236
4237impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
4238    type Target = WindowContext<'a>;
4239
4240    fn deref(&self) -> &Self::Target {
4241        &self.window_cx
4242    }
4243}
4244
4245impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
4246    fn deref_mut(&mut self) -> &mut Self::Target {
4247        &mut self.window_cx
4248    }
4249}
4250
4251// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
4252slotmap::new_key_type! {
4253    /// A unique identifier for a window.
4254    pub struct WindowId;
4255}
4256
4257impl WindowId {
4258    /// Converts this window ID to a `u64`.
4259    pub fn as_u64(&self) -> u64 {
4260        self.0.as_ffi()
4261    }
4262}
4263
4264/// A handle to a window with a specific root view type.
4265/// Note that this does not keep the window alive on its own.
4266#[derive(Deref, DerefMut)]
4267pub struct WindowHandle<V> {
4268    #[deref]
4269    #[deref_mut]
4270    pub(crate) any_handle: AnyWindowHandle,
4271    state_type: PhantomData<V>,
4272}
4273
4274impl<V: 'static + Render> WindowHandle<V> {
4275    /// Creates a new handle from a window ID.
4276    /// This does not check if the root type of the window is `V`.
4277    pub fn new(id: WindowId) -> Self {
4278        WindowHandle {
4279            any_handle: AnyWindowHandle {
4280                id,
4281                state_type: TypeId::of::<V>(),
4282            },
4283            state_type: PhantomData,
4284        }
4285    }
4286
4287    /// Get the root view out of this window.
4288    ///
4289    /// This will fail if the window is closed or if the root view's type does not match `V`.
4290    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
4291    where
4292        C: Context,
4293    {
4294        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
4295            root_view
4296                .downcast::<V>()
4297                .map_err(|_| anyhow!("the type of the window's root view has changed"))
4298        }))
4299    }
4300
4301    /// Updates the root view of this window.
4302    ///
4303    /// This will fail if the window has been closed or if the root view's type does not match
4304    pub fn update<C, R>(
4305        &self,
4306        cx: &mut C,
4307        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
4308    ) -> Result<R>
4309    where
4310        C: Context,
4311    {
4312        cx.update_window(self.any_handle, |root_view, cx| {
4313            let view = root_view
4314                .downcast::<V>()
4315                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4316            Ok(cx.update_view(&view, update))
4317        })?
4318    }
4319
4320    /// Read the root view out of this window.
4321    ///
4322    /// This will fail if the window is closed or if the root view's type does not match `V`.
4323    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
4324        let x = cx
4325            .windows
4326            .get(self.id)
4327            .and_then(|window| {
4328                window
4329                    .as_ref()
4330                    .and_then(|window| window.root_view.clone())
4331                    .map(|root_view| root_view.downcast::<V>())
4332            })
4333            .ok_or_else(|| anyhow!("window not found"))?
4334            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4335
4336        Ok(x.read(cx))
4337    }
4338
4339    /// Read the root view out of this window, with a callback
4340    ///
4341    /// This will fail if the window is closed or if the root view's type does not match `V`.
4342    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
4343    where
4344        C: Context,
4345    {
4346        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
4347    }
4348
4349    /// Read the root view pointer off of this window.
4350    ///
4351    /// This will fail if the window is closed or if the root view's type does not match `V`.
4352    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
4353    where
4354        C: Context,
4355    {
4356        cx.read_window(self, |root_view, _cx| root_view.clone())
4357    }
4358
4359    /// Check if this window is 'active'.
4360    ///
4361    /// Will return `None` if the window is closed or currently
4362    /// borrowed.
4363    pub fn is_active(&self, cx: &mut AppContext) -> Option<bool> {
4364        cx.update_window(self.any_handle, |_, cx| cx.is_window_active())
4365            .ok()
4366    }
4367}
4368
4369impl<V> Copy for WindowHandle<V> {}
4370
4371impl<V> Clone for WindowHandle<V> {
4372    fn clone(&self) -> Self {
4373        *self
4374    }
4375}
4376
4377impl<V> PartialEq for WindowHandle<V> {
4378    fn eq(&self, other: &Self) -> bool {
4379        self.any_handle == other.any_handle
4380    }
4381}
4382
4383impl<V> Eq for WindowHandle<V> {}
4384
4385impl<V> Hash for WindowHandle<V> {
4386    fn hash<H: Hasher>(&self, state: &mut H) {
4387        self.any_handle.hash(state);
4388    }
4389}
4390
4391impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
4392    fn from(val: WindowHandle<V>) -> Self {
4393        val.any_handle
4394    }
4395}
4396
4397/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
4398#[derive(Copy, Clone, PartialEq, Eq, Hash)]
4399pub struct AnyWindowHandle {
4400    pub(crate) id: WindowId,
4401    state_type: TypeId,
4402}
4403
4404impl AnyWindowHandle {
4405    /// Get the ID of this window.
4406    pub fn window_id(&self) -> WindowId {
4407        self.id
4408    }
4409
4410    /// Attempt to convert this handle to a window handle with a specific root view type.
4411    /// If the types do not match, this will return `None`.
4412    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
4413        if TypeId::of::<T>() == self.state_type {
4414            Some(WindowHandle {
4415                any_handle: *self,
4416                state_type: PhantomData,
4417            })
4418        } else {
4419            None
4420        }
4421    }
4422
4423    /// Updates the state of the root view of this window.
4424    ///
4425    /// This will fail if the window has been closed.
4426    pub fn update<C, R>(
4427        self,
4428        cx: &mut C,
4429        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
4430    ) -> Result<R>
4431    where
4432        C: Context,
4433    {
4434        cx.update_window(self, update)
4435    }
4436
4437    /// Read the state of the root view of this window.
4438    ///
4439    /// This will fail if the window has been closed.
4440    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
4441    where
4442        C: Context,
4443        T: 'static,
4444    {
4445        let view = self
4446            .downcast::<T>()
4447            .context("the type of the window's root view has changed")?;
4448
4449        cx.read_window(&view, read)
4450    }
4451}
4452
4453/// An identifier for an [`Element`](crate::Element).
4454///
4455/// Can be constructed with a string, a number, or both, as well
4456/// as other internal representations.
4457#[derive(Clone, Debug, Eq, PartialEq, Hash)]
4458pub enum ElementId {
4459    /// The ID of a View element
4460    View(EntityId),
4461    /// An integer ID.
4462    Integer(usize),
4463    /// A string based ID.
4464    Name(SharedString),
4465    /// An ID that's equated with a focus handle.
4466    FocusHandle(FocusId),
4467    /// A combination of a name and an integer.
4468    NamedInteger(SharedString, usize),
4469}
4470
4471impl Display for ElementId {
4472    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4473        match self {
4474            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
4475            ElementId::Integer(ix) => write!(f, "{}", ix)?,
4476            ElementId::Name(name) => write!(f, "{}", name)?,
4477            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
4478            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
4479        }
4480
4481        Ok(())
4482    }
4483}
4484
4485impl TryInto<SharedString> for ElementId {
4486    type Error = anyhow::Error;
4487
4488    fn try_into(self) -> anyhow::Result<SharedString> {
4489        if let ElementId::Name(name) = self {
4490            Ok(name)
4491        } else {
4492            Err(anyhow!("element id is not string"))
4493        }
4494    }
4495}
4496
4497impl From<usize> for ElementId {
4498    fn from(id: usize) -> Self {
4499        ElementId::Integer(id)
4500    }
4501}
4502
4503impl From<i32> for ElementId {
4504    fn from(id: i32) -> Self {
4505        Self::Integer(id as usize)
4506    }
4507}
4508
4509impl From<SharedString> for ElementId {
4510    fn from(name: SharedString) -> Self {
4511        ElementId::Name(name)
4512    }
4513}
4514
4515impl From<&'static str> for ElementId {
4516    fn from(name: &'static str) -> Self {
4517        ElementId::Name(name.into())
4518    }
4519}
4520
4521impl<'a> From<&'a FocusHandle> for ElementId {
4522    fn from(handle: &'a FocusHandle) -> Self {
4523        ElementId::FocusHandle(handle.id)
4524    }
4525}
4526
4527impl From<(&'static str, EntityId)> for ElementId {
4528    fn from((name, id): (&'static str, EntityId)) -> Self {
4529        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
4530    }
4531}
4532
4533impl From<(&'static str, usize)> for ElementId {
4534    fn from((name, id): (&'static str, usize)) -> Self {
4535        ElementId::NamedInteger(name.into(), id)
4536    }
4537}
4538
4539impl From<(&'static str, u64)> for ElementId {
4540    fn from((name, id): (&'static str, u64)) -> Self {
4541        ElementId::NamedInteger(name.into(), id as usize)
4542    }
4543}
4544
4545/// A rectangle to be rendered in the window at the given position and size.
4546/// Passed as an argument [`WindowContext::paint_quad`].
4547#[derive(Clone)]
4548pub struct PaintQuad {
4549    /// The bounds of the quad within the window.
4550    pub bounds: Bounds<Pixels>,
4551    /// The radii of the quad's corners.
4552    pub corner_radii: Corners<Pixels>,
4553    /// The background color of the quad.
4554    pub background: Hsla,
4555    /// The widths of the quad's borders.
4556    pub border_widths: Edges<Pixels>,
4557    /// The color of the quad's borders.
4558    pub border_color: Hsla,
4559}
4560
4561impl PaintQuad {
4562    /// Sets the corner radii of the quad.
4563    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
4564        PaintQuad {
4565            corner_radii: corner_radii.into(),
4566            ..self
4567        }
4568    }
4569
4570    /// Sets the border widths of the quad.
4571    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
4572        PaintQuad {
4573            border_widths: border_widths.into(),
4574            ..self
4575        }
4576    }
4577
4578    /// Sets the border color of the quad.
4579    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
4580        PaintQuad {
4581            border_color: border_color.into(),
4582            ..self
4583        }
4584    }
4585
4586    /// Sets the background color of the quad.
4587    pub fn background(self, background: impl Into<Hsla>) -> Self {
4588        PaintQuad {
4589            background: background.into(),
4590            ..self
4591        }
4592    }
4593}
4594
4595/// Creates a quad with the given parameters.
4596pub fn quad(
4597    bounds: Bounds<Pixels>,
4598    corner_radii: impl Into<Corners<Pixels>>,
4599    background: impl Into<Hsla>,
4600    border_widths: impl Into<Edges<Pixels>>,
4601    border_color: impl Into<Hsla>,
4602) -> PaintQuad {
4603    PaintQuad {
4604        bounds,
4605        corner_radii: corner_radii.into(),
4606        background: background.into(),
4607        border_widths: border_widths.into(),
4608        border_color: border_color.into(),
4609    }
4610}
4611
4612/// Creates a filled quad with the given bounds and background color.
4613pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
4614    PaintQuad {
4615        bounds: bounds.into(),
4616        corner_radii: (0.).into(),
4617        background: background.into(),
4618        border_widths: (0.).into(),
4619        border_color: transparent_black(),
4620    }
4621}
4622
4623/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
4624pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
4625    PaintQuad {
4626        bounds: bounds.into(),
4627        corner_radii: (0.).into(),
4628        background: transparent_black(),
4629        border_widths: (1.).into(),
4630        border_color: border_color.into(),
4631    }
4632}