window.rs

   1use crate::{
   2    key_dispatch::DispatchActionListener, px, size, Action, 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: 'static + 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, Box<dyn Any>>,
 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    pub fn listener_for<V: Render, E>(
1441        &self,
1442        view: &View<V>,
1443        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1444    ) -> impl Fn(&E, &mut WindowContext) + 'static {
1445        let view = view.downgrade();
1446        move |e: &E, cx: &mut WindowContext| {
1447            view.update(cx, |view, cx| f(view, e, cx)).ok();
1448        }
1449    }
1450
1451    pub fn constructor_for<V: Render, R>(
1452        &self,
1453        view: &View<V>,
1454        f: impl Fn(&mut V, &mut ViewContext<V>) -> R + 'static,
1455    ) -> impl Fn(&mut WindowContext) -> R + 'static {
1456        let view = view.clone();
1457        move |cx: &mut WindowContext| view.update(cx, |view, cx| f(view, cx))
1458    }
1459
1460    //========== ELEMENT RELATED FUNCTIONS ===========
1461    pub fn with_key_dispatch<R>(
1462        &mut self,
1463        context: KeyContext,
1464        focus_handle: Option<FocusHandle>,
1465        f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
1466    ) -> R {
1467        let window = &mut self.window;
1468        window
1469            .current_frame
1470            .dispatch_tree
1471            .push_node(context.clone());
1472        if let Some(focus_handle) = focus_handle.as_ref() {
1473            window
1474                .current_frame
1475                .dispatch_tree
1476                .make_focusable(focus_handle.id);
1477        }
1478        let result = f(focus_handle, self);
1479
1480        self.window.current_frame.dispatch_tree.pop_node();
1481
1482        result
1483    }
1484
1485    /// Register a focus listener for the current frame only. It will be cleared
1486    /// on the next frame render. You should use this method only from within elements,
1487    /// and we may want to enforce that better via a different context type.
1488    // todo!() Move this to `FrameContext` to emphasize its individuality?
1489    pub fn on_focus_changed(
1490        &mut self,
1491        listener: impl Fn(&FocusEvent, &mut WindowContext) + 'static,
1492    ) {
1493        self.window
1494            .current_frame
1495            .focus_listeners
1496            .push(Box::new(move |event, cx| {
1497                listener(event, cx);
1498            }));
1499    }
1500
1501    /// Set an input handler, such as [ElementInputHandler], which interfaces with the
1502    /// platform to receive textual input with proper integration with concerns such
1503    /// as IME interactions.
1504    pub fn handle_input(
1505        &mut self,
1506        focus_handle: &FocusHandle,
1507        input_handler: impl PlatformInputHandler,
1508    ) {
1509        if focus_handle.is_focused(self) {
1510            self.window
1511                .platform_window
1512                .set_input_handler(Box::new(input_handler));
1513        }
1514    }
1515}
1516
1517impl Context for WindowContext<'_> {
1518    type Result<T> = T;
1519
1520    fn build_model<T>(
1521        &mut self,
1522        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1523    ) -> Model<T>
1524    where
1525        T: 'static,
1526    {
1527        let slot = self.app.entities.reserve();
1528        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1529        self.entities.insert(slot, model)
1530    }
1531
1532    fn update_model<T: 'static, R>(
1533        &mut self,
1534        model: &Model<T>,
1535        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1536    ) -> R {
1537        let mut entity = self.entities.lease(model);
1538        let result = update(
1539            &mut *entity,
1540            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1541        );
1542        self.entities.end_lease(entity);
1543        result
1544    }
1545
1546    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1547    where
1548        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1549    {
1550        if window == self.window.handle {
1551            let root_view = self.window.root_view.clone().unwrap();
1552            Ok(update(root_view, self))
1553        } else {
1554            window.update(self.app, update)
1555        }
1556    }
1557
1558    fn read_model<T, R>(
1559        &self,
1560        handle: &Model<T>,
1561        read: impl FnOnce(&T, &AppContext) -> R,
1562    ) -> Self::Result<R>
1563    where
1564        T: 'static,
1565    {
1566        let entity = self.entities.read(handle);
1567        read(&*entity, &*self.app)
1568    }
1569
1570    fn read_window<T, R>(
1571        &self,
1572        window: &WindowHandle<T>,
1573        read: impl FnOnce(View<T>, &AppContext) -> R,
1574    ) -> Result<R>
1575    where
1576        T: 'static,
1577    {
1578        if window.any_handle == self.window.handle {
1579            let root_view = self
1580                .window
1581                .root_view
1582                .clone()
1583                .unwrap()
1584                .downcast::<T>()
1585                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1586            Ok(read(root_view, self))
1587        } else {
1588            self.app.read_window(window, read)
1589        }
1590    }
1591}
1592
1593impl VisualContext for WindowContext<'_> {
1594    fn build_view<V>(
1595        &mut self,
1596        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1597    ) -> Self::Result<View<V>>
1598    where
1599        V: 'static + Render,
1600    {
1601        let slot = self.app.entities.reserve();
1602        let view = View {
1603            model: slot.clone(),
1604        };
1605        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1606        let entity = build_view_state(&mut cx);
1607        cx.entities.insert(slot, entity);
1608
1609        cx.new_view_observers
1610            .clone()
1611            .retain(&TypeId::of::<V>(), |observer| {
1612                let any_view = AnyView::from(view.clone());
1613                (observer)(any_view, self);
1614                true
1615            });
1616
1617        view
1618    }
1619
1620    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1621    fn update_view<T: 'static, R>(
1622        &mut self,
1623        view: &View<T>,
1624        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1625    ) -> Self::Result<R> {
1626        let mut lease = self.app.entities.lease(&view.model);
1627        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1628        let result = update(&mut *lease, &mut cx);
1629        cx.app.entities.end_lease(lease);
1630        result
1631    }
1632
1633    fn replace_root_view<V>(
1634        &mut self,
1635        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1636    ) -> Self::Result<View<V>>
1637    where
1638        V: 'static + Render,
1639    {
1640        let slot = self.app.entities.reserve();
1641        let view = View {
1642            model: slot.clone(),
1643        };
1644        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1645        let entity = build_view(&mut cx);
1646        self.entities.insert(slot, entity);
1647        self.window.root_view = Some(view.clone().into());
1648        view
1649    }
1650
1651    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1652        self.update_view(view, |view, cx| {
1653            view.focus_handle(cx).clone().focus(cx);
1654        })
1655    }
1656
1657    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1658    where
1659        V: ManagedView,
1660    {
1661        self.update_view(view, |_, cx| cx.emit(Manager::Dismiss))
1662    }
1663}
1664
1665impl<'a> std::ops::Deref for WindowContext<'a> {
1666    type Target = AppContext;
1667
1668    fn deref(&self) -> &Self::Target {
1669        &self.app
1670    }
1671}
1672
1673impl<'a> std::ops::DerefMut for WindowContext<'a> {
1674    fn deref_mut(&mut self) -> &mut Self::Target {
1675        &mut self.app
1676    }
1677}
1678
1679impl<'a> Borrow<AppContext> for WindowContext<'a> {
1680    fn borrow(&self) -> &AppContext {
1681        &self.app
1682    }
1683}
1684
1685impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1686    fn borrow_mut(&mut self) -> &mut AppContext {
1687        &mut self.app
1688    }
1689}
1690
1691pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1692    fn app_mut(&mut self) -> &mut AppContext {
1693        self.borrow_mut()
1694    }
1695
1696    fn app(&self) -> &AppContext {
1697        self.borrow()
1698    }
1699
1700    fn window(&self) -> &Window {
1701        self.borrow()
1702    }
1703
1704    fn window_mut(&mut self) -> &mut Window {
1705        self.borrow_mut()
1706    }
1707
1708    /// Pushes the given element id onto the global stack and invokes the given closure
1709    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1710    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1711    /// used to associate state with identified elements across separate frames.
1712    fn with_element_id<R>(
1713        &mut self,
1714        id: Option<impl Into<ElementId>>,
1715        f: impl FnOnce(&mut Self) -> R,
1716    ) -> R {
1717        if let Some(id) = id.map(Into::into) {
1718            let window = self.window_mut();
1719            window.element_id_stack.push(id.into());
1720            let result = f(self);
1721            let window: &mut Window = self.borrow_mut();
1722            window.element_id_stack.pop();
1723            result
1724        } else {
1725            f(self)
1726        }
1727    }
1728
1729    /// Invoke the given function with the given content mask after intersecting it
1730    /// with the current mask.
1731    fn with_content_mask<R>(
1732        &mut self,
1733        mask: Option<ContentMask<Pixels>>,
1734        f: impl FnOnce(&mut Self) -> R,
1735    ) -> R {
1736        if let Some(mask) = mask {
1737            let mask = mask.intersect(&self.content_mask());
1738            self.window_mut()
1739                .current_frame
1740                .content_mask_stack
1741                .push(mask);
1742            let result = f(self);
1743            self.window_mut().current_frame.content_mask_stack.pop();
1744            result
1745        } else {
1746            f(self)
1747        }
1748    }
1749
1750    /// Update the global element offset relative to the current offset. This is used to implement
1751    /// scrolling.
1752    fn with_element_offset<R>(
1753        &mut self,
1754        offset: Point<Pixels>,
1755        f: impl FnOnce(&mut Self) -> R,
1756    ) -> R {
1757        if offset.is_zero() {
1758            return f(self);
1759        };
1760
1761        let abs_offset = self.element_offset() + offset;
1762        self.with_absolute_element_offset(abs_offset, f)
1763    }
1764
1765    /// Update the global element offset based on the given offset. This is used to implement
1766    /// drag handles and other manual painting of elements.
1767    fn with_absolute_element_offset<R>(
1768        &mut self,
1769        offset: Point<Pixels>,
1770        f: impl FnOnce(&mut Self) -> R,
1771    ) -> R {
1772        self.window_mut()
1773            .current_frame
1774            .element_offset_stack
1775            .push(offset);
1776        let result = f(self);
1777        self.window_mut().current_frame.element_offset_stack.pop();
1778        result
1779    }
1780
1781    /// Obtain the current element offset.
1782    fn element_offset(&self) -> Point<Pixels> {
1783        self.window()
1784            .current_frame
1785            .element_offset_stack
1786            .last()
1787            .copied()
1788            .unwrap_or_default()
1789    }
1790
1791    /// Update or intialize state for an element with the given id that lives across multiple
1792    /// frames. If an element with this id existed in the previous frame, its state will be passed
1793    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1794    /// when drawing the next frame.
1795    fn with_element_state<S, R>(
1796        &mut self,
1797        id: ElementId,
1798        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1799    ) -> R
1800    where
1801        S: 'static,
1802    {
1803        self.with_element_id(Some(id), |cx| {
1804            let global_id = cx.window().element_id_stack.clone();
1805
1806            if let Some(any) = cx
1807                .window_mut()
1808                .current_frame
1809                .element_states
1810                .remove(&global_id)
1811                .or_else(|| {
1812                    cx.window_mut()
1813                        .previous_frame
1814                        .element_states
1815                        .remove(&global_id)
1816                })
1817            {
1818                // Using the extra inner option to avoid needing to reallocate a new box.
1819                let mut state_box = any
1820                    .downcast::<Option<S>>()
1821                    .expect("invalid element state type for id");
1822                let state = state_box
1823                    .take()
1824                    .expect("element state is already on the stack");
1825                let (result, state) = f(Some(state), cx);
1826                state_box.replace(state);
1827                cx.window_mut()
1828                    .current_frame
1829                    .element_states
1830                    .insert(global_id, state_box);
1831                result
1832            } else {
1833                let (result, state) = f(None, cx);
1834                cx.window_mut()
1835                    .current_frame
1836                    .element_states
1837                    .insert(global_id, Box::new(Some(state)));
1838                result
1839            }
1840        })
1841    }
1842
1843    /// Like `with_element_state`, but for situations where the element_id is optional. If the
1844    /// id is `None`, no state will be retrieved or stored.
1845    fn with_optional_element_state<S, R>(
1846        &mut self,
1847        element_id: Option<ElementId>,
1848        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1849    ) -> R
1850    where
1851        S: 'static,
1852    {
1853        if let Some(element_id) = element_id {
1854            self.with_element_state(element_id, f)
1855        } else {
1856            f(None, self).0
1857        }
1858    }
1859
1860    /// Obtain the current content mask.
1861    fn content_mask(&self) -> ContentMask<Pixels> {
1862        self.window()
1863            .current_frame
1864            .content_mask_stack
1865            .last()
1866            .cloned()
1867            .unwrap_or_else(|| ContentMask {
1868                bounds: Bounds {
1869                    origin: Point::default(),
1870                    size: self.window().viewport_size,
1871                },
1872            })
1873    }
1874
1875    /// The size of an em for the base font of the application. Adjusting this value allows the
1876    /// UI to scale, just like zooming a web page.
1877    fn rem_size(&self) -> Pixels {
1878        self.window().rem_size
1879    }
1880}
1881
1882impl Borrow<Window> for WindowContext<'_> {
1883    fn borrow(&self) -> &Window {
1884        &self.window
1885    }
1886}
1887
1888impl BorrowMut<Window> for WindowContext<'_> {
1889    fn borrow_mut(&mut self) -> &mut Window {
1890        &mut self.window
1891    }
1892}
1893
1894impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1895
1896pub struct ViewContext<'a, V> {
1897    window_cx: WindowContext<'a>,
1898    view: &'a View<V>,
1899}
1900
1901impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1902    fn borrow(&self) -> &AppContext {
1903        &*self.window_cx.app
1904    }
1905}
1906
1907impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1908    fn borrow_mut(&mut self) -> &mut AppContext {
1909        &mut *self.window_cx.app
1910    }
1911}
1912
1913impl<V> Borrow<Window> for ViewContext<'_, V> {
1914    fn borrow(&self) -> &Window {
1915        &*self.window_cx.window
1916    }
1917}
1918
1919impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1920    fn borrow_mut(&mut self) -> &mut Window {
1921        &mut *self.window_cx.window
1922    }
1923}
1924
1925impl<'a, V: 'static> ViewContext<'a, V> {
1926    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1927        Self {
1928            window_cx: WindowContext::new(app, window),
1929            view,
1930        }
1931    }
1932
1933    pub fn entity_id(&self) -> EntityId {
1934        self.view.entity_id()
1935    }
1936
1937    pub fn view(&self) -> &View<V> {
1938        self.view
1939    }
1940
1941    pub fn model(&self) -> &Model<V> {
1942        &self.view.model
1943    }
1944
1945    /// Access the underlying window context.
1946    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1947        &mut self.window_cx
1948    }
1949
1950    pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1951        self.window.current_frame.z_index_stack.push(z_index);
1952        let result = f(self);
1953        self.window.current_frame.z_index_stack.pop();
1954        result
1955    }
1956
1957    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1958    where
1959        V: 'static,
1960    {
1961        let view = self.view().clone();
1962        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1963    }
1964
1965    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1966    /// that are currently on the stack to be returned to the app.
1967    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1968        let view = self.view().downgrade();
1969        self.window_cx.defer(move |cx| {
1970            view.update(cx, f).ok();
1971        });
1972    }
1973
1974    pub fn observe<V2, E>(
1975        &mut self,
1976        entity: &E,
1977        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1978    ) -> Subscription
1979    where
1980        V2: 'static,
1981        V: 'static,
1982        E: Entity<V2>,
1983    {
1984        let view = self.view().downgrade();
1985        let entity_id = entity.entity_id();
1986        let entity = entity.downgrade();
1987        let window_handle = self.window.handle;
1988        self.app.observers.insert(
1989            entity_id,
1990            Box::new(move |cx| {
1991                window_handle
1992                    .update(cx, |_, cx| {
1993                        if let Some(handle) = E::upgrade_from(&entity) {
1994                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1995                                .is_ok()
1996                        } else {
1997                            false
1998                        }
1999                    })
2000                    .unwrap_or(false)
2001            }),
2002        )
2003    }
2004
2005    pub fn subscribe<V2, E, Evt>(
2006        &mut self,
2007        entity: &E,
2008        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2009    ) -> Subscription
2010    where
2011        V2: EventEmitter<Evt>,
2012        E: Entity<V2>,
2013        Evt: 'static,
2014    {
2015        let view = self.view().downgrade();
2016        let entity_id = entity.entity_id();
2017        let handle = entity.downgrade();
2018        let window_handle = self.window.handle;
2019        self.app.event_listeners.insert(
2020            entity_id,
2021            (
2022                TypeId::of::<Evt>(),
2023                Box::new(move |event, cx| {
2024                    window_handle
2025                        .update(cx, |_, cx| {
2026                            if let Some(handle) = E::upgrade_from(&handle) {
2027                                let event = event.downcast_ref().expect("invalid event type");
2028                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
2029                                    .is_ok()
2030                            } else {
2031                                false
2032                            }
2033                        })
2034                        .unwrap_or(false)
2035                }),
2036            ),
2037        )
2038    }
2039
2040    pub fn on_release(
2041        &mut self,
2042        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
2043    ) -> Subscription {
2044        let window_handle = self.window.handle;
2045        self.app.release_listeners.insert(
2046            self.view.model.entity_id,
2047            Box::new(move |this, cx| {
2048                let this = this.downcast_mut().expect("invalid entity type");
2049                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
2050            }),
2051        )
2052    }
2053
2054    pub fn observe_release<V2, E>(
2055        &mut self,
2056        entity: &E,
2057        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2058    ) -> Subscription
2059    where
2060        V: 'static,
2061        V2: 'static,
2062        E: Entity<V2>,
2063    {
2064        let view = self.view().downgrade();
2065        let entity_id = entity.entity_id();
2066        let window_handle = self.window.handle;
2067        self.app.release_listeners.insert(
2068            entity_id,
2069            Box::new(move |entity, cx| {
2070                let entity = entity.downcast_mut().expect("invalid entity type");
2071                let _ = window_handle.update(cx, |_, cx| {
2072                    view.update(cx, |this, cx| on_release(this, entity, cx))
2073                });
2074            }),
2075        )
2076    }
2077
2078    pub fn notify(&mut self) {
2079        self.window_cx.notify();
2080        self.window_cx.app.push_effect(Effect::Notify {
2081            emitter: self.view.model.entity_id,
2082        });
2083    }
2084
2085    pub fn observe_window_bounds(
2086        &mut self,
2087        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2088    ) -> Subscription {
2089        let view = self.view.downgrade();
2090        self.window.bounds_observers.insert(
2091            (),
2092            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2093        )
2094    }
2095
2096    pub fn observe_window_activation(
2097        &mut self,
2098        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2099    ) -> Subscription {
2100        let view = self.view.downgrade();
2101        self.window.activation_observers.insert(
2102            (),
2103            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2104        )
2105    }
2106
2107    /// Register a listener to be called when the given focus handle receives focus.
2108    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2109    /// is dropped.
2110    pub fn on_focus(
2111        &mut self,
2112        handle: &FocusHandle,
2113        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2114    ) -> Subscription {
2115        let view = self.view.downgrade();
2116        let focus_id = handle.id;
2117        self.window.focus_listeners.insert(
2118            (),
2119            Box::new(move |event, cx| {
2120                view.update(cx, |view, cx| {
2121                    if event.focused.as_ref().map(|focused| focused.id) == Some(focus_id) {
2122                        listener(view, cx)
2123                    }
2124                })
2125                .is_ok()
2126            }),
2127        )
2128    }
2129
2130    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2131    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2132    /// is dropped.
2133    pub fn on_focus_in(
2134        &mut self,
2135        handle: &FocusHandle,
2136        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2137    ) -> Subscription {
2138        let view = self.view.downgrade();
2139        let focus_id = handle.id;
2140        self.window.focus_listeners.insert(
2141            (),
2142            Box::new(move |event, cx| {
2143                view.update(cx, |view, cx| {
2144                    if event
2145                        .focused
2146                        .as_ref()
2147                        .map_or(false, |focused| focus_id.contains(focused.id, cx))
2148                    {
2149                        listener(view, cx)
2150                    }
2151                })
2152                .is_ok()
2153            }),
2154        )
2155    }
2156
2157    /// Register a listener to be called when the given focus handle loses focus.
2158    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2159    /// is dropped.
2160    pub fn on_blur(
2161        &mut self,
2162        handle: &FocusHandle,
2163        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2164    ) -> Subscription {
2165        let view = self.view.downgrade();
2166        let focus_id = handle.id;
2167        self.window.focus_listeners.insert(
2168            (),
2169            Box::new(move |event, cx| {
2170                view.update(cx, |view, cx| {
2171                    if event.blurred.as_ref().map(|blurred| blurred.id) == Some(focus_id) {
2172                        listener(view, cx)
2173                    }
2174                })
2175                .is_ok()
2176            }),
2177        )
2178    }
2179
2180    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2181    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2182    /// is dropped.
2183    pub fn on_focus_out(
2184        &mut self,
2185        handle: &FocusHandle,
2186        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2187    ) -> Subscription {
2188        let view = self.view.downgrade();
2189        let focus_id = handle.id;
2190        self.window.focus_listeners.insert(
2191            (),
2192            Box::new(move |event, cx| {
2193                view.update(cx, |view, cx| {
2194                    if event
2195                        .blurred
2196                        .as_ref()
2197                        .map_or(false, |blurred| focus_id.contains(blurred.id, cx))
2198                    {
2199                        listener(view, cx)
2200                    }
2201                })
2202                .is_ok()
2203            }),
2204        )
2205    }
2206
2207    pub fn spawn<Fut, R>(
2208        &mut self,
2209        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2210    ) -> Task<R>
2211    where
2212        R: 'static,
2213        Fut: Future<Output = R> + 'static,
2214    {
2215        let view = self.view().downgrade();
2216        self.window_cx.spawn(|cx| f(view, cx))
2217    }
2218
2219    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2220    where
2221        G: 'static,
2222    {
2223        let mut global = self.app.lease_global::<G>();
2224        let result = f(&mut global, self);
2225        self.app.end_global_lease(global);
2226        result
2227    }
2228
2229    pub fn observe_global<G: 'static>(
2230        &mut self,
2231        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2232    ) -> Subscription {
2233        let window_handle = self.window.handle;
2234        let view = self.view().downgrade();
2235        self.global_observers.insert(
2236            TypeId::of::<G>(),
2237            Box::new(move |cx| {
2238                window_handle
2239                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2240                    .unwrap_or(false)
2241            }),
2242        )
2243    }
2244
2245    pub fn on_mouse_event<Event: 'static>(
2246        &mut self,
2247        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2248    ) {
2249        let handle = self.view().clone();
2250        self.window_cx.on_mouse_event(move |event, phase, cx| {
2251            handle.update(cx, |view, cx| {
2252                handler(view, event, phase, cx);
2253            })
2254        });
2255    }
2256
2257    pub fn on_key_event<Event: 'static>(
2258        &mut self,
2259        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2260    ) {
2261        let handle = self.view().clone();
2262        self.window_cx.on_key_event(move |event, phase, cx| {
2263            handle.update(cx, |view, cx| {
2264                handler(view, event, phase, cx);
2265            })
2266        });
2267    }
2268
2269    pub fn on_action(
2270        &mut self,
2271        action_type: TypeId,
2272        handler: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2273    ) {
2274        let handle = self.view().clone();
2275        self.window_cx
2276            .on_action(action_type, move |action, phase, cx| {
2277                handle.update(cx, |view, cx| {
2278                    handler(view, action, phase, cx);
2279                })
2280            });
2281    }
2282
2283    pub fn emit<Evt>(&mut self, event: Evt)
2284    where
2285        Evt: 'static,
2286        V: EventEmitter<Evt>,
2287    {
2288        let emitter = self.view.model.entity_id;
2289        self.app.push_effect(Effect::Emit {
2290            emitter,
2291            event_type: TypeId::of::<Evt>(),
2292            event: Box::new(event),
2293        });
2294    }
2295
2296    pub fn focus_self(&mut self)
2297    where
2298        V: FocusableView,
2299    {
2300        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2301    }
2302
2303    pub fn dismiss_self(&mut self)
2304    where
2305        V: ManagedView,
2306    {
2307        self.defer(|_, cx| cx.emit(Manager::Dismiss))
2308    }
2309
2310    pub fn listener<E>(
2311        &self,
2312        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2313    ) -> impl Fn(&E, &mut WindowContext) + 'static {
2314        let view = self.view().downgrade();
2315        move |e: &E, cx: &mut WindowContext| {
2316            view.update(cx, |view, cx| f(view, e, cx)).ok();
2317        }
2318    }
2319}
2320
2321impl<V> Context for ViewContext<'_, V> {
2322    type Result<U> = U;
2323
2324    fn build_model<T: 'static>(
2325        &mut self,
2326        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2327    ) -> Model<T> {
2328        self.window_cx.build_model(build_model)
2329    }
2330
2331    fn update_model<T: 'static, R>(
2332        &mut self,
2333        model: &Model<T>,
2334        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2335    ) -> R {
2336        self.window_cx.update_model(model, update)
2337    }
2338
2339    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2340    where
2341        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2342    {
2343        self.window_cx.update_window(window, update)
2344    }
2345
2346    fn read_model<T, R>(
2347        &self,
2348        handle: &Model<T>,
2349        read: impl FnOnce(&T, &AppContext) -> R,
2350    ) -> Self::Result<R>
2351    where
2352        T: 'static,
2353    {
2354        self.window_cx.read_model(handle, read)
2355    }
2356
2357    fn read_window<T, R>(
2358        &self,
2359        window: &WindowHandle<T>,
2360        read: impl FnOnce(View<T>, &AppContext) -> R,
2361    ) -> Result<R>
2362    where
2363        T: 'static,
2364    {
2365        self.window_cx.read_window(window, read)
2366    }
2367}
2368
2369impl<V: 'static> VisualContext for ViewContext<'_, V> {
2370    fn build_view<W: Render + 'static>(
2371        &mut self,
2372        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2373    ) -> Self::Result<View<W>> {
2374        self.window_cx.build_view(build_view_state)
2375    }
2376
2377    fn update_view<V2: 'static, R>(
2378        &mut self,
2379        view: &View<V2>,
2380        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2381    ) -> Self::Result<R> {
2382        self.window_cx.update_view(view, update)
2383    }
2384
2385    fn replace_root_view<W>(
2386        &mut self,
2387        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2388    ) -> Self::Result<View<W>>
2389    where
2390        W: 'static + Render,
2391    {
2392        self.window_cx.replace_root_view(build_view)
2393    }
2394
2395    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2396        self.window_cx.focus_view(view)
2397    }
2398
2399    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2400        self.window_cx.dismiss_view(view)
2401    }
2402}
2403
2404impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2405    type Target = WindowContext<'a>;
2406
2407    fn deref(&self) -> &Self::Target {
2408        &self.window_cx
2409    }
2410}
2411
2412impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2413    fn deref_mut(&mut self) -> &mut Self::Target {
2414        &mut self.window_cx
2415    }
2416}
2417
2418// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2419slotmap::new_key_type! { pub struct WindowId; }
2420
2421impl WindowId {
2422    pub fn as_u64(&self) -> u64 {
2423        self.0.as_ffi()
2424    }
2425}
2426
2427#[derive(Deref, DerefMut)]
2428pub struct WindowHandle<V> {
2429    #[deref]
2430    #[deref_mut]
2431    pub(crate) any_handle: AnyWindowHandle,
2432    state_type: PhantomData<V>,
2433}
2434
2435impl<V: 'static + Render> WindowHandle<V> {
2436    pub fn new(id: WindowId) -> Self {
2437        WindowHandle {
2438            any_handle: AnyWindowHandle {
2439                id,
2440                state_type: TypeId::of::<V>(),
2441            },
2442            state_type: PhantomData,
2443        }
2444    }
2445
2446    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2447    where
2448        C: Context,
2449    {
2450        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2451            root_view
2452                .downcast::<V>()
2453                .map_err(|_| anyhow!("the type of the window's root view has changed"))
2454        }))
2455    }
2456
2457    pub fn update<C, R>(
2458        &self,
2459        cx: &mut C,
2460        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2461    ) -> Result<R>
2462    where
2463        C: Context,
2464    {
2465        cx.update_window(self.any_handle, |root_view, cx| {
2466            let view = root_view
2467                .downcast::<V>()
2468                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2469            Ok(cx.update_view(&view, update))
2470        })?
2471    }
2472
2473    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2474        let x = cx
2475            .windows
2476            .get(self.id)
2477            .and_then(|window| {
2478                window
2479                    .as_ref()
2480                    .and_then(|window| window.root_view.clone())
2481                    .map(|root_view| root_view.downcast::<V>())
2482            })
2483            .ok_or_else(|| anyhow!("window not found"))?
2484            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2485
2486        Ok(x.read(cx))
2487    }
2488
2489    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2490    where
2491        C: Context,
2492    {
2493        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2494    }
2495
2496    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2497    where
2498        C: Context,
2499    {
2500        cx.read_window(self, |root_view, _cx| root_view.clone())
2501    }
2502
2503    pub fn is_active(&self, cx: &WindowContext) -> Option<bool> {
2504        cx.windows
2505            .get(self.id)
2506            .and_then(|window| window.as_ref().map(|window| window.active))
2507    }
2508}
2509
2510impl<V> Copy for WindowHandle<V> {}
2511
2512impl<V> Clone for WindowHandle<V> {
2513    fn clone(&self) -> Self {
2514        WindowHandle {
2515            any_handle: self.any_handle,
2516            state_type: PhantomData,
2517        }
2518    }
2519}
2520
2521impl<V> PartialEq for WindowHandle<V> {
2522    fn eq(&self, other: &Self) -> bool {
2523        self.any_handle == other.any_handle
2524    }
2525}
2526
2527impl<V> Eq for WindowHandle<V> {}
2528
2529impl<V> Hash for WindowHandle<V> {
2530    fn hash<H: Hasher>(&self, state: &mut H) {
2531        self.any_handle.hash(state);
2532    }
2533}
2534
2535impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2536    fn into(self) -> AnyWindowHandle {
2537        self.any_handle
2538    }
2539}
2540
2541#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2542pub struct AnyWindowHandle {
2543    pub(crate) id: WindowId,
2544    state_type: TypeId,
2545}
2546
2547impl AnyWindowHandle {
2548    pub fn window_id(&self) -> WindowId {
2549        self.id
2550    }
2551
2552    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2553        if TypeId::of::<T>() == self.state_type {
2554            Some(WindowHandle {
2555                any_handle: *self,
2556                state_type: PhantomData,
2557            })
2558        } else {
2559            None
2560        }
2561    }
2562
2563    pub fn update<C, R>(
2564        self,
2565        cx: &mut C,
2566        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2567    ) -> Result<R>
2568    where
2569        C: Context,
2570    {
2571        cx.update_window(self, update)
2572    }
2573
2574    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2575    where
2576        C: Context,
2577        T: 'static,
2578    {
2579        let view = self
2580            .downcast::<T>()
2581            .context("the type of the window's root view has changed")?;
2582
2583        cx.read_window(&view, read)
2584    }
2585}
2586
2587#[cfg(any(test, feature = "test-support"))]
2588impl From<SmallVec<[u32; 16]>> for StackingOrder {
2589    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2590        StackingOrder(small_vec)
2591    }
2592}
2593
2594#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2595pub enum ElementId {
2596    View(EntityId),
2597    Integer(usize),
2598    Name(SharedString),
2599    FocusHandle(FocusId),
2600}
2601
2602impl TryInto<SharedString> for ElementId {
2603    type Error = anyhow::Error;
2604
2605    fn try_into(self) -> anyhow::Result<SharedString> {
2606        if let ElementId::Name(name) = self {
2607            Ok(name)
2608        } else {
2609            Err(anyhow!("element id is not string"))
2610        }
2611    }
2612}
2613
2614impl From<EntityId> for ElementId {
2615    fn from(id: EntityId) -> Self {
2616        ElementId::View(id)
2617    }
2618}
2619
2620impl From<usize> for ElementId {
2621    fn from(id: usize) -> Self {
2622        ElementId::Integer(id)
2623    }
2624}
2625
2626impl From<i32> for ElementId {
2627    fn from(id: i32) -> Self {
2628        Self::Integer(id as usize)
2629    }
2630}
2631
2632impl From<SharedString> for ElementId {
2633    fn from(name: SharedString) -> Self {
2634        ElementId::Name(name)
2635    }
2636}
2637
2638impl From<&'static str> for ElementId {
2639    fn from(name: &'static str) -> Self {
2640        ElementId::Name(name.into())
2641    }
2642}
2643
2644impl<'a> From<&'a FocusHandle> for ElementId {
2645    fn from(handle: &'a FocusHandle) -> Self {
2646        ElementId::FocusHandle(handle.id)
2647    }
2648}