window.rs

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