window.rs

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