window.rs

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