window.rs

   1use crate::{
   2    px, size, transparent_black, Action, AnyDrag, AnyView, AppContext, Arena, AsyncWindowContext,
   3    AvailableSpace, Bounds, Context, Corners, CursorStyle, DispatchActionListener, DispatchNodeId,
   4    DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter, FileDropEvent, Flatten,
   5    Global, GlobalElementId, Hsla, KeyBinding, KeyContext, KeyDownEvent, KeyMatch, KeymatchResult,
   6    Keystroke, KeystrokeEvent, Model, ModelContext, Modifiers, MouseButton, MouseMoveEvent,
   7    MouseUpEvent, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformWindow, Point,
   8    PromptLevel, Render, ScaledPixels, SharedString, Size, SubscriberSet, Subscription,
   9    TaffyLayoutEngine, Task, View, VisualContext, WeakView, WindowAppearance, WindowBounds,
  10    WindowOptions, WindowTextSystem,
  11};
  12use anyhow::{anyhow, Context as _, Result};
  13use collections::FxHashSet;
  14use derive_more::{Deref, DerefMut};
  15use futures::channel::oneshot;
  16use parking_lot::RwLock;
  17use slotmap::SlotMap;
  18use smallvec::SmallVec;
  19use std::{
  20    any::{Any, TypeId},
  21    borrow::{Borrow, BorrowMut},
  22    cell::{Cell, RefCell},
  23    fmt::{Debug, Display},
  24    future::Future,
  25    hash::{Hash, Hasher},
  26    marker::PhantomData,
  27    mem,
  28    rc::Rc,
  29    sync::{
  30        atomic::{AtomicUsize, Ordering::SeqCst},
  31        Arc,
  32    },
  33    time::{Duration, Instant},
  34};
  35use util::{measure, ResultExt};
  36
  37mod element_cx;
  38pub use element_cx::*;
  39
  40const ACTIVE_DRAG_Z_INDEX: u16 = 1;
  41
  42/// A global stacking order, which is created by stacking successive z-index values.
  43/// Each z-index will always be interpreted in the context of its parent z-index.
  44#[derive(Debug, Deref, DerefMut, Clone, Ord, PartialOrd, PartialEq, Eq, Default)]
  45pub struct StackingOrder(SmallVec<[StackingContext; 64]>);
  46
  47/// A single entry in a primitive's z-index stacking order
  48#[derive(Clone, Ord, PartialOrd, PartialEq, Eq, Default)]
  49pub struct StackingContext {
  50    pub(crate) z_index: u16,
  51    pub(crate) id: u16,
  52}
  53
  54impl std::fmt::Debug for StackingContext {
  55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  56        write!(f, "{{{}.{}}} ", self.z_index, self.id)
  57    }
  58}
  59
  60/// Represents the two different phases when dispatching events.
  61#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
  62pub enum DispatchPhase {
  63    /// After the capture phase comes the bubble phase, in which mouse event listeners are
  64    /// invoked front to back and keyboard event listeners are invoked from the focused element
  65    /// to the root of the element tree. This is the phase you'll most commonly want to use when
  66    /// registering event listeners.
  67    #[default]
  68    Bubble,
  69    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
  70    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
  71    /// is used for special purposes such as clearing the "pressed" state for click events. If
  72    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
  73    /// outside of the immediate region may rely on detecting non-local events during this phase.
  74    Capture,
  75}
  76
  77impl DispatchPhase {
  78    /// Returns true if this represents the "bubble" phase.
  79    pub fn bubble(self) -> bool {
  80        self == DispatchPhase::Bubble
  81    }
  82
  83    /// Returns true if this represents the "capture" phase.
  84    pub fn capture(self) -> bool {
  85        self == DispatchPhase::Capture
  86    }
  87}
  88
  89type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
  90
  91type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
  92
  93struct FocusEvent {
  94    previous_focus_path: SmallVec<[FocusId; 8]>,
  95    current_focus_path: SmallVec<[FocusId; 8]>,
  96}
  97
  98slotmap::new_key_type! {
  99    /// A globally unique identifier for a focusable element.
 100    pub struct FocusId;
 101}
 102
 103thread_local! {
 104    pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(8 * 1024 * 1024));
 105}
 106
 107impl FocusId {
 108    /// Obtains whether the element associated with this handle is currently focused.
 109    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 110        cx.window.focus == Some(*self)
 111    }
 112
 113    /// Obtains whether the element associated with this handle contains the focused
 114    /// element or is itself focused.
 115    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 116        cx.focused()
 117            .map_or(false, |focused| self.contains(focused.id, cx))
 118    }
 119
 120    /// Obtains whether the element associated with this handle is contained within the
 121    /// focused element or is itself focused.
 122    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 123        let focused = cx.focused();
 124        focused.map_or(false, |focused| focused.id.contains(*self, cx))
 125    }
 126
 127    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 128    pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
 129        cx.window
 130            .rendered_frame
 131            .dispatch_tree
 132            .focus_contains(*self, other)
 133    }
 134}
 135
 136/// A handle which can be used to track and manipulate the focused element in a window.
 137pub struct FocusHandle {
 138    pub(crate) id: FocusId,
 139    handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 140}
 141
 142impl std::fmt::Debug for FocusHandle {
 143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 144        f.write_fmt(format_args!("FocusHandle({:?})", self.id))
 145    }
 146}
 147
 148impl FocusHandle {
 149    pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
 150        let id = handles.write().insert(AtomicUsize::new(1));
 151        Self {
 152            id,
 153            handles: handles.clone(),
 154        }
 155    }
 156
 157    pub(crate) fn for_id(
 158        id: FocusId,
 159        handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 160    ) -> Option<Self> {
 161        let lock = handles.read();
 162        let ref_count = lock.get(id)?;
 163        if ref_count.load(SeqCst) == 0 {
 164            None
 165        } else {
 166            ref_count.fetch_add(1, SeqCst);
 167            Some(Self {
 168                id,
 169                handles: handles.clone(),
 170            })
 171        }
 172    }
 173
 174    /// Moves the focus to the element associated with this handle.
 175    pub fn focus(&self, cx: &mut WindowContext) {
 176        cx.focus(self)
 177    }
 178
 179    /// Obtains whether the element associated with this handle is currently focused.
 180    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 181        self.id.is_focused(cx)
 182    }
 183
 184    /// Obtains whether the element associated with this handle contains the focused
 185    /// element or is itself focused.
 186    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 187        self.id.contains_focused(cx)
 188    }
 189
 190    /// Obtains whether the element associated with this handle is contained within the
 191    /// focused element or is itself focused.
 192    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 193        self.id.within_focused(cx)
 194    }
 195
 196    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 197    pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
 198        self.id.contains(other.id, cx)
 199    }
 200}
 201
 202impl Clone for FocusHandle {
 203    fn clone(&self) -> Self {
 204        Self::for_id(self.id, &self.handles).unwrap()
 205    }
 206}
 207
 208impl PartialEq for FocusHandle {
 209    fn eq(&self, other: &Self) -> bool {
 210        self.id == other.id
 211    }
 212}
 213
 214impl Eq for FocusHandle {}
 215
 216impl Drop for FocusHandle {
 217    fn drop(&mut self) {
 218        self.handles
 219            .read()
 220            .get(self.id)
 221            .unwrap()
 222            .fetch_sub(1, SeqCst);
 223    }
 224}
 225
 226/// FocusableView allows users of your view to easily
 227/// focus it (using cx.focus_view(view))
 228pub trait FocusableView: 'static + Render {
 229    /// Returns the focus handle associated with this view.
 230    fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
 231}
 232
 233/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
 234/// where the lifecycle of the view is handled by another view.
 235pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
 236
 237impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
 238
 239/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
 240pub struct DismissEvent;
 241
 242type FrameCallback = Box<dyn FnOnce(&mut WindowContext)>;
 243
 244// Holds the state for a specific window.
 245#[doc(hidden)]
 246pub struct Window {
 247    pub(crate) handle: AnyWindowHandle,
 248    pub(crate) removed: bool,
 249    pub(crate) platform_window: Box<dyn PlatformWindow>,
 250    display_id: DisplayId,
 251    sprite_atlas: Arc<dyn PlatformAtlas>,
 252    text_system: Arc<WindowTextSystem>,
 253    pub(crate) rem_size: Pixels,
 254    pub(crate) viewport_size: Size<Pixels>,
 255    layout_engine: Option<TaffyLayoutEngine>,
 256    pub(crate) root_view: Option<AnyView>,
 257    pub(crate) element_id_stack: GlobalElementId,
 258    pub(crate) rendered_frame: Frame,
 259    pub(crate) next_frame: Frame,
 260    next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
 261    pub(crate) dirty_views: FxHashSet<EntityId>,
 262    pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 263    focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
 264    focus_lost_listeners: SubscriberSet<(), AnyObserver>,
 265    default_prevented: bool,
 266    mouse_position: Point<Pixels>,
 267    modifiers: Modifiers,
 268    scale_factor: f32,
 269    bounds: WindowBounds,
 270    bounds_observers: SubscriberSet<(), AnyObserver>,
 271    appearance: WindowAppearance,
 272    appearance_observers: SubscriberSet<(), AnyObserver>,
 273    active: Rc<Cell<bool>>,
 274    pub(crate) dirty: Rc<Cell<bool>>,
 275    pub(crate) needs_present: Rc<Cell<bool>>,
 276    pub(crate) last_input_timestamp: Rc<Cell<Instant>>,
 277    pub(crate) refreshing: bool,
 278    pub(crate) drawing: bool,
 279    activation_observers: SubscriberSet<(), AnyObserver>,
 280    pub(crate) focus: Option<FocusId>,
 281    focus_enabled: bool,
 282    pending_input: Option<PendingInput>,
 283    graphics_profiler_enabled: bool,
 284}
 285
 286#[derive(Default, Debug)]
 287struct PendingInput {
 288    keystrokes: SmallVec<[Keystroke; 1]>,
 289    bindings: SmallVec<[KeyBinding; 1]>,
 290    focus: Option<FocusId>,
 291    timer: Option<Task<()>>,
 292}
 293
 294impl PendingInput {
 295    fn input(&self) -> String {
 296        self.keystrokes
 297            .iter()
 298            .flat_map(|k| k.ime_key.clone())
 299            .collect::<Vec<String>>()
 300            .join("")
 301    }
 302
 303    fn used_by_binding(&self, binding: &KeyBinding) -> bool {
 304        if self.keystrokes.is_empty() {
 305            return true;
 306        }
 307        let keystroke = &self.keystrokes[0];
 308        for candidate in keystroke.match_candidates() {
 309            if binding.match_keystrokes(&[candidate]) == KeyMatch::Pending {
 310                return true;
 311            }
 312        }
 313        false
 314    }
 315}
 316
 317pub(crate) struct ElementStateBox {
 318    pub(crate) inner: Box<dyn Any>,
 319    pub(crate) parent_view_id: EntityId,
 320    #[cfg(debug_assertions)]
 321    pub(crate) type_name: &'static str,
 322}
 323
 324impl Window {
 325    pub(crate) fn new(
 326        handle: AnyWindowHandle,
 327        options: WindowOptions,
 328        cx: &mut AppContext,
 329    ) -> Self {
 330        let platform_window = cx.platform.open_window(handle, options);
 331        let display_id = platform_window.display().id();
 332        let sprite_atlas = platform_window.sprite_atlas();
 333        let mouse_position = platform_window.mouse_position();
 334        let modifiers = platform_window.modifiers();
 335        let content_size = platform_window.content_size();
 336        let scale_factor = platform_window.scale_factor();
 337        let bounds = platform_window.bounds();
 338        let appearance = platform_window.appearance();
 339        let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
 340        let dirty = Rc::new(Cell::new(true));
 341        let active = Rc::new(Cell::new(false));
 342        let needs_present = Rc::new(Cell::new(false));
 343        let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
 344        let last_input_timestamp = Rc::new(Cell::new(Instant::now()));
 345
 346        platform_window.on_close(Box::new({
 347            let mut cx = cx.to_async();
 348            move || {
 349                let _ = handle.update(&mut cx, |_, cx| cx.remove_window());
 350            }
 351        }));
 352        platform_window.on_request_frame(Box::new({
 353            let mut cx = cx.to_async();
 354            let dirty = dirty.clone();
 355            let active = active.clone();
 356            let needs_present = needs_present.clone();
 357            let next_frame_callbacks = next_frame_callbacks.clone();
 358            let last_input_timestamp = last_input_timestamp.clone();
 359            move || {
 360                let next_frame_callbacks = next_frame_callbacks.take();
 361                if !next_frame_callbacks.is_empty() {
 362                    handle
 363                        .update(&mut cx, |_, cx| {
 364                            for callback in next_frame_callbacks {
 365                                callback(cx);
 366                            }
 367                        })
 368                        .log_err();
 369                }
 370
 371                // Keep presenting the current scene for 1 extra second since the
 372                // last input to prevent the display from underclocking the refresh rate.
 373                let needs_present = needs_present.get()
 374                    || (active.get()
 375                        && last_input_timestamp.get().elapsed() < Duration::from_secs(1));
 376
 377                if dirty.get() {
 378                    measure("frame duration", || {
 379                        handle
 380                            .update(&mut cx, |_, cx| {
 381                                cx.draw();
 382                                cx.present();
 383                            })
 384                            .log_err();
 385                    })
 386                } else if needs_present {
 387                    handle.update(&mut cx, |_, cx| cx.present()).log_err();
 388                }
 389            }
 390        }));
 391        platform_window.on_resize(Box::new({
 392            let mut cx = cx.to_async();
 393            move |_, _| {
 394                handle
 395                    .update(&mut cx, |_, cx| cx.window_bounds_changed())
 396                    .log_err();
 397            }
 398        }));
 399        platform_window.on_moved(Box::new({
 400            let mut cx = cx.to_async();
 401            move || {
 402                handle
 403                    .update(&mut cx, |_, cx| cx.window_bounds_changed())
 404                    .log_err();
 405            }
 406        }));
 407        platform_window.on_appearance_changed(Box::new({
 408            let mut cx = cx.to_async();
 409            move || {
 410                handle
 411                    .update(&mut cx, |_, cx| cx.appearance_changed())
 412                    .log_err();
 413            }
 414        }));
 415        platform_window.on_active_status_change(Box::new({
 416            let mut cx = cx.to_async();
 417            move |active| {
 418                handle
 419                    .update(&mut cx, |_, cx| {
 420                        cx.window.active.set(active);
 421                        cx.window
 422                            .activation_observers
 423                            .clone()
 424                            .retain(&(), |callback| callback(cx));
 425                    })
 426                    .log_err();
 427            }
 428        }));
 429
 430        platform_window.on_input({
 431            let mut cx = cx.to_async();
 432            Box::new(move |event| {
 433                handle
 434                    .update(&mut cx, |_, cx| cx.dispatch_event(event))
 435                    .log_err()
 436                    .unwrap_or(false)
 437            })
 438        });
 439
 440        Window {
 441            handle,
 442            removed: false,
 443            platform_window,
 444            display_id,
 445            sprite_atlas,
 446            text_system,
 447            rem_size: px(16.),
 448            viewport_size: content_size,
 449            layout_engine: Some(TaffyLayoutEngine::new()),
 450            root_view: None,
 451            element_id_stack: GlobalElementId::default(),
 452            rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 453            next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 454            next_frame_callbacks,
 455            dirty_views: FxHashSet::default(),
 456            focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
 457            focus_listeners: SubscriberSet::new(),
 458            focus_lost_listeners: SubscriberSet::new(),
 459            default_prevented: true,
 460            mouse_position,
 461            modifiers,
 462            scale_factor,
 463            bounds,
 464            bounds_observers: SubscriberSet::new(),
 465            appearance,
 466            appearance_observers: SubscriberSet::new(),
 467            active,
 468            dirty,
 469            needs_present,
 470            last_input_timestamp,
 471            refreshing: false,
 472            drawing: false,
 473            activation_observers: SubscriberSet::new(),
 474            focus: None,
 475            focus_enabled: true,
 476            pending_input: None,
 477            graphics_profiler_enabled: false,
 478        }
 479    }
 480    fn new_focus_listener(
 481        &mut self,
 482        value: AnyWindowFocusListener,
 483    ) -> (Subscription, impl FnOnce()) {
 484        self.focus_listeners.insert((), value)
 485    }
 486}
 487
 488/// Indicates which region of the window is visible. Content falling outside of this mask will not be
 489/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
 490/// to leave room to support more complex shapes in the future.
 491#[derive(Clone, Debug, Default, PartialEq, Eq)]
 492#[repr(C)]
 493pub struct ContentMask<P: Clone + Default + Debug> {
 494    /// The bounds
 495    pub bounds: Bounds<P>,
 496}
 497
 498impl ContentMask<Pixels> {
 499    /// Scale the content mask's pixel units by the given scaling factor.
 500    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
 501        ContentMask {
 502            bounds: self.bounds.scale(factor),
 503        }
 504    }
 505
 506    /// Intersect the content mask with the given content mask.
 507    pub fn intersect(&self, other: &Self) -> Self {
 508        let bounds = self.bounds.intersect(&other.bounds);
 509        ContentMask { bounds }
 510    }
 511}
 512
 513/// Provides access to application state in the context of a single window. Derefs
 514/// to an [`AppContext`], so you can also pass a [`WindowContext`] to any method that takes
 515/// an [`AppContext`] and call any [`AppContext`] methods.
 516pub struct WindowContext<'a> {
 517    pub(crate) app: &'a mut AppContext,
 518    pub(crate) window: &'a mut Window,
 519}
 520
 521impl<'a> WindowContext<'a> {
 522    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
 523        Self { app, window }
 524    }
 525
 526    /// Obtain a handle to the window that belongs to this context.
 527    pub fn window_handle(&self) -> AnyWindowHandle {
 528        self.window.handle
 529    }
 530
 531    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
 532    pub fn refresh(&mut self) {
 533        if !self.window.drawing {
 534            self.window.refreshing = true;
 535            self.window.dirty.set(true);
 536        }
 537    }
 538
 539    /// Close this window.
 540    pub fn remove_window(&mut self) {
 541        self.window.removed = true;
 542    }
 543
 544    /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
 545    /// for elements rendered within this window.
 546    pub fn focus_handle(&mut self) -> FocusHandle {
 547        FocusHandle::new(&self.window.focus_handles)
 548    }
 549
 550    /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
 551    pub fn focused(&self) -> Option<FocusHandle> {
 552        self.window
 553            .focus
 554            .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
 555    }
 556
 557    /// Move focus to the element associated with the given [`FocusHandle`].
 558    pub fn focus(&mut self, handle: &FocusHandle) {
 559        if !self.window.focus_enabled || self.window.focus == Some(handle.id) {
 560            return;
 561        }
 562
 563        self.window.focus = Some(handle.id);
 564        self.window
 565            .rendered_frame
 566            .dispatch_tree
 567            .clear_pending_keystrokes();
 568        self.refresh();
 569    }
 570
 571    /// Remove focus from all elements within this context's window.
 572    pub fn blur(&mut self) {
 573        if !self.window.focus_enabled {
 574            return;
 575        }
 576
 577        self.window.focus = None;
 578        self.refresh();
 579    }
 580
 581    /// Blur the window and don't allow anything in it to be focused again.
 582    pub fn disable_focus(&mut self) {
 583        self.blur();
 584        self.window.focus_enabled = false;
 585    }
 586
 587    /// Accessor for the text system.
 588    pub fn text_system(&self) -> &Arc<WindowTextSystem> {
 589        &self.window.text_system
 590    }
 591
 592    /// Dispatch the given action on the currently focused element.
 593    pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
 594        let focus_handle = self.focused();
 595
 596        self.defer(move |cx| {
 597            let node_id = focus_handle
 598                .and_then(|handle| {
 599                    cx.window
 600                        .rendered_frame
 601                        .dispatch_tree
 602                        .focusable_node_id(handle.id)
 603                })
 604                .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
 605
 606            cx.propagate_event = true;
 607            cx.dispatch_action_on_node(node_id, action);
 608        })
 609    }
 610
 611    pub(crate) fn dispatch_keystroke_observers(
 612        &mut self,
 613        event: &dyn Any,
 614        action: Option<Box<dyn Action>>,
 615    ) {
 616        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
 617            return;
 618        };
 619
 620        self.keystroke_observers
 621            .clone()
 622            .retain(&(), move |callback| {
 623                (callback)(
 624                    &KeystrokeEvent {
 625                        keystroke: key_down_event.keystroke.clone(),
 626                        action: action.as_ref().map(|action| action.boxed_clone()),
 627                    },
 628                    self,
 629                );
 630                true
 631            });
 632    }
 633
 634    pub(crate) fn clear_pending_keystrokes(&mut self) {
 635        self.window
 636            .rendered_frame
 637            .dispatch_tree
 638            .clear_pending_keystrokes();
 639        self.window
 640            .next_frame
 641            .dispatch_tree
 642            .clear_pending_keystrokes();
 643    }
 644
 645    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
 646    /// that are currently on the stack to be returned to the app.
 647    pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
 648        let handle = self.window.handle;
 649        self.app.defer(move |cx| {
 650            handle.update(cx, |_, cx| f(cx)).ok();
 651        });
 652    }
 653
 654    /// Subscribe to events emitted by a model or view.
 655    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
 656    /// 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.
 657    pub fn subscribe<Emitter, E, Evt>(
 658        &mut self,
 659        entity: &E,
 660        mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
 661    ) -> Subscription
 662    where
 663        Emitter: EventEmitter<Evt>,
 664        E: Entity<Emitter>,
 665        Evt: 'static,
 666    {
 667        let entity_id = entity.entity_id();
 668        let entity = entity.downgrade();
 669        let window_handle = self.window.handle;
 670        self.app.new_subscription(
 671            entity_id,
 672            (
 673                TypeId::of::<Evt>(),
 674                Box::new(move |event, cx| {
 675                    window_handle
 676                        .update(cx, |_, cx| {
 677                            if let Some(handle) = E::upgrade_from(&entity) {
 678                                let event = event.downcast_ref().expect("invalid event type");
 679                                on_event(handle, event, cx);
 680                                true
 681                            } else {
 682                                false
 683                            }
 684                        })
 685                        .unwrap_or(false)
 686                }),
 687            ),
 688        )
 689    }
 690
 691    /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
 692    /// await points in async code.
 693    pub fn to_async(&self) -> AsyncWindowContext {
 694        AsyncWindowContext::new(self.app.to_async(), self.window.handle)
 695    }
 696
 697    /// Schedule the given closure to be run directly after the current frame is rendered.
 698    pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
 699        RefCell::borrow_mut(&self.window.next_frame_callbacks).push(Box::new(callback));
 700    }
 701
 702    /// Spawn the future returned by the given closure on the application thread pool.
 703    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
 704    /// use within your future.
 705    pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
 706    where
 707        R: 'static,
 708        Fut: Future<Output = R> + 'static,
 709    {
 710        self.app
 711            .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
 712    }
 713
 714    /// Updates the global of the given type. The given closure is given simultaneous mutable
 715    /// access both to the global and the context.
 716    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
 717    where
 718        G: Global,
 719    {
 720        let mut global = self.app.lease_global::<G>();
 721        let result = f(&mut global, self);
 722        self.app.end_global_lease(global);
 723        result
 724    }
 725
 726    fn window_bounds_changed(&mut self) {
 727        self.window.scale_factor = self.window.platform_window.scale_factor();
 728        self.window.viewport_size = self.window.platform_window.content_size();
 729        self.window.bounds = self.window.platform_window.bounds();
 730        self.window.display_id = self.window.platform_window.display().id();
 731        self.refresh();
 732
 733        self.window
 734            .bounds_observers
 735            .clone()
 736            .retain(&(), |callback| callback(self));
 737    }
 738
 739    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
 740    pub fn window_bounds(&self) -> WindowBounds {
 741        self.window.bounds
 742    }
 743
 744    fn appearance_changed(&mut self) {
 745        self.window.appearance = self.window.platform_window.appearance();
 746
 747        self.window
 748            .appearance_observers
 749            .clone()
 750            .retain(&(), |callback| callback(self));
 751    }
 752
 753    /// Returns the appearance of the current window.
 754    pub fn appearance(&self) -> WindowAppearance {
 755        self.window.appearance
 756    }
 757
 758    /// Returns the size of the drawable area within the window.
 759    pub fn viewport_size(&self) -> Size<Pixels> {
 760        self.window.viewport_size
 761    }
 762
 763    /// Returns whether this window is focused by the operating system (receiving key events).
 764    pub fn is_window_active(&self) -> bool {
 765        self.window.active.get()
 766    }
 767
 768    /// Toggle zoom on the window.
 769    pub fn zoom_window(&self) {
 770        self.window.platform_window.zoom();
 771    }
 772
 773    /// Updates the window's title at the platform level.
 774    pub fn set_window_title(&mut self, title: &str) {
 775        self.window.platform_window.set_title(title);
 776    }
 777
 778    /// Mark the window as dirty at the platform level.
 779    pub fn set_window_edited(&mut self, edited: bool) {
 780        self.window.platform_window.set_edited(edited);
 781    }
 782
 783    /// Determine the display on which the window is visible.
 784    pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 785        self.platform
 786            .displays()
 787            .into_iter()
 788            .find(|display| display.id() == self.window.display_id)
 789    }
 790
 791    /// Show the platform character palette.
 792    pub fn show_character_palette(&self) {
 793        self.window.platform_window.show_character_palette();
 794    }
 795
 796    /// The scale factor of the display associated with the window. For example, it could
 797    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
 798    /// be rendered as two pixels on screen.
 799    pub fn scale_factor(&self) -> f32 {
 800        self.window.scale_factor
 801    }
 802
 803    /// The size of an em for the base font of the application. Adjusting this value allows the
 804    /// UI to scale, just like zooming a web page.
 805    pub fn rem_size(&self) -> Pixels {
 806        self.window.rem_size
 807    }
 808
 809    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
 810    /// UI to scale, just like zooming a web page.
 811    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
 812        self.window.rem_size = rem_size.into();
 813    }
 814
 815    /// The line height associated with the current text style.
 816    pub fn line_height(&self) -> Pixels {
 817        let rem_size = self.rem_size();
 818        let text_style = self.text_style();
 819        text_style
 820            .line_height
 821            .to_pixels(text_style.font_size, rem_size)
 822    }
 823
 824    /// Call to prevent the default action of an event. Currently only used to prevent
 825    /// parent elements from becoming focused on mouse down.
 826    pub fn prevent_default(&mut self) {
 827        self.window.default_prevented = true;
 828    }
 829
 830    /// Obtain whether default has been prevented for the event currently being dispatched.
 831    pub fn default_prevented(&self) -> bool {
 832        self.window.default_prevented
 833    }
 834
 835    /// Determine whether the given action is available along the dispatch path to the currently focused element.
 836    pub fn is_action_available(&self, action: &dyn Action) -> bool {
 837        let target = self
 838            .focused()
 839            .and_then(|focused_handle| {
 840                self.window
 841                    .rendered_frame
 842                    .dispatch_tree
 843                    .focusable_node_id(focused_handle.id)
 844            })
 845            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
 846        self.window
 847            .rendered_frame
 848            .dispatch_tree
 849            .is_action_available(action, target)
 850    }
 851
 852    /// The position of the mouse relative to the window.
 853    pub fn mouse_position(&self) -> Point<Pixels> {
 854        self.window.mouse_position
 855    }
 856
 857    /// The current state of the keyboard's modifiers
 858    pub fn modifiers(&self) -> Modifiers {
 859        self.window.modifiers
 860    }
 861
 862    /// Returns true if there is no opaque layer containing the given point
 863    /// on top of the given level. Layers who are extensions of the queried layer
 864    /// are not considered to be on top of queried layer.
 865    pub fn was_top_layer(&self, point: &Point<Pixels>, layer: &StackingOrder) -> bool {
 866        // Precondition: the depth map is ordered from topmost to bottomost.
 867
 868        for (opaque_layer, _, bounds) in self.window.rendered_frame.depth_map.iter() {
 869            if layer >= opaque_layer {
 870                // The queried layer is either above or is the same as the this opaque layer.
 871                // Anything after this point is guaranteed to be below the queried layer.
 872                return true;
 873            }
 874
 875            if !bounds.contains(point) {
 876                // This opaque layer is above the queried layer but it doesn't contain
 877                // the given position, so we can ignore it even if it's above.
 878                continue;
 879            }
 880
 881            // At this point, we've established that this opaque layer is on top of the queried layer
 882            // and contains the position:
 883            // If neither the opaque layer or the queried layer is an extension of the other then
 884            // we know they are on different stacking orders, and return false.
 885            let is_on_same_layer = opaque_layer
 886                .iter()
 887                .zip(layer.iter())
 888                .all(|(a, b)| a.z_index == b.z_index);
 889
 890            if !is_on_same_layer {
 891                return false;
 892            }
 893        }
 894
 895        true
 896    }
 897
 898    pub(crate) fn was_top_layer_under_active_drag(
 899        &self,
 900        point: &Point<Pixels>,
 901        layer: &StackingOrder,
 902    ) -> bool {
 903        // Precondition: the depth map is ordered from topmost to bottomost.
 904
 905        for (opaque_layer, _, bounds) in self.window.rendered_frame.depth_map.iter() {
 906            if layer >= opaque_layer {
 907                // The queried layer is either above or is the same as the this opaque layer.
 908                // Anything after this point is guaranteed to be below the queried layer.
 909                return true;
 910            }
 911
 912            if !bounds.contains(point) {
 913                // This opaque layer is above the queried layer but it doesn't contain
 914                // the given position, so we can ignore it even if it's above.
 915                continue;
 916            }
 917
 918            // All normal content is rendered with a base z-index of 0, we know that if the root of this opaque layer
 919            // equals `ACTIVE_DRAG_Z_INDEX` then it must be the drag layer and we can ignore it as we are
 920            // looking to see if the queried layer was the topmost underneath the drag layer.
 921            if opaque_layer
 922                .first()
 923                .map(|c| c.z_index == ACTIVE_DRAG_Z_INDEX)
 924                .unwrap_or(false)
 925            {
 926                continue;
 927            }
 928
 929            // At this point, we've established that this opaque layer is on top of the queried layer
 930            // and contains the position:
 931            // If neither the opaque layer or the queried layer is an extension of the other then
 932            // we know they are on different stacking orders, and return false.
 933            let is_on_same_layer = opaque_layer
 934                .iter()
 935                .zip(layer.iter())
 936                .all(|(a, b)| a.z_index == b.z_index);
 937
 938            if !is_on_same_layer {
 939                return false;
 940            }
 941        }
 942
 943        true
 944    }
 945
 946    /// Called during painting to get the current stacking order.
 947    pub fn stacking_order(&self) -> &StackingOrder {
 948        &self.window.next_frame.z_index_stack
 949    }
 950
 951    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
 952    /// the contents of the new [Scene], use [present].
 953    #[profiling::function]
 954    pub fn draw(&mut self) {
 955        self.window.dirty.set(false);
 956        self.window.drawing = true;
 957
 958        if let Some(requested_handler) = self.window.rendered_frame.requested_input_handler.as_mut()
 959        {
 960            let input_handler = self.window.platform_window.take_input_handler();
 961            requested_handler.handler = input_handler;
 962        }
 963
 964        let root_view = self.window.root_view.take().unwrap();
 965        self.with_element_context(|cx| {
 966            cx.with_z_index(0, |cx| {
 967                cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| {
 968                    // We need to use cx.cx here so we can utilize borrow splitting
 969                    for (action_type, action_listeners) in &cx.cx.app.global_action_listeners {
 970                        for action_listener in action_listeners.iter().cloned() {
 971                            cx.cx.window.next_frame.dispatch_tree.on_action(
 972                                *action_type,
 973                                Rc::new(
 974                                    move |action: &dyn Any, phase, cx: &mut WindowContext<'_>| {
 975                                        action_listener(action, phase, cx)
 976                                    },
 977                                ),
 978                            )
 979                        }
 980                    }
 981
 982                    let available_space = cx.window.viewport_size.map(Into::into);
 983                    root_view.draw(Point::default(), available_space, cx);
 984                })
 985            })
 986        });
 987
 988        if let Some(active_drag) = self.app.active_drag.take() {
 989            self.with_element_context(|cx| {
 990                cx.with_z_index(ACTIVE_DRAG_Z_INDEX, |cx| {
 991                    let offset = cx.mouse_position() - active_drag.cursor_offset;
 992                    let available_space =
 993                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
 994                    active_drag.view.draw(offset, available_space, cx);
 995                })
 996            });
 997            self.active_drag = Some(active_drag);
 998        } else if let Some(tooltip_request) = self.window.next_frame.tooltip_request.take() {
 999            self.with_element_context(|cx| {
1000                cx.with_z_index(1, |cx| {
1001                    let available_space =
1002                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1003                    tooltip_request.tooltip.view.draw(
1004                        tooltip_request.tooltip.cursor_offset,
1005                        available_space,
1006                        cx,
1007                    );
1008                })
1009            });
1010            self.window.next_frame.tooltip_request = Some(tooltip_request);
1011        }
1012        self.window.dirty_views.clear();
1013
1014        self.window
1015            .next_frame
1016            .dispatch_tree
1017            .preserve_pending_keystrokes(
1018                &mut self.window.rendered_frame.dispatch_tree,
1019                self.window.focus,
1020            );
1021        self.window.next_frame.focus = self.window.focus;
1022        self.window.next_frame.window_active = self.window.active.get();
1023        self.window.root_view = Some(root_view);
1024
1025        // Set the cursor only if we're the active window.
1026        let cursor_style_request = self.window.next_frame.requested_cursor_style.take();
1027        if self.is_window_active() {
1028            let cursor_style =
1029                cursor_style_request.map_or(CursorStyle::Arrow, |request| request.style);
1030            self.platform.set_cursor_style(cursor_style);
1031        }
1032
1033        // Register requested input handler with the platform window.
1034        if let Some(requested_input) = self.window.next_frame.requested_input_handler.as_mut() {
1035            if let Some(handler) = requested_input.handler.take() {
1036                self.window.platform_window.set_input_handler(handler);
1037            }
1038        }
1039
1040        self.window.layout_engine.as_mut().unwrap().clear();
1041        self.text_system()
1042            .finish_frame(&self.window.next_frame.reused_views);
1043        self.window
1044            .next_frame
1045            .finish(&mut self.window.rendered_frame);
1046        ELEMENT_ARENA.with_borrow_mut(|element_arena| {
1047            let percentage = (element_arena.len() as f32 / element_arena.capacity() as f32) * 100.;
1048            if percentage >= 80. {
1049                log::warn!("elevated element arena occupation: {}.", percentage);
1050            }
1051            element_arena.clear();
1052        });
1053
1054        let previous_focus_path = self.window.rendered_frame.focus_path();
1055        let previous_window_active = self.window.rendered_frame.window_active;
1056        mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1057        self.window.next_frame.clear();
1058        let current_focus_path = self.window.rendered_frame.focus_path();
1059        let current_window_active = self.window.rendered_frame.window_active;
1060
1061        if previous_focus_path != current_focus_path
1062            || previous_window_active != current_window_active
1063        {
1064            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1065                self.window
1066                    .focus_lost_listeners
1067                    .clone()
1068                    .retain(&(), |listener| listener(self));
1069            }
1070
1071            let event = FocusEvent {
1072                previous_focus_path: if previous_window_active {
1073                    previous_focus_path
1074                } else {
1075                    Default::default()
1076                },
1077                current_focus_path: if current_window_active {
1078                    current_focus_path
1079                } else {
1080                    Default::default()
1081                },
1082            };
1083            self.window
1084                .focus_listeners
1085                .clone()
1086                .retain(&(), |listener| listener(&event, self));
1087        }
1088        self.window.refreshing = false;
1089        self.window.drawing = false;
1090        self.window.needs_present.set(true);
1091    }
1092
1093    #[profiling::function]
1094    fn present(&self) {
1095        self.window
1096            .platform_window
1097            .draw(&self.window.rendered_frame.scene);
1098        self.window.needs_present.set(false);
1099        profiling::finish_frame!();
1100    }
1101
1102    /// Dispatch a given keystroke as though the user had typed it.
1103    /// You can create a keystroke with Keystroke::parse("").
1104    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke) -> bool {
1105        let keystroke = keystroke.with_simulated_ime();
1106        if self.dispatch_event(PlatformInput::KeyDown(KeyDownEvent {
1107            keystroke: keystroke.clone(),
1108            is_held: false,
1109        })) {
1110            return true;
1111        }
1112
1113        if let Some(input) = keystroke.ime_key {
1114            if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
1115                input_handler.dispatch_input(&input, self);
1116                self.window.platform_window.set_input_handler(input_handler);
1117                return true;
1118            }
1119        }
1120
1121        false
1122    }
1123
1124    /// Represent this action as a key binding string, to display in the UI.
1125    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
1126        self.bindings_for_action(action)
1127            .into_iter()
1128            .next()
1129            .map(|binding| {
1130                binding
1131                    .keystrokes()
1132                    .iter()
1133                    .map(ToString::to_string)
1134                    .collect::<Vec<_>>()
1135                    .join(" ")
1136            })
1137            .unwrap_or_else(|| action.name().to_string())
1138    }
1139
1140    /// Dispatch a mouse or keyboard event on the window.
1141    #[profiling::function]
1142    pub fn dispatch_event(&mut self, event: PlatformInput) -> bool {
1143        self.window.last_input_timestamp.set(Instant::now());
1144        // Handlers may set this to false by calling `stop_propagation`.
1145        self.app.propagate_event = true;
1146        // Handlers may set this to true by calling `prevent_default`.
1147        self.window.default_prevented = false;
1148
1149        let event = match event {
1150            // Track the mouse position with our own state, since accessing the platform
1151            // API for the mouse position can only occur on the main thread.
1152            PlatformInput::MouseMove(mouse_move) => {
1153                self.window.mouse_position = mouse_move.position;
1154                self.window.modifiers = mouse_move.modifiers;
1155                PlatformInput::MouseMove(mouse_move)
1156            }
1157            PlatformInput::MouseDown(mouse_down) => {
1158                self.window.mouse_position = mouse_down.position;
1159                self.window.modifiers = mouse_down.modifiers;
1160                PlatformInput::MouseDown(mouse_down)
1161            }
1162            PlatformInput::MouseUp(mouse_up) => {
1163                self.window.mouse_position = mouse_up.position;
1164                self.window.modifiers = mouse_up.modifiers;
1165                PlatformInput::MouseUp(mouse_up)
1166            }
1167            PlatformInput::MouseExited(mouse_exited) => {
1168                self.window.modifiers = mouse_exited.modifiers;
1169                PlatformInput::MouseExited(mouse_exited)
1170            }
1171            PlatformInput::ModifiersChanged(modifiers_changed) => {
1172                self.window.modifiers = modifiers_changed.modifiers;
1173                PlatformInput::ModifiersChanged(modifiers_changed)
1174            }
1175            PlatformInput::ScrollWheel(scroll_wheel) => {
1176                self.window.mouse_position = scroll_wheel.position;
1177                self.window.modifiers = scroll_wheel.modifiers;
1178                PlatformInput::ScrollWheel(scroll_wheel)
1179            }
1180            // Translate dragging and dropping of external files from the operating system
1181            // to internal drag and drop events.
1182            PlatformInput::FileDrop(file_drop) => match file_drop {
1183                FileDropEvent::Entered { position, paths } => {
1184                    self.window.mouse_position = position;
1185                    if self.active_drag.is_none() {
1186                        self.active_drag = Some(AnyDrag {
1187                            value: Box::new(paths.clone()),
1188                            view: self.new_view(|_| paths).into(),
1189                            cursor_offset: position,
1190                        });
1191                    }
1192                    PlatformInput::MouseMove(MouseMoveEvent {
1193                        position,
1194                        pressed_button: Some(MouseButton::Left),
1195                        modifiers: Modifiers::default(),
1196                    })
1197                }
1198                FileDropEvent::Pending { position } => {
1199                    self.window.mouse_position = position;
1200                    PlatformInput::MouseMove(MouseMoveEvent {
1201                        position,
1202                        pressed_button: Some(MouseButton::Left),
1203                        modifiers: Modifiers::default(),
1204                    })
1205                }
1206                FileDropEvent::Submit { position } => {
1207                    self.activate(true);
1208                    self.window.mouse_position = position;
1209                    PlatformInput::MouseUp(MouseUpEvent {
1210                        button: MouseButton::Left,
1211                        position,
1212                        modifiers: Modifiers::default(),
1213                        click_count: 1,
1214                    })
1215                }
1216                FileDropEvent::Exited => PlatformInput::MouseUp(MouseUpEvent {
1217                    button: MouseButton::Left,
1218                    position: Point::default(),
1219                    modifiers: Modifiers::default(),
1220                    click_count: 1,
1221                }),
1222            },
1223            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
1224        };
1225
1226        if let Some(any_mouse_event) = event.mouse_event() {
1227            self.dispatch_mouse_event(any_mouse_event);
1228        } else if let Some(any_key_event) = event.keyboard_event() {
1229            self.dispatch_key_event(any_key_event);
1230        }
1231
1232        !self.app.propagate_event
1233    }
1234
1235    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1236        if let Some(mut handlers) = self
1237            .window
1238            .rendered_frame
1239            .mouse_listeners
1240            .remove(&event.type_id())
1241        {
1242            // Because handlers may add other handlers, we sort every time.
1243            handlers.sort_by(|(a, _, _), (b, _, _)| a.cmp(b));
1244
1245            // Capture phase, events bubble from back to front. Handlers for this phase are used for
1246            // special purposes, such as detecting events outside of a given Bounds.
1247            for (_, _, handler) in &mut handlers {
1248                self.with_element_context(|cx| {
1249                    handler(event, DispatchPhase::Capture, cx);
1250                });
1251                if !self.app.propagate_event {
1252                    break;
1253                }
1254            }
1255
1256            // Bubble phase, where most normal handlers do their work.
1257            if self.app.propagate_event {
1258                for (_, _, handler) in handlers.iter_mut().rev() {
1259                    self.with_element_context(|cx| {
1260                        handler(event, DispatchPhase::Bubble, cx);
1261                    });
1262                    if !self.app.propagate_event {
1263                        break;
1264                    }
1265                }
1266            }
1267
1268            self.window
1269                .rendered_frame
1270                .mouse_listeners
1271                .insert(event.type_id(), handlers);
1272        }
1273
1274        if self.app.propagate_event && self.has_active_drag() {
1275            if event.is::<MouseMoveEvent>() {
1276                // If this was a mouse move event, redraw the window so that the
1277                // active drag can follow the mouse cursor.
1278                self.refresh();
1279            } else if event.is::<MouseUpEvent>() {
1280                // If this was a mouse up event, cancel the active drag and redraw
1281                // the window.
1282                self.active_drag = None;
1283                self.refresh();
1284            }
1285        }
1286    }
1287
1288    fn dispatch_key_event(&mut self, event: &dyn Any) {
1289        if self.window.dirty.get() {
1290            self.draw();
1291        }
1292
1293        let node_id = self
1294            .window
1295            .focus
1296            .and_then(|focus_id| {
1297                self.window
1298                    .rendered_frame
1299                    .dispatch_tree
1300                    .focusable_node_id(focus_id)
1301            })
1302            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1303
1304        let dispatch_path = self
1305            .window
1306            .rendered_frame
1307            .dispatch_tree
1308            .dispatch_path(node_id);
1309
1310        if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1311            let KeymatchResult { bindings, pending } = self
1312                .window
1313                .rendered_frame
1314                .dispatch_tree
1315                .dispatch_key(&key_down_event.keystroke, &dispatch_path);
1316
1317            if pending {
1318                let mut currently_pending = self.window.pending_input.take().unwrap_or_default();
1319                if currently_pending.focus.is_some() && currently_pending.focus != self.window.focus
1320                {
1321                    currently_pending = PendingInput::default();
1322                }
1323                currently_pending.focus = self.window.focus;
1324                currently_pending
1325                    .keystrokes
1326                    .push(key_down_event.keystroke.clone());
1327                for binding in bindings {
1328                    currently_pending.bindings.push(binding);
1329                }
1330
1331                currently_pending.timer = Some(self.spawn(|mut cx| async move {
1332                    cx.background_executor.timer(Duration::from_secs(1)).await;
1333                    cx.update(move |cx| {
1334                        cx.clear_pending_keystrokes();
1335                        let Some(currently_pending) = cx.window.pending_input.take() else {
1336                            return;
1337                        };
1338                        cx.replay_pending_input(currently_pending)
1339                    })
1340                    .log_err();
1341                }));
1342                self.window.pending_input = Some(currently_pending);
1343
1344                self.propagate_event = false;
1345                return;
1346            } else if let Some(currently_pending) = self.window.pending_input.take() {
1347                if bindings
1348                    .iter()
1349                    .all(|binding| !currently_pending.used_by_binding(binding))
1350                {
1351                    self.replay_pending_input(currently_pending)
1352                }
1353            }
1354
1355            if !bindings.is_empty() {
1356                self.clear_pending_keystrokes();
1357            }
1358
1359            self.propagate_event = true;
1360            for binding in bindings {
1361                self.dispatch_action_on_node(node_id, binding.action.boxed_clone());
1362                if !self.propagate_event {
1363                    self.dispatch_keystroke_observers(event, Some(binding.action));
1364                    return;
1365                }
1366            }
1367        }
1368
1369        self.dispatch_key_down_up_event(event, &dispatch_path);
1370        if !self.propagate_event {
1371            return;
1372        }
1373
1374        self.dispatch_keystroke_observers(event, None);
1375    }
1376
1377    fn dispatch_key_down_up_event(
1378        &mut self,
1379        event: &dyn Any,
1380        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
1381    ) {
1382        // Capture phase
1383        for node_id in dispatch_path {
1384            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1385
1386            for key_listener in node.key_listeners.clone() {
1387                self.with_element_context(|cx| {
1388                    key_listener(event, DispatchPhase::Capture, cx);
1389                });
1390                if !self.propagate_event {
1391                    return;
1392                }
1393            }
1394        }
1395
1396        // Bubble phase
1397        for node_id in dispatch_path.iter().rev() {
1398            // Handle low level key events
1399            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1400            for key_listener in node.key_listeners.clone() {
1401                self.with_element_context(|cx| {
1402                    key_listener(event, DispatchPhase::Bubble, cx);
1403                });
1404                if !self.propagate_event {
1405                    return;
1406                }
1407            }
1408        }
1409    }
1410
1411    /// Determine whether a potential multi-stroke key binding is in progress on this window.
1412    pub fn has_pending_keystrokes(&self) -> bool {
1413        self.window
1414            .rendered_frame
1415            .dispatch_tree
1416            .has_pending_keystrokes()
1417    }
1418
1419    fn replay_pending_input(&mut self, currently_pending: PendingInput) {
1420        let node_id = self
1421            .window
1422            .focus
1423            .and_then(|focus_id| {
1424                self.window
1425                    .rendered_frame
1426                    .dispatch_tree
1427                    .focusable_node_id(focus_id)
1428            })
1429            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1430
1431        if self.window.focus != currently_pending.focus {
1432            return;
1433        }
1434
1435        let input = currently_pending.input();
1436
1437        self.propagate_event = true;
1438        for binding in currently_pending.bindings {
1439            self.dispatch_action_on_node(node_id, binding.action.boxed_clone());
1440            if !self.propagate_event {
1441                return;
1442            }
1443        }
1444
1445        let dispatch_path = self
1446            .window
1447            .rendered_frame
1448            .dispatch_tree
1449            .dispatch_path(node_id);
1450
1451        for keystroke in currently_pending.keystrokes {
1452            let event = KeyDownEvent {
1453                keystroke,
1454                is_held: false,
1455            };
1456
1457            self.dispatch_key_down_up_event(&event, &dispatch_path);
1458            if !self.propagate_event {
1459                return;
1460            }
1461        }
1462
1463        if !input.is_empty() {
1464            if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
1465                input_handler.dispatch_input(&input, self);
1466                self.window.platform_window.set_input_handler(input_handler)
1467            }
1468        }
1469    }
1470
1471    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1472        let dispatch_path = self
1473            .window
1474            .rendered_frame
1475            .dispatch_tree
1476            .dispatch_path(node_id);
1477
1478        // Capture phase
1479        for node_id in &dispatch_path {
1480            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1481            for DispatchActionListener {
1482                action_type,
1483                listener,
1484            } in node.action_listeners.clone()
1485            {
1486                let any_action = action.as_any();
1487                if action_type == any_action.type_id() {
1488                    self.with_element_context(|cx| {
1489                        listener(any_action, DispatchPhase::Capture, cx);
1490                    });
1491
1492                    if !self.propagate_event {
1493                        return;
1494                    }
1495                }
1496            }
1497        }
1498        // Bubble phase
1499        for node_id in dispatch_path.iter().rev() {
1500            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1501            for DispatchActionListener {
1502                action_type,
1503                listener,
1504            } in node.action_listeners.clone()
1505            {
1506                let any_action = action.as_any();
1507                if action_type == any_action.type_id() {
1508                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1509
1510                    self.with_element_context(|cx| {
1511                        listener(any_action, DispatchPhase::Bubble, cx);
1512                    });
1513
1514                    if !self.propagate_event {
1515                        return;
1516                    }
1517                }
1518            }
1519        }
1520    }
1521
1522    /// Toggle the graphics profiler to debug your application's rendering performance.
1523    pub fn toggle_graphics_profiler(&mut self) {
1524        self.window.graphics_profiler_enabled = !self.window.graphics_profiler_enabled;
1525        self.window
1526            .platform_window
1527            .set_graphics_profiler_enabled(self.window.graphics_profiler_enabled);
1528    }
1529
1530    /// Register the given handler to be invoked whenever the global of the given type
1531    /// is updated.
1532    pub fn observe_global<G: Global>(
1533        &mut self,
1534        f: impl Fn(&mut WindowContext<'_>) + 'static,
1535    ) -> Subscription {
1536        let window_handle = self.window.handle;
1537        let (subscription, activate) = self.global_observers.insert(
1538            TypeId::of::<G>(),
1539            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1540        );
1541        self.app.defer(move |_| activate());
1542        subscription
1543    }
1544
1545    /// Focus the current window and bring it to the foreground at the platform level.
1546    pub fn activate_window(&self) {
1547        self.window.platform_window.activate();
1548    }
1549
1550    /// Minimize the current window at the platform level.
1551    pub fn minimize_window(&self) {
1552        self.window.platform_window.minimize();
1553    }
1554
1555    /// Toggle full screen status on the current window at the platform level.
1556    pub fn toggle_full_screen(&self) {
1557        self.window.platform_window.toggle_full_screen();
1558    }
1559
1560    /// Present a platform dialog.
1561    /// The provided message will be presented, along with buttons for each answer.
1562    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
1563    pub fn prompt(
1564        &self,
1565        level: PromptLevel,
1566        message: &str,
1567        detail: Option<&str>,
1568        answers: &[&str],
1569    ) -> oneshot::Receiver<usize> {
1570        self.window
1571            .platform_window
1572            .prompt(level, message, detail, answers)
1573    }
1574
1575    /// Returns all available actions for the focused element.
1576    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1577        let node_id = self
1578            .window
1579            .focus
1580            .and_then(|focus_id| {
1581                self.window
1582                    .rendered_frame
1583                    .dispatch_tree
1584                    .focusable_node_id(focus_id)
1585            })
1586            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1587
1588        self.window
1589            .rendered_frame
1590            .dispatch_tree
1591            .available_actions(node_id)
1592    }
1593
1594    /// Returns key bindings that invoke the given action on the currently focused element.
1595    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1596        self.window
1597            .rendered_frame
1598            .dispatch_tree
1599            .bindings_for_action(
1600                action,
1601                &self.window.rendered_frame.dispatch_tree.context_stack,
1602            )
1603    }
1604
1605    /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
1606    pub fn bindings_for_action_in(
1607        &self,
1608        action: &dyn Action,
1609        focus_handle: &FocusHandle,
1610    ) -> Vec<KeyBinding> {
1611        let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1612
1613        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1614            return vec![];
1615        };
1616        let context_stack: Vec<_> = dispatch_tree
1617            .dispatch_path(node_id)
1618            .into_iter()
1619            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1620            .collect();
1621        dispatch_tree.bindings_for_action(action, &context_stack)
1622    }
1623
1624    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
1625    pub fn listener_for<V: Render, E>(
1626        &self,
1627        view: &View<V>,
1628        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1629    ) -> impl Fn(&E, &mut WindowContext) + 'static {
1630        let view = view.downgrade();
1631        move |e: &E, cx: &mut WindowContext| {
1632            view.update(cx, |view, cx| f(view, e, cx)).ok();
1633        }
1634    }
1635
1636    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
1637    pub fn handler_for<V: Render>(
1638        &self,
1639        view: &View<V>,
1640        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1641    ) -> impl Fn(&mut WindowContext) {
1642        let view = view.downgrade();
1643        move |cx: &mut WindowContext| {
1644            view.update(cx, |view, cx| f(view, cx)).ok();
1645        }
1646    }
1647
1648    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
1649    /// If the callback returns false, the window won't be closed.
1650    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1651        let mut this = self.to_async();
1652        self.window
1653            .platform_window
1654            .on_should_close(Box::new(move || this.update(|cx| f(cx)).unwrap_or(true)))
1655    }
1656
1657    pub(crate) fn parent_view_id(&self) -> EntityId {
1658        *self
1659            .window
1660            .next_frame
1661            .view_stack
1662            .last()
1663            .expect("a view should always be on the stack while drawing")
1664    }
1665
1666    /// Register an action listener on the window for the next frame. The type of action
1667    /// is determined by the first parameter of the given listener. When the next frame is rendered
1668    /// the listener will be cleared.
1669    ///
1670    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
1671    /// a specific need to register a global listener.
1672    pub fn on_action(
1673        &mut self,
1674        action_type: TypeId,
1675        listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
1676    ) {
1677        self.window
1678            .next_frame
1679            .dispatch_tree
1680            .on_action(action_type, Rc::new(listener));
1681    }
1682}
1683
1684impl Context for WindowContext<'_> {
1685    type Result<T> = T;
1686
1687    fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
1688    where
1689        T: 'static,
1690    {
1691        let slot = self.app.entities.reserve();
1692        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1693        self.entities.insert(slot, model)
1694    }
1695
1696    fn update_model<T: 'static, R>(
1697        &mut self,
1698        model: &Model<T>,
1699        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1700    ) -> R {
1701        let mut entity = self.entities.lease(model);
1702        let result = update(
1703            &mut *entity,
1704            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1705        );
1706        self.entities.end_lease(entity);
1707        result
1708    }
1709
1710    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1711    where
1712        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1713    {
1714        if window == self.window.handle {
1715            let root_view = self.window.root_view.clone().unwrap();
1716            Ok(update(root_view, self))
1717        } else {
1718            window.update(self.app, update)
1719        }
1720    }
1721
1722    fn read_model<T, R>(
1723        &self,
1724        handle: &Model<T>,
1725        read: impl FnOnce(&T, &AppContext) -> R,
1726    ) -> Self::Result<R>
1727    where
1728        T: 'static,
1729    {
1730        let entity = self.entities.read(handle);
1731        read(entity, &*self.app)
1732    }
1733
1734    fn read_window<T, R>(
1735        &self,
1736        window: &WindowHandle<T>,
1737        read: impl FnOnce(View<T>, &AppContext) -> R,
1738    ) -> Result<R>
1739    where
1740        T: 'static,
1741    {
1742        if window.any_handle == self.window.handle {
1743            let root_view = self
1744                .window
1745                .root_view
1746                .clone()
1747                .unwrap()
1748                .downcast::<T>()
1749                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1750            Ok(read(root_view, self))
1751        } else {
1752            self.app.read_window(window, read)
1753        }
1754    }
1755}
1756
1757impl VisualContext for WindowContext<'_> {
1758    fn new_view<V>(
1759        &mut self,
1760        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1761    ) -> Self::Result<View<V>>
1762    where
1763        V: 'static + Render,
1764    {
1765        let slot = self.app.entities.reserve();
1766        let view = View {
1767            model: slot.clone(),
1768        };
1769        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1770        let entity = build_view_state(&mut cx);
1771        cx.entities.insert(slot, entity);
1772
1773        // Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
1774        fn notify_observers(cx: &mut WindowContext, tid: TypeId, view: AnyView) {
1775            cx.new_view_observers.clone().retain(&tid, |observer| {
1776                let any_view = view.clone();
1777                (observer)(any_view, cx);
1778                true
1779            });
1780        }
1781        notify_observers(self, TypeId::of::<V>(), AnyView::from(view.clone()));
1782
1783        view
1784    }
1785
1786    /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
1787    fn update_view<T: 'static, R>(
1788        &mut self,
1789        view: &View<T>,
1790        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1791    ) -> Self::Result<R> {
1792        let mut lease = self.app.entities.lease(&view.model);
1793        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
1794        let result = update(&mut *lease, &mut cx);
1795        cx.app.entities.end_lease(lease);
1796        result
1797    }
1798
1799    fn replace_root_view<V>(
1800        &mut self,
1801        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1802    ) -> Self::Result<View<V>>
1803    where
1804        V: 'static + Render,
1805    {
1806        let view = self.new_view(build_view);
1807        self.window.root_view = Some(view.clone().into());
1808        self.refresh();
1809        view
1810    }
1811
1812    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1813        self.update_view(view, |view, cx| {
1814            view.focus_handle(cx).clone().focus(cx);
1815        })
1816    }
1817
1818    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1819    where
1820        V: ManagedView,
1821    {
1822        self.update_view(view, |_, cx| cx.emit(DismissEvent))
1823    }
1824}
1825
1826impl<'a> std::ops::Deref for WindowContext<'a> {
1827    type Target = AppContext;
1828
1829    fn deref(&self) -> &Self::Target {
1830        self.app
1831    }
1832}
1833
1834impl<'a> std::ops::DerefMut for WindowContext<'a> {
1835    fn deref_mut(&mut self) -> &mut Self::Target {
1836        self.app
1837    }
1838}
1839
1840impl<'a> Borrow<AppContext> for WindowContext<'a> {
1841    fn borrow(&self) -> &AppContext {
1842        self.app
1843    }
1844}
1845
1846impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1847    fn borrow_mut(&mut self) -> &mut AppContext {
1848        self.app
1849    }
1850}
1851
1852/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
1853pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1854    #[doc(hidden)]
1855    fn app_mut(&mut self) -> &mut AppContext {
1856        self.borrow_mut()
1857    }
1858
1859    #[doc(hidden)]
1860    fn app(&self) -> &AppContext {
1861        self.borrow()
1862    }
1863
1864    #[doc(hidden)]
1865    fn window(&self) -> &Window {
1866        self.borrow()
1867    }
1868
1869    #[doc(hidden)]
1870    fn window_mut(&mut self) -> &mut Window {
1871        self.borrow_mut()
1872    }
1873}
1874
1875impl Borrow<Window> for WindowContext<'_> {
1876    fn borrow(&self) -> &Window {
1877        self.window
1878    }
1879}
1880
1881impl BorrowMut<Window> for WindowContext<'_> {
1882    fn borrow_mut(&mut self) -> &mut Window {
1883        self.window
1884    }
1885}
1886
1887impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1888
1889/// Provides access to application state that is specialized for a particular [`View`].
1890/// Allows you to interact with focus, emit events, etc.
1891/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
1892/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
1893pub struct ViewContext<'a, V> {
1894    window_cx: WindowContext<'a>,
1895    view: &'a View<V>,
1896}
1897
1898impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1899    fn borrow(&self) -> &AppContext {
1900        &*self.window_cx.app
1901    }
1902}
1903
1904impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1905    fn borrow_mut(&mut self) -> &mut AppContext {
1906        &mut *self.window_cx.app
1907    }
1908}
1909
1910impl<V> Borrow<Window> for ViewContext<'_, V> {
1911    fn borrow(&self) -> &Window {
1912        &*self.window_cx.window
1913    }
1914}
1915
1916impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1917    fn borrow_mut(&mut self) -> &mut Window {
1918        &mut *self.window_cx.window
1919    }
1920}
1921
1922impl<'a, V: 'static> ViewContext<'a, V> {
1923    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1924        Self {
1925            window_cx: WindowContext::new(app, window),
1926            view,
1927        }
1928    }
1929
1930    /// Get the entity_id of this view.
1931    pub fn entity_id(&self) -> EntityId {
1932        self.view.entity_id()
1933    }
1934
1935    /// Get the view pointer underlying this context.
1936    pub fn view(&self) -> &View<V> {
1937        self.view
1938    }
1939
1940    /// Get the model underlying this view.
1941    pub fn model(&self) -> &Model<V> {
1942        &self.view.model
1943    }
1944
1945    /// Access the underlying window context.
1946    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1947        &mut self.window_cx
1948    }
1949
1950    /// Sets a given callback to be run on the next frame.
1951    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1952    where
1953        V: 'static,
1954    {
1955        let view = self.view().clone();
1956        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1957    }
1958
1959    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1960    /// that are currently on the stack to be returned to the app.
1961    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1962        let view = self.view().downgrade();
1963        self.window_cx.defer(move |cx| {
1964            view.update(cx, f).ok();
1965        });
1966    }
1967
1968    /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
1969    pub fn observe<V2, E>(
1970        &mut self,
1971        entity: &E,
1972        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1973    ) -> Subscription
1974    where
1975        V2: 'static,
1976        V: 'static,
1977        E: Entity<V2>,
1978    {
1979        let view = self.view().downgrade();
1980        let entity_id = entity.entity_id();
1981        let entity = entity.downgrade();
1982        let window_handle = self.window.handle;
1983        self.app.new_observer(
1984            entity_id,
1985            Box::new(move |cx| {
1986                window_handle
1987                    .update(cx, |_, cx| {
1988                        if let Some(handle) = E::upgrade_from(&entity) {
1989                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1990                                .is_ok()
1991                        } else {
1992                            false
1993                        }
1994                    })
1995                    .unwrap_or(false)
1996            }),
1997        )
1998    }
1999
2000    /// Subscribe to events emitted by another model or view.
2001    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
2002    /// 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.
2003    pub fn subscribe<V2, E, Evt>(
2004        &mut self,
2005        entity: &E,
2006        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2007    ) -> Subscription
2008    where
2009        V2: EventEmitter<Evt>,
2010        E: Entity<V2>,
2011        Evt: 'static,
2012    {
2013        let view = self.view().downgrade();
2014        let entity_id = entity.entity_id();
2015        let handle = entity.downgrade();
2016        let window_handle = self.window.handle;
2017        self.app.new_subscription(
2018            entity_id,
2019            (
2020                TypeId::of::<Evt>(),
2021                Box::new(move |event, cx| {
2022                    window_handle
2023                        .update(cx, |_, cx| {
2024                            if let Some(handle) = E::upgrade_from(&handle) {
2025                                let event = event.downcast_ref().expect("invalid event type");
2026                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
2027                                    .is_ok()
2028                            } else {
2029                                false
2030                            }
2031                        })
2032                        .unwrap_or(false)
2033                }),
2034            ),
2035        )
2036    }
2037
2038    /// Register a callback to be invoked when the view is released.
2039    ///
2040    /// The callback receives a handle to the view's window. This handle may be
2041    /// invalid, if the window was closed before the view was released.
2042    pub fn on_release(
2043        &mut self,
2044        on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
2045    ) -> Subscription {
2046        let window_handle = self.window.handle;
2047        let (subscription, activate) = self.app.release_listeners.insert(
2048            self.view.model.entity_id,
2049            Box::new(move |this, cx| {
2050                let this = this.downcast_mut().expect("invalid entity type");
2051                on_release(this, window_handle, cx)
2052            }),
2053        );
2054        activate();
2055        subscription
2056    }
2057
2058    /// Register a callback to be invoked when the given Model or View is released.
2059    pub fn observe_release<V2, E>(
2060        &mut self,
2061        entity: &E,
2062        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2063    ) -> Subscription
2064    where
2065        V: 'static,
2066        V2: 'static,
2067        E: Entity<V2>,
2068    {
2069        let view = self.view().downgrade();
2070        let entity_id = entity.entity_id();
2071        let window_handle = self.window.handle;
2072        let (subscription, activate) = self.app.release_listeners.insert(
2073            entity_id,
2074            Box::new(move |entity, cx| {
2075                let entity = entity.downcast_mut().expect("invalid entity type");
2076                let _ = window_handle.update(cx, |_, cx| {
2077                    view.update(cx, |this, cx| on_release(this, entity, cx))
2078                });
2079            }),
2080        );
2081        activate();
2082        subscription
2083    }
2084
2085    /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
2086    /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
2087    pub fn notify(&mut self) {
2088        for view_id in self
2089            .window
2090            .rendered_frame
2091            .dispatch_tree
2092            .view_path(self.view.entity_id())
2093            .into_iter()
2094            .rev()
2095        {
2096            if !self.window.dirty_views.insert(view_id) {
2097                break;
2098            }
2099        }
2100
2101        if !self.window.drawing {
2102            self.window_cx.window.dirty.set(true);
2103            self.window_cx.app.push_effect(Effect::Notify {
2104                emitter: self.view.model.entity_id,
2105            });
2106        }
2107    }
2108
2109    /// Register a callback to be invoked when the window is resized.
2110    pub fn observe_window_bounds(
2111        &mut self,
2112        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2113    ) -> Subscription {
2114        let view = self.view.downgrade();
2115        let (subscription, activate) = self.window.bounds_observers.insert(
2116            (),
2117            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2118        );
2119        activate();
2120        subscription
2121    }
2122
2123    /// Register a callback to be invoked when the window is activated or deactivated.
2124    pub fn observe_window_activation(
2125        &mut self,
2126        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2127    ) -> Subscription {
2128        let view = self.view.downgrade();
2129        let (subscription, activate) = self.window.activation_observers.insert(
2130            (),
2131            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2132        );
2133        activate();
2134        subscription
2135    }
2136
2137    /// Registers a callback to be invoked when the window appearance changes.
2138    pub fn observe_window_appearance(
2139        &mut self,
2140        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2141    ) -> Subscription {
2142        let view = self.view.downgrade();
2143        let (subscription, activate) = self.window.appearance_observers.insert(
2144            (),
2145            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2146        );
2147        activate();
2148        subscription
2149    }
2150
2151    /// Register a listener to be called when the given focus handle receives focus.
2152    /// Returns a subscription and persists until the subscription is dropped.
2153    pub fn on_focus(
2154        &mut self,
2155        handle: &FocusHandle,
2156        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2157    ) -> Subscription {
2158        let view = self.view.downgrade();
2159        let focus_id = handle.id;
2160        let (subscription, activate) =
2161            self.window.new_focus_listener(Box::new(move |event, cx| {
2162                view.update(cx, |view, cx| {
2163                    if event.previous_focus_path.last() != Some(&focus_id)
2164                        && event.current_focus_path.last() == Some(&focus_id)
2165                    {
2166                        listener(view, cx)
2167                    }
2168                })
2169                .is_ok()
2170            }));
2171        self.app.defer(|_| activate());
2172        subscription
2173    }
2174
2175    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2176    /// Returns a subscription and persists until the subscription is dropped.
2177    pub fn on_focus_in(
2178        &mut self,
2179        handle: &FocusHandle,
2180        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2181    ) -> Subscription {
2182        let view = self.view.downgrade();
2183        let focus_id = handle.id;
2184        let (subscription, activate) =
2185            self.window.new_focus_listener(Box::new(move |event, cx| {
2186                view.update(cx, |view, cx| {
2187                    if !event.previous_focus_path.contains(&focus_id)
2188                        && event.current_focus_path.contains(&focus_id)
2189                    {
2190                        listener(view, cx)
2191                    }
2192                })
2193                .is_ok()
2194            }));
2195        self.app.defer(move |_| activate());
2196        subscription
2197    }
2198
2199    /// Register a listener to be called when the given focus handle loses focus.
2200    /// Returns a subscription and persists until the subscription is dropped.
2201    pub fn on_blur(
2202        &mut self,
2203        handle: &FocusHandle,
2204        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2205    ) -> Subscription {
2206        let view = self.view.downgrade();
2207        let focus_id = handle.id;
2208        let (subscription, activate) =
2209            self.window.new_focus_listener(Box::new(move |event, cx| {
2210                view.update(cx, |view, cx| {
2211                    if event.previous_focus_path.last() == Some(&focus_id)
2212                        && event.current_focus_path.last() != Some(&focus_id)
2213                    {
2214                        listener(view, cx)
2215                    }
2216                })
2217                .is_ok()
2218            }));
2219        self.app.defer(move |_| activate());
2220        subscription
2221    }
2222
2223    /// Register a listener to be called when nothing in the window has focus.
2224    /// This typically happens when the node that was focused is removed from the tree,
2225    /// and this callback lets you chose a default place to restore the users focus.
2226    /// Returns a subscription and persists until the subscription is dropped.
2227    pub fn on_focus_lost(
2228        &mut self,
2229        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2230    ) -> Subscription {
2231        let view = self.view.downgrade();
2232        let (subscription, activate) = self.window.focus_lost_listeners.insert(
2233            (),
2234            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2235        );
2236        activate();
2237        subscription
2238    }
2239
2240    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2241    /// Returns a subscription and persists until the subscription is dropped.
2242    pub fn on_focus_out(
2243        &mut self,
2244        handle: &FocusHandle,
2245        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2246    ) -> Subscription {
2247        let view = self.view.downgrade();
2248        let focus_id = handle.id;
2249        let (subscription, activate) =
2250            self.window.new_focus_listener(Box::new(move |event, cx| {
2251                view.update(cx, |view, cx| {
2252                    if event.previous_focus_path.contains(&focus_id)
2253                        && !event.current_focus_path.contains(&focus_id)
2254                    {
2255                        listener(view, cx)
2256                    }
2257                })
2258                .is_ok()
2259            }));
2260        self.app.defer(move |_| activate());
2261        subscription
2262    }
2263
2264    /// Schedule a future to be run asynchronously.
2265    /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
2266    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
2267    /// The returned future will be polled on the main thread.
2268    pub fn spawn<Fut, R>(
2269        &mut self,
2270        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2271    ) -> Task<R>
2272    where
2273        R: 'static,
2274        Fut: Future<Output = R> + 'static,
2275    {
2276        let view = self.view().downgrade();
2277        self.window_cx.spawn(|cx| f(view, cx))
2278    }
2279
2280    /// Updates the global state of the given type.
2281    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2282    where
2283        G: Global,
2284    {
2285        let mut global = self.app.lease_global::<G>();
2286        let result = f(&mut global, self);
2287        self.app.end_global_lease(global);
2288        result
2289    }
2290
2291    /// Register a callback to be invoked when the given global state changes.
2292    pub fn observe_global<G: Global>(
2293        &mut self,
2294        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2295    ) -> Subscription {
2296        let window_handle = self.window.handle;
2297        let view = self.view().downgrade();
2298        let (subscription, activate) = self.global_observers.insert(
2299            TypeId::of::<G>(),
2300            Box::new(move |cx| {
2301                window_handle
2302                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2303                    .unwrap_or(false)
2304            }),
2305        );
2306        self.app.defer(move |_| activate());
2307        subscription
2308    }
2309
2310    /// Register a callback to be invoked when the given Action type is dispatched to the window.
2311    pub fn on_action(
2312        &mut self,
2313        action_type: TypeId,
2314        listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2315    ) {
2316        let handle = self.view().clone();
2317        self.window_cx
2318            .on_action(action_type, move |action, phase, cx| {
2319                handle.update(cx, |view, cx| {
2320                    listener(view, action, phase, cx);
2321                })
2322            });
2323    }
2324
2325    /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
2326    pub fn emit<Evt>(&mut self, event: Evt)
2327    where
2328        Evt: 'static,
2329        V: EventEmitter<Evt>,
2330    {
2331        let emitter = self.view.model.entity_id;
2332        self.app.push_effect(Effect::Emit {
2333            emitter,
2334            event_type: TypeId::of::<Evt>(),
2335            event: Box::new(event),
2336        });
2337    }
2338
2339    /// Move focus to the current view, assuming it implements [`FocusableView`].
2340    pub fn focus_self(&mut self)
2341    where
2342        V: FocusableView,
2343    {
2344        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2345    }
2346
2347    /// Convenience method for accessing view state in an event callback.
2348    ///
2349    /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
2350    /// but it's often useful to be able to access view state in these
2351    /// callbacks. This method provides a convenient way to do so.
2352    pub fn listener<E>(
2353        &self,
2354        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2355    ) -> impl Fn(&E, &mut WindowContext) + 'static {
2356        let view = self.view().downgrade();
2357        move |e: &E, cx: &mut WindowContext| {
2358            view.update(cx, |view, cx| f(view, e, cx)).ok();
2359        }
2360    }
2361}
2362
2363impl<V> Context for ViewContext<'_, V> {
2364    type Result<U> = U;
2365
2366    fn new_model<T: 'static>(
2367        &mut self,
2368        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2369    ) -> Model<T> {
2370        self.window_cx.new_model(build_model)
2371    }
2372
2373    fn update_model<T: 'static, R>(
2374        &mut self,
2375        model: &Model<T>,
2376        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2377    ) -> R {
2378        self.window_cx.update_model(model, update)
2379    }
2380
2381    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2382    where
2383        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2384    {
2385        self.window_cx.update_window(window, update)
2386    }
2387
2388    fn read_model<T, R>(
2389        &self,
2390        handle: &Model<T>,
2391        read: impl FnOnce(&T, &AppContext) -> R,
2392    ) -> Self::Result<R>
2393    where
2394        T: 'static,
2395    {
2396        self.window_cx.read_model(handle, read)
2397    }
2398
2399    fn read_window<T, R>(
2400        &self,
2401        window: &WindowHandle<T>,
2402        read: impl FnOnce(View<T>, &AppContext) -> R,
2403    ) -> Result<R>
2404    where
2405        T: 'static,
2406    {
2407        self.window_cx.read_window(window, read)
2408    }
2409}
2410
2411impl<V: 'static> VisualContext for ViewContext<'_, V> {
2412    fn new_view<W: Render + 'static>(
2413        &mut self,
2414        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2415    ) -> Self::Result<View<W>> {
2416        self.window_cx.new_view(build_view_state)
2417    }
2418
2419    fn update_view<V2: 'static, R>(
2420        &mut self,
2421        view: &View<V2>,
2422        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2423    ) -> Self::Result<R> {
2424        self.window_cx.update_view(view, update)
2425    }
2426
2427    fn replace_root_view<W>(
2428        &mut self,
2429        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2430    ) -> Self::Result<View<W>>
2431    where
2432        W: 'static + Render,
2433    {
2434        self.window_cx.replace_root_view(build_view)
2435    }
2436
2437    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2438        self.window_cx.focus_view(view)
2439    }
2440
2441    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2442        self.window_cx.dismiss_view(view)
2443    }
2444}
2445
2446impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2447    type Target = WindowContext<'a>;
2448
2449    fn deref(&self) -> &Self::Target {
2450        &self.window_cx
2451    }
2452}
2453
2454impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2455    fn deref_mut(&mut self) -> &mut Self::Target {
2456        &mut self.window_cx
2457    }
2458}
2459
2460// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2461slotmap::new_key_type! {
2462    /// A unique identifier for a window.
2463    pub struct WindowId;
2464}
2465
2466impl WindowId {
2467    /// Converts this window ID to a `u64`.
2468    pub fn as_u64(&self) -> u64 {
2469        self.0.as_ffi()
2470    }
2471}
2472
2473/// A handle to a window with a specific root view type.
2474/// Note that this does not keep the window alive on its own.
2475#[derive(Deref, DerefMut)]
2476pub struct WindowHandle<V> {
2477    #[deref]
2478    #[deref_mut]
2479    pub(crate) any_handle: AnyWindowHandle,
2480    state_type: PhantomData<V>,
2481}
2482
2483impl<V: 'static + Render> WindowHandle<V> {
2484    /// Creates a new handle from a window ID.
2485    /// This does not check if the root type of the window is `V`.
2486    pub fn new(id: WindowId) -> Self {
2487        WindowHandle {
2488            any_handle: AnyWindowHandle {
2489                id,
2490                state_type: TypeId::of::<V>(),
2491            },
2492            state_type: PhantomData,
2493        }
2494    }
2495
2496    /// Get the root view out of this window.
2497    ///
2498    /// This will fail if the window is closed or if the root view's type does not match `V`.
2499    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2500    where
2501        C: Context,
2502    {
2503        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2504            root_view
2505                .downcast::<V>()
2506                .map_err(|_| anyhow!("the type of the window's root view has changed"))
2507        }))
2508    }
2509
2510    /// Updates the root view of this window.
2511    ///
2512    /// This will fail if the window has been closed or if the root view's type does not match
2513    pub fn update<C, R>(
2514        &self,
2515        cx: &mut C,
2516        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2517    ) -> Result<R>
2518    where
2519        C: Context,
2520    {
2521        cx.update_window(self.any_handle, |root_view, cx| {
2522            let view = root_view
2523                .downcast::<V>()
2524                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2525            Ok(cx.update_view(&view, update))
2526        })?
2527    }
2528
2529    /// Read the root view out of this window.
2530    ///
2531    /// This will fail if the window is closed or if the root view's type does not match `V`.
2532    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2533        let x = cx
2534            .windows
2535            .get(self.id)
2536            .and_then(|window| {
2537                window
2538                    .as_ref()
2539                    .and_then(|window| window.root_view.clone())
2540                    .map(|root_view| root_view.downcast::<V>())
2541            })
2542            .ok_or_else(|| anyhow!("window not found"))?
2543            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2544
2545        Ok(x.read(cx))
2546    }
2547
2548    /// Read the root view out of this window, with a callback
2549    ///
2550    /// This will fail if the window is closed or if the root view's type does not match `V`.
2551    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2552    where
2553        C: Context,
2554    {
2555        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2556    }
2557
2558    /// Read the root view pointer off of this window.
2559    ///
2560    /// This will fail if the window is closed or if the root view's type does not match `V`.
2561    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2562    where
2563        C: Context,
2564    {
2565        cx.read_window(self, |root_view, _cx| root_view.clone())
2566    }
2567
2568    /// Check if this window is 'active'.
2569    ///
2570    /// Will return `None` if the window is closed or currently
2571    /// borrowed.
2572    pub fn is_active(&self, cx: &mut AppContext) -> Option<bool> {
2573        cx.update_window(self.any_handle, |_, cx| cx.is_window_active())
2574            .ok()
2575    }
2576}
2577
2578impl<V> Copy for WindowHandle<V> {}
2579
2580impl<V> Clone for WindowHandle<V> {
2581    fn clone(&self) -> Self {
2582        *self
2583    }
2584}
2585
2586impl<V> PartialEq for WindowHandle<V> {
2587    fn eq(&self, other: &Self) -> bool {
2588        self.any_handle == other.any_handle
2589    }
2590}
2591
2592impl<V> Eq for WindowHandle<V> {}
2593
2594impl<V> Hash for WindowHandle<V> {
2595    fn hash<H: Hasher>(&self, state: &mut H) {
2596        self.any_handle.hash(state);
2597    }
2598}
2599
2600impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
2601    fn from(val: WindowHandle<V>) -> Self {
2602        val.any_handle
2603    }
2604}
2605
2606/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
2607#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2608pub struct AnyWindowHandle {
2609    pub(crate) id: WindowId,
2610    state_type: TypeId,
2611}
2612
2613impl AnyWindowHandle {
2614    /// Get the ID of this window.
2615    pub fn window_id(&self) -> WindowId {
2616        self.id
2617    }
2618
2619    /// Attempt to convert this handle to a window handle with a specific root view type.
2620    /// If the types do not match, this will return `None`.
2621    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2622        if TypeId::of::<T>() == self.state_type {
2623            Some(WindowHandle {
2624                any_handle: *self,
2625                state_type: PhantomData,
2626            })
2627        } else {
2628            None
2629        }
2630    }
2631
2632    /// Updates the state of the root view of this window.
2633    ///
2634    /// This will fail if the window has been closed.
2635    pub fn update<C, R>(
2636        self,
2637        cx: &mut C,
2638        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2639    ) -> Result<R>
2640    where
2641        C: Context,
2642    {
2643        cx.update_window(self, update)
2644    }
2645
2646    /// Read the state of the root view of this window.
2647    ///
2648    /// This will fail if the window has been closed.
2649    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2650    where
2651        C: Context,
2652        T: 'static,
2653    {
2654        let view = self
2655            .downcast::<T>()
2656            .context("the type of the window's root view has changed")?;
2657
2658        cx.read_window(&view, read)
2659    }
2660}
2661
2662/// An identifier for an [`Element`](crate::Element).
2663///
2664/// Can be constructed with a string, a number, or both, as well
2665/// as other internal representations.
2666#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2667pub enum ElementId {
2668    /// The ID of a View element
2669    View(EntityId),
2670    /// An integer ID.
2671    Integer(usize),
2672    /// A string based ID.
2673    Name(SharedString),
2674    /// An ID that's equated with a focus handle.
2675    FocusHandle(FocusId),
2676    /// A combination of a name and an integer.
2677    NamedInteger(SharedString, usize),
2678}
2679
2680impl Display for ElementId {
2681    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2682        match self {
2683            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
2684            ElementId::Integer(ix) => write!(f, "{}", ix)?,
2685            ElementId::Name(name) => write!(f, "{}", name)?,
2686            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
2687            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
2688        }
2689
2690        Ok(())
2691    }
2692}
2693
2694impl ElementId {
2695    pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
2696        ElementId::View(entity_id)
2697    }
2698}
2699
2700impl TryInto<SharedString> for ElementId {
2701    type Error = anyhow::Error;
2702
2703    fn try_into(self) -> anyhow::Result<SharedString> {
2704        if let ElementId::Name(name) = self {
2705            Ok(name)
2706        } else {
2707            Err(anyhow!("element id is not string"))
2708        }
2709    }
2710}
2711
2712impl From<usize> for ElementId {
2713    fn from(id: usize) -> Self {
2714        ElementId::Integer(id)
2715    }
2716}
2717
2718impl From<i32> for ElementId {
2719    fn from(id: i32) -> Self {
2720        Self::Integer(id as usize)
2721    }
2722}
2723
2724impl From<SharedString> for ElementId {
2725    fn from(name: SharedString) -> Self {
2726        ElementId::Name(name)
2727    }
2728}
2729
2730impl From<&'static str> for ElementId {
2731    fn from(name: &'static str) -> Self {
2732        ElementId::Name(name.into())
2733    }
2734}
2735
2736impl<'a> From<&'a FocusHandle> for ElementId {
2737    fn from(handle: &'a FocusHandle) -> Self {
2738        ElementId::FocusHandle(handle.id)
2739    }
2740}
2741
2742impl From<(&'static str, EntityId)> for ElementId {
2743    fn from((name, id): (&'static str, EntityId)) -> Self {
2744        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
2745    }
2746}
2747
2748impl From<(&'static str, usize)> for ElementId {
2749    fn from((name, id): (&'static str, usize)) -> Self {
2750        ElementId::NamedInteger(name.into(), id)
2751    }
2752}
2753
2754impl From<(&'static str, u64)> for ElementId {
2755    fn from((name, id): (&'static str, u64)) -> Self {
2756        ElementId::NamedInteger(name.into(), id as usize)
2757    }
2758}
2759
2760/// A rectangle to be rendered in the window at the given position and size.
2761/// Passed as an argument [`ElementContext::paint_quad`].
2762#[derive(Clone)]
2763pub struct PaintQuad {
2764    bounds: Bounds<Pixels>,
2765    corner_radii: Corners<Pixels>,
2766    background: Hsla,
2767    border_widths: Edges<Pixels>,
2768    border_color: Hsla,
2769}
2770
2771impl PaintQuad {
2772    /// Sets the corner radii of the quad.
2773    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
2774        PaintQuad {
2775            corner_radii: corner_radii.into(),
2776            ..self
2777        }
2778    }
2779
2780    /// Sets the border widths of the quad.
2781    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
2782        PaintQuad {
2783            border_widths: border_widths.into(),
2784            ..self
2785        }
2786    }
2787
2788    /// Sets the border color of the quad.
2789    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
2790        PaintQuad {
2791            border_color: border_color.into(),
2792            ..self
2793        }
2794    }
2795
2796    /// Sets the background color of the quad.
2797    pub fn background(self, background: impl Into<Hsla>) -> Self {
2798        PaintQuad {
2799            background: background.into(),
2800            ..self
2801        }
2802    }
2803}
2804
2805/// Creates a quad with the given parameters.
2806pub fn quad(
2807    bounds: Bounds<Pixels>,
2808    corner_radii: impl Into<Corners<Pixels>>,
2809    background: impl Into<Hsla>,
2810    border_widths: impl Into<Edges<Pixels>>,
2811    border_color: impl Into<Hsla>,
2812) -> PaintQuad {
2813    PaintQuad {
2814        bounds,
2815        corner_radii: corner_radii.into(),
2816        background: background.into(),
2817        border_widths: border_widths.into(),
2818        border_color: border_color.into(),
2819    }
2820}
2821
2822/// Creates a filled quad with the given bounds and background color.
2823pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
2824    PaintQuad {
2825        bounds: bounds.into(),
2826        corner_radii: (0.).into(),
2827        background: background.into(),
2828        border_widths: (0.).into(),
2829        border_color: transparent_black(),
2830    }
2831}
2832
2833/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
2834pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
2835    PaintQuad {
2836        bounds: bounds.into(),
2837        corner_radii: (0.).into(),
2838        background: transparent_black(),
2839        border_widths: (1.).into(),
2840        border_color: border_color.into(),
2841    }
2842}