window.rs

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