window.rs

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