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