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