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