window.rs

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