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