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