window.rs

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