window.rs

   1use crate::{
   2    px, size, Action, AnyBox, AnyDrag, AnyView, AppContext, AsyncWindowContext, AvailableSpace,
   3    Bounds, BoxShadow, Context, Corners, DevicePixels, DispatchContext, DisplayId, Edges, Effect,
   4    Entity, EntityId, EventEmitter, FileDropEvent, FocusEvent, FontId, GlobalElementId, GlyphId,
   5    Hsla, ImageData, InputEvent, IsZero, KeyListener, KeyMatch, KeyMatcher, Keystroke, LayoutId,
   6    Model, ModelContext, Modifiers, MonochromeSprite, MouseButton, MouseDownEvent, MouseMoveEvent,
   7    MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformWindow, Point, PolychromeSprite, Quad,
   8    Reference, RenderGlyphParams, RenderImageParams, RenderSvgParams, ScaledPixels, SceneBuilder,
   9    Shadow, SharedString, Size, Style, Subscription, TaffyLayoutEngine, Task, Underline,
  10    UnderlineStyle, View, VisualContext, WeakModel, WeakView, WindowOptions, SUBPIXEL_VARIANTS,
  11};
  12use anyhow::Result;
  13use collections::HashMap;
  14use derive_more::{Deref, DerefMut};
  15use parking_lot::RwLock;
  16use slotmap::SlotMap;
  17use smallvec::SmallVec;
  18use std::{
  19    any::{Any, TypeId},
  20    borrow::{Borrow, BorrowMut, Cow},
  21    fmt::Debug,
  22    future::Future,
  23    marker::PhantomData,
  24    mem,
  25    sync::{
  26        atomic::{AtomicUsize, Ordering::SeqCst},
  27        Arc,
  28    },
  29};
  30use util::ResultExt;
  31
  32/// A global stacking order, which is created by stacking successive z-index values.
  33/// Each z-index will always be interpreted in the context of its parent z-index.
  34#[derive(Deref, DerefMut, Ord, PartialOrd, Eq, PartialEq, Clone, Default)]
  35pub(crate) struct StackingOrder(pub(crate) SmallVec<[u32; 16]>);
  36
  37/// Represents the two different phases when dispatching events.
  38#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
  39pub enum DispatchPhase {
  40    /// After the capture phase comes the bubble phase, in which mouse event listeners are
  41    /// invoked front to back and keyboard event listeners are invoked from the focused element
  42    /// to the root of the element tree. This is the phase you'll most commonly want to use when
  43    /// registering event listeners.
  44    #[default]
  45    Bubble,
  46    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
  47    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
  48    /// is used for special purposes such as clearing the "pressed" state for click events. If
  49    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
  50    /// outside of the immediate region may rely on detecting non-local events during this phase.
  51    Capture,
  52}
  53
  54type AnyListener = Box<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
  55type AnyKeyListener = Box<
  56    dyn Fn(
  57            &dyn Any,
  58            &[&DispatchContext],
  59            DispatchPhase,
  60            &mut WindowContext,
  61        ) -> Option<Box<dyn Action>>
  62        + 'static,
  63>;
  64type AnyFocusListener = Box<dyn Fn(&FocusEvent, &mut WindowContext) + 'static>;
  65
  66slotmap::new_key_type! { pub struct FocusId; }
  67
  68/// A handle which can be used to track and manipulate the focused element in a window.
  69pub struct FocusHandle {
  70    pub(crate) id: FocusId,
  71    handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
  72}
  73
  74impl FocusHandle {
  75    pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
  76        let id = handles.write().insert(AtomicUsize::new(1));
  77        Self {
  78            id,
  79            handles: handles.clone(),
  80        }
  81    }
  82
  83    pub(crate) fn for_id(
  84        id: FocusId,
  85        handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
  86    ) -> Option<Self> {
  87        let lock = handles.read();
  88        let ref_count = lock.get(id)?;
  89        if ref_count.load(SeqCst) == 0 {
  90            None
  91        } else {
  92            ref_count.fetch_add(1, SeqCst);
  93            Some(Self {
  94                id,
  95                handles: handles.clone(),
  96            })
  97        }
  98    }
  99
 100    /// Obtains whether the element associated with this handle is currently focused.
 101    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 102        cx.window.focus == Some(self.id)
 103    }
 104
 105    /// Obtains whether the element associated with this handle contains the focused
 106    /// element or is itself focused.
 107    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 108        cx.focused()
 109            .map_or(false, |focused| self.contains(&focused, cx))
 110    }
 111
 112    /// Obtains whether the element associated with this handle is contained within the
 113    /// focused element or is itself focused.
 114    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 115        let focused = cx.focused();
 116        focused.map_or(false, |focused| focused.contains(self, cx))
 117    }
 118
 119    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 120    pub(crate) fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
 121        let mut ancestor = Some(other.id);
 122        while let Some(ancestor_id) = ancestor {
 123            if self.id == ancestor_id {
 124                return true;
 125            } else {
 126                ancestor = cx.window.focus_parents_by_child.get(&ancestor_id).copied();
 127            }
 128        }
 129        false
 130    }
 131}
 132
 133impl Clone for FocusHandle {
 134    fn clone(&self) -> Self {
 135        Self::for_id(self.id, &self.handles).unwrap()
 136    }
 137}
 138
 139impl PartialEq for FocusHandle {
 140    fn eq(&self, other: &Self) -> bool {
 141        self.id == other.id
 142    }
 143}
 144
 145impl Eq for FocusHandle {}
 146
 147impl Drop for FocusHandle {
 148    fn drop(&mut self) {
 149        self.handles
 150            .read()
 151            .get(self.id)
 152            .unwrap()
 153            .fetch_sub(1, SeqCst);
 154    }
 155}
 156
 157// Holds the state for a specific window.
 158pub struct Window {
 159    handle: AnyWindowHandle,
 160    platform_window: Box<dyn PlatformWindow>,
 161    display_id: DisplayId,
 162    sprite_atlas: Arc<dyn PlatformAtlas>,
 163    rem_size: Pixels,
 164    content_size: Size<Pixels>,
 165    pub(crate) layout_engine: TaffyLayoutEngine,
 166    pub(crate) root_view: Option<AnyView>,
 167    pub(crate) element_id_stack: GlobalElementId,
 168    prev_frame_element_states: HashMap<GlobalElementId, AnyBox>,
 169    element_states: HashMap<GlobalElementId, AnyBox>,
 170    prev_frame_key_matchers: HashMap<GlobalElementId, KeyMatcher>,
 171    key_matchers: HashMap<GlobalElementId, KeyMatcher>,
 172    z_index_stack: StackingOrder,
 173    content_mask_stack: Vec<ContentMask<Pixels>>,
 174    element_offset_stack: Vec<Point<Pixels>>,
 175    mouse_listeners: HashMap<TypeId, Vec<(StackingOrder, AnyListener)>>,
 176    key_dispatch_stack: Vec<KeyDispatchStackFrame>,
 177    freeze_key_dispatch_stack: bool,
 178    focus_stack: Vec<FocusId>,
 179    focus_parents_by_child: HashMap<FocusId, FocusId>,
 180    pub(crate) focus_listeners: Vec<AnyFocusListener>,
 181    pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 182    default_prevented: bool,
 183    mouse_position: Point<Pixels>,
 184    scale_factor: f32,
 185    pub(crate) scene_builder: SceneBuilder,
 186    pub(crate) dirty: bool,
 187    pub(crate) last_blur: Option<Option<FocusId>>,
 188    pub(crate) focus: Option<FocusId>,
 189}
 190
 191impl Window {
 192    pub(crate) fn new(
 193        handle: AnyWindowHandle,
 194        options: WindowOptions,
 195        cx: &mut AppContext,
 196    ) -> Self {
 197        let platform_window = cx.platform().open_window(handle, options);
 198        let display_id = platform_window.display().id();
 199        let sprite_atlas = platform_window.sprite_atlas();
 200        let mouse_position = platform_window.mouse_position();
 201        let content_size = platform_window.content_size();
 202        let scale_factor = platform_window.scale_factor();
 203        platform_window.on_resize(Box::new({
 204            let cx = cx.to_async();
 205            move |content_size, scale_factor| {
 206                cx.update_window(handle, |cx| {
 207                    cx.window.scale_factor = scale_factor;
 208                    cx.window.scene_builder = SceneBuilder::new();
 209                    cx.window.content_size = content_size;
 210                    cx.window.display_id = cx.window.platform_window.display().id();
 211                    cx.window.dirty = true;
 212                })
 213                .log_err();
 214            }
 215        }));
 216
 217        platform_window.on_input({
 218            let cx = cx.to_async();
 219            Box::new(move |event| {
 220                cx.update_window(handle, |cx| cx.dispatch_event(event))
 221                    .log_err()
 222                    .unwrap_or(true)
 223            })
 224        });
 225
 226        Window {
 227            handle,
 228            platform_window,
 229            display_id,
 230            sprite_atlas,
 231            rem_size: px(16.),
 232            content_size,
 233            layout_engine: TaffyLayoutEngine::new(),
 234            root_view: None,
 235            element_id_stack: GlobalElementId::default(),
 236            prev_frame_element_states: HashMap::default(),
 237            element_states: HashMap::default(),
 238            prev_frame_key_matchers: HashMap::default(),
 239            key_matchers: HashMap::default(),
 240            z_index_stack: StackingOrder(SmallVec::new()),
 241            content_mask_stack: Vec::new(),
 242            element_offset_stack: Vec::new(),
 243            mouse_listeners: HashMap::default(),
 244            key_dispatch_stack: Vec::new(),
 245            freeze_key_dispatch_stack: false,
 246            focus_stack: Vec::new(),
 247            focus_parents_by_child: HashMap::default(),
 248            focus_listeners: Vec::new(),
 249            focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
 250            default_prevented: true,
 251            mouse_position,
 252            scale_factor,
 253            scene_builder: SceneBuilder::new(),
 254            dirty: true,
 255            last_blur: None,
 256            focus: None,
 257        }
 258    }
 259}
 260
 261/// When constructing the element tree, we maintain a stack of key dispatch frames until we
 262/// find the focused element. We interleave key listeners with dispatch contexts so we can use the
 263/// contexts when matching key events against the keymap.
 264enum KeyDispatchStackFrame {
 265    Listener {
 266        event_type: TypeId,
 267        listener: AnyKeyListener,
 268    },
 269    Context(DispatchContext),
 270}
 271
 272/// Indicates which region of the window is visible. Content falling outside of this mask will not be
 273/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
 274/// to leave room to support more complex shapes in the future.
 275#[derive(Clone, Debug, Default, PartialEq, Eq)]
 276#[repr(C)]
 277pub struct ContentMask<P: Clone + Default + Debug> {
 278    pub bounds: Bounds<P>,
 279}
 280
 281impl ContentMask<Pixels> {
 282    /// Scale the content mask's pixel units by the given scaling factor.
 283    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
 284        ContentMask {
 285            bounds: self.bounds.scale(factor),
 286        }
 287    }
 288
 289    /// Intersect the content mask with the given content mask.
 290    pub fn intersect(&self, other: &Self) -> Self {
 291        let bounds = self.bounds.intersect(&other.bounds);
 292        ContentMask { bounds }
 293    }
 294}
 295
 296/// Provides access to application state in the context of a single window. Derefs
 297/// to an `AppContext`, so you can also pass a `WindowContext` to any method that takes
 298/// an `AppContext` and call any `AppContext` methods.
 299pub struct WindowContext<'a, 'w> {
 300    pub(crate) app: Reference<'a, AppContext>,
 301    pub(crate) window: Reference<'w, Window>,
 302}
 303
 304impl<'a, 'w> WindowContext<'a, 'w> {
 305    pub(crate) fn immutable(app: &'a AppContext, window: &'w Window) -> Self {
 306        Self {
 307            app: Reference::Immutable(app),
 308            window: Reference::Immutable(window),
 309        }
 310    }
 311
 312    pub(crate) fn mutable(app: &'a mut AppContext, window: &'w mut Window) -> Self {
 313        Self {
 314            app: Reference::Mutable(app),
 315            window: Reference::Mutable(window),
 316        }
 317    }
 318
 319    /// Obtain a handle to the window that belongs to this context.
 320    pub fn window_handle(&self) -> AnyWindowHandle {
 321        self.window.handle
 322    }
 323
 324    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
 325    pub fn notify(&mut self) {
 326        self.window.dirty = true;
 327    }
 328
 329    /// Obtain a new `FocusHandle`, which allows you to track and manipulate the keyboard focus
 330    /// for elements rendered within this window.
 331    pub fn focus_handle(&mut self) -> FocusHandle {
 332        FocusHandle::new(&self.window.focus_handles)
 333    }
 334
 335    /// Obtain the currently focused `FocusHandle`. If no elements are focused, returns `None`.
 336    pub fn focused(&self) -> Option<FocusHandle> {
 337        self.window
 338            .focus
 339            .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
 340    }
 341
 342    /// Move focus to the element associated with the given `FocusHandle`.
 343    pub fn focus(&mut self, handle: &FocusHandle) {
 344        if self.window.last_blur.is_none() {
 345            self.window.last_blur = Some(self.window.focus);
 346        }
 347
 348        let window_id = self.window.handle.id;
 349        self.window.focus = Some(handle.id);
 350        self.app.push_effect(Effect::FocusChanged {
 351            window_id,
 352            focused: Some(handle.id),
 353        });
 354        self.notify();
 355    }
 356
 357    /// Remove focus from all elements within this context's window.
 358    pub fn blur(&mut self) {
 359        if self.window.last_blur.is_none() {
 360            self.window.last_blur = Some(self.window.focus);
 361        }
 362
 363        let window_id = self.window.handle.id;
 364        self.window.focus = None;
 365        self.app.push_effect(Effect::FocusChanged {
 366            window_id,
 367            focused: None,
 368        });
 369        self.notify();
 370    }
 371
 372    /// Create an `AsyncWindowContext`, which has a static lifetime and can be held across
 373    /// await points in async code.
 374    pub fn to_async(&self) -> AsyncWindowContext {
 375        AsyncWindowContext::new(self.app.to_async(), self.window.handle)
 376    }
 377
 378    /// Schedule the given closure to be run directly after the current frame is rendered.
 379    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + Send + 'static) {
 380        let f = Box::new(f);
 381        let display_id = self.window.display_id;
 382
 383        if let Some(callbacks) = self.next_frame_callbacks.get_mut(&display_id) {
 384            callbacks.push(f);
 385            // If there was already a callback, it means that we already scheduled a frame.
 386            if callbacks.len() > 1 {
 387                return;
 388            }
 389        } else {
 390            let async_cx = self.to_async();
 391            self.next_frame_callbacks.insert(display_id, vec![f]);
 392            self.platform().set_display_link_output_callback(
 393                display_id,
 394                Box::new(move |_current_time, _output_time| {
 395                    let _ = async_cx.update(|cx| {
 396                        let callbacks = cx
 397                            .next_frame_callbacks
 398                            .get_mut(&display_id)
 399                            .unwrap()
 400                            .drain(..)
 401                            .collect::<Vec<_>>();
 402                        for callback in callbacks {
 403                            callback(cx);
 404                        }
 405
 406                        if cx.next_frame_callbacks.get(&display_id).unwrap().is_empty() {
 407                            cx.platform().stop_display_link(display_id);
 408                        }
 409                    });
 410                }),
 411            );
 412        }
 413
 414        self.platform().start_display_link(display_id);
 415    }
 416
 417    /// Spawn the future returned by the given closure on the application thread pool.
 418    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
 419    /// use within your future.
 420    pub fn spawn<Fut, R>(
 421        &mut self,
 422        f: impl FnOnce(AnyWindowHandle, AsyncWindowContext) -> Fut,
 423    ) -> Task<R>
 424    where
 425        R: 'static,
 426        Fut: Future<Output = R> + 'static,
 427    {
 428        let window = self.window.handle;
 429        self.app.spawn(move |app| {
 430            let cx = AsyncWindowContext::new(app, window);
 431            f(window, cx)
 432        })
 433    }
 434
 435    /// Update the global of the given type. The given closure is given simultaneous mutable
 436    /// access both to the global and the context.
 437    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
 438    where
 439        G: 'static,
 440    {
 441        let mut global = self.app.lease_global::<G>();
 442        let result = f(&mut global, self);
 443        self.app.end_global_lease(global);
 444        result
 445    }
 446
 447    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
 448    /// layout is being requested, along with the layout ids of any children. This method is called during
 449    /// calls to the `Element::layout` trait method and enables any element to participate in layout.
 450    pub fn request_layout(
 451        &mut self,
 452        style: &Style,
 453        children: impl IntoIterator<Item = LayoutId>,
 454    ) -> LayoutId {
 455        self.app.layout_id_buffer.clear();
 456        self.app.layout_id_buffer.extend(children.into_iter());
 457        let rem_size = self.rem_size();
 458
 459        self.window
 460            .layout_engine
 461            .request_layout(style, rem_size, &self.app.layout_id_buffer)
 462    }
 463
 464    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
 465    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
 466    /// determine the element's size. One place this is used internally is when measuring text.
 467    ///
 468    /// The given closure is invoked at layout time with the known dimensions and available space and
 469    /// returns a `Size`.
 470    pub fn request_measured_layout<
 471        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>) -> Size<Pixels> + Send + Sync + 'static,
 472    >(
 473        &mut self,
 474        style: Style,
 475        rem_size: Pixels,
 476        measure: F,
 477    ) -> LayoutId {
 478        self.window
 479            .layout_engine
 480            .request_measured_layout(style, rem_size, measure)
 481    }
 482
 483    /// Obtain the bounds computed for the given LayoutId relative to the window. This method should not
 484    /// be invoked until the paint phase begins, and will usually be invoked by GPUI itself automatically
 485    /// in order to pass your element its `Bounds` automatically.
 486    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
 487        let mut bounds = self
 488            .window
 489            .layout_engine
 490            .layout_bounds(layout_id)
 491            .map(Into::into);
 492        bounds.origin += self.element_offset();
 493        bounds
 494    }
 495
 496    /// The scale factor of the display associated with the window. For example, it could
 497    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
 498    /// be rendered as two pixels on screen.
 499    pub fn scale_factor(&self) -> f32 {
 500        self.window.scale_factor
 501    }
 502
 503    /// The size of an em for the base font of the application. Adjusting this value allows the
 504    /// UI to scale, just like zooming a web page.
 505    pub fn rem_size(&self) -> Pixels {
 506        self.window.rem_size
 507    }
 508
 509    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
 510    /// UI to scale, just like zooming a web page.
 511    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
 512        self.window.rem_size = rem_size.into();
 513    }
 514
 515    /// The line height associated with the current text style.
 516    pub fn line_height(&self) -> Pixels {
 517        let rem_size = self.rem_size();
 518        let text_style = self.text_style();
 519        text_style
 520            .line_height
 521            .to_pixels(text_style.font_size.into(), rem_size)
 522    }
 523
 524    /// Call to prevent the default action of an event. Currently only used to prevent
 525    /// parent elements from becoming focused on mouse down.
 526    pub fn prevent_default(&mut self) {
 527        self.window.default_prevented = true;
 528    }
 529
 530    /// Obtain whether default has been prevented for the event currently being dispatched.
 531    pub fn default_prevented(&self) -> bool {
 532        self.window.default_prevented
 533    }
 534
 535    /// Register a mouse event listener on the window for the current frame. The type of event
 536    /// is determined by the first parameter of the given listener. When the next frame is rendered
 537    /// the listener will be cleared.
 538    ///
 539    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
 540    /// a specific need to register a global listener.
 541    pub fn on_mouse_event<Event: 'static>(
 542        &mut self,
 543        handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
 544    ) {
 545        let order = self.window.z_index_stack.clone();
 546        self.window
 547            .mouse_listeners
 548            .entry(TypeId::of::<Event>())
 549            .or_default()
 550            .push((
 551                order,
 552                Box::new(move |event: &dyn Any, phase, cx| {
 553                    handler(event.downcast_ref().unwrap(), phase, cx)
 554                }),
 555            ))
 556    }
 557
 558    /// The position of the mouse relative to the window.
 559    pub fn mouse_position(&self) -> Point<Pixels> {
 560        self.window.mouse_position
 561    }
 562
 563    /// Called during painting to invoke the given closure in a new stacking context. The given
 564    /// z-index is interpreted relative to the previous call to `stack`.
 565    pub fn stack<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
 566        self.window.z_index_stack.push(z_index);
 567        let result = f(self);
 568        self.window.z_index_stack.pop();
 569        result
 570    }
 571
 572    /// Paint one or more drop shadows into the scene for the current frame at the current z-index.
 573    pub fn paint_shadows(
 574        &mut self,
 575        bounds: Bounds<Pixels>,
 576        corner_radii: Corners<Pixels>,
 577        shadows: &[BoxShadow],
 578    ) {
 579        let scale_factor = self.scale_factor();
 580        let content_mask = self.content_mask();
 581        let window = &mut *self.window;
 582        for shadow in shadows {
 583            let mut shadow_bounds = bounds;
 584            shadow_bounds.origin += shadow.offset;
 585            shadow_bounds.dilate(shadow.spread_radius);
 586            window.scene_builder.insert(
 587                &window.z_index_stack,
 588                Shadow {
 589                    order: 0,
 590                    bounds: shadow_bounds.scale(scale_factor),
 591                    content_mask: content_mask.scale(scale_factor),
 592                    corner_radii: corner_radii.scale(scale_factor),
 593                    color: shadow.color,
 594                    blur_radius: shadow.blur_radius.scale(scale_factor),
 595                },
 596            );
 597        }
 598    }
 599
 600    /// Paint one or more quads into the scene for the current frame at the current stacking context.
 601    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
 602    pub fn paint_quad(
 603        &mut self,
 604        bounds: Bounds<Pixels>,
 605        corner_radii: Corners<Pixels>,
 606        background: impl Into<Hsla>,
 607        border_widths: Edges<Pixels>,
 608        border_color: impl Into<Hsla>,
 609    ) {
 610        let scale_factor = self.scale_factor();
 611        let content_mask = self.content_mask();
 612
 613        let window = &mut *self.window;
 614        window.scene_builder.insert(
 615            &window.z_index_stack,
 616            Quad {
 617                order: 0,
 618                bounds: bounds.scale(scale_factor),
 619                content_mask: content_mask.scale(scale_factor),
 620                background: background.into(),
 621                border_color: border_color.into(),
 622                corner_radii: corner_radii.scale(scale_factor),
 623                border_widths: border_widths.scale(scale_factor),
 624            },
 625        );
 626    }
 627
 628    /// Paint the given `Path` into the scene for the current frame at the current z-index.
 629    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
 630        let scale_factor = self.scale_factor();
 631        let content_mask = self.content_mask();
 632        path.content_mask = content_mask;
 633        path.color = color.into();
 634        let window = &mut *self.window;
 635        window
 636            .scene_builder
 637            .insert(&window.z_index_stack, path.scale(scale_factor));
 638    }
 639
 640    /// Paint an underline into the scene for the current frame at the current z-index.
 641    pub fn paint_underline(
 642        &mut self,
 643        origin: Point<Pixels>,
 644        width: Pixels,
 645        style: &UnderlineStyle,
 646    ) -> Result<()> {
 647        let scale_factor = self.scale_factor();
 648        let height = if style.wavy {
 649            style.thickness * 3.
 650        } else {
 651            style.thickness
 652        };
 653        let bounds = Bounds {
 654            origin,
 655            size: size(width, height),
 656        };
 657        let content_mask = self.content_mask();
 658        let window = &mut *self.window;
 659        window.scene_builder.insert(
 660            &window.z_index_stack,
 661            Underline {
 662                order: 0,
 663                bounds: bounds.scale(scale_factor),
 664                content_mask: content_mask.scale(scale_factor),
 665                thickness: style.thickness.scale(scale_factor),
 666                color: style.color.unwrap_or_default(),
 667                wavy: style.wavy,
 668            },
 669        );
 670        Ok(())
 671    }
 672
 673    /// Paint a monochrome (non-emoji) glyph into the scene for the current frame at the current z-index.
 674    pub fn paint_glyph(
 675        &mut self,
 676        origin: Point<Pixels>,
 677        font_id: FontId,
 678        glyph_id: GlyphId,
 679        font_size: Pixels,
 680        color: Hsla,
 681    ) -> Result<()> {
 682        let scale_factor = self.scale_factor();
 683        let glyph_origin = origin.scale(scale_factor);
 684        let subpixel_variant = Point {
 685            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 686            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 687        };
 688        let params = RenderGlyphParams {
 689            font_id,
 690            glyph_id,
 691            font_size,
 692            subpixel_variant,
 693            scale_factor,
 694            is_emoji: false,
 695        };
 696
 697        let raster_bounds = self.text_system().raster_bounds(&params)?;
 698        if !raster_bounds.is_zero() {
 699            let tile =
 700                self.window
 701                    .sprite_atlas
 702                    .get_or_insert_with(&params.clone().into(), &mut || {
 703                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 704                        Ok((size, Cow::Owned(bytes)))
 705                    })?;
 706            let bounds = Bounds {
 707                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 708                size: tile.bounds.size.map(Into::into),
 709            };
 710            let content_mask = self.content_mask().scale(scale_factor);
 711            let window = &mut *self.window;
 712            window.scene_builder.insert(
 713                &window.z_index_stack,
 714                MonochromeSprite {
 715                    order: 0,
 716                    bounds,
 717                    content_mask,
 718                    color,
 719                    tile,
 720                },
 721            );
 722        }
 723        Ok(())
 724    }
 725
 726    /// Paint an emoji glyph into the scene for the current frame at the current z-index.
 727    pub fn paint_emoji(
 728        &mut self,
 729        origin: Point<Pixels>,
 730        font_id: FontId,
 731        glyph_id: GlyphId,
 732        font_size: Pixels,
 733    ) -> Result<()> {
 734        let scale_factor = self.scale_factor();
 735        let glyph_origin = origin.scale(scale_factor);
 736        let params = RenderGlyphParams {
 737            font_id,
 738            glyph_id,
 739            font_size,
 740            // We don't render emojis with subpixel variants.
 741            subpixel_variant: Default::default(),
 742            scale_factor,
 743            is_emoji: true,
 744        };
 745
 746        let raster_bounds = self.text_system().raster_bounds(&params)?;
 747        if !raster_bounds.is_zero() {
 748            let tile =
 749                self.window
 750                    .sprite_atlas
 751                    .get_or_insert_with(&params.clone().into(), &mut || {
 752                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 753                        Ok((size, Cow::Owned(bytes)))
 754                    })?;
 755            let bounds = Bounds {
 756                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 757                size: tile.bounds.size.map(Into::into),
 758            };
 759            let content_mask = self.content_mask().scale(scale_factor);
 760            let window = &mut *self.window;
 761
 762            window.scene_builder.insert(
 763                &window.z_index_stack,
 764                PolychromeSprite {
 765                    order: 0,
 766                    bounds,
 767                    corner_radii: Default::default(),
 768                    content_mask,
 769                    tile,
 770                    grayscale: false,
 771                },
 772            );
 773        }
 774        Ok(())
 775    }
 776
 777    /// Paint a monochrome SVG into the scene for the current frame at the current stacking context.
 778    pub fn paint_svg(
 779        &mut self,
 780        bounds: Bounds<Pixels>,
 781        path: SharedString,
 782        color: Hsla,
 783    ) -> Result<()> {
 784        let scale_factor = self.scale_factor();
 785        let bounds = bounds.scale(scale_factor);
 786        // Render the SVG at twice the size to get a higher quality result.
 787        let params = RenderSvgParams {
 788            path,
 789            size: bounds
 790                .size
 791                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
 792        };
 793
 794        let tile =
 795            self.window
 796                .sprite_atlas
 797                .get_or_insert_with(&params.clone().into(), &mut || {
 798                    let bytes = self.svg_renderer.render(&params)?;
 799                    Ok((params.size, Cow::Owned(bytes)))
 800                })?;
 801        let content_mask = self.content_mask().scale(scale_factor);
 802
 803        let window = &mut *self.window;
 804        window.scene_builder.insert(
 805            &window.z_index_stack,
 806            MonochromeSprite {
 807                order: 0,
 808                bounds,
 809                content_mask,
 810                color,
 811                tile,
 812            },
 813        );
 814
 815        Ok(())
 816    }
 817
 818    /// Paint an image into the scene for the current frame at the current z-index.
 819    pub fn paint_image(
 820        &mut self,
 821        bounds: Bounds<Pixels>,
 822        corner_radii: Corners<Pixels>,
 823        data: Arc<ImageData>,
 824        grayscale: bool,
 825    ) -> Result<()> {
 826        let scale_factor = self.scale_factor();
 827        let bounds = bounds.scale(scale_factor);
 828        let params = RenderImageParams { image_id: data.id };
 829
 830        let tile = self
 831            .window
 832            .sprite_atlas
 833            .get_or_insert_with(&params.clone().into(), &mut || {
 834                Ok((data.size(), Cow::Borrowed(data.as_bytes())))
 835            })?;
 836        let content_mask = self.content_mask().scale(scale_factor);
 837        let corner_radii = corner_radii.scale(scale_factor);
 838
 839        let window = &mut *self.window;
 840        window.scene_builder.insert(
 841            &window.z_index_stack,
 842            PolychromeSprite {
 843                order: 0,
 844                bounds,
 845                content_mask,
 846                corner_radii,
 847                tile,
 848                grayscale,
 849            },
 850        );
 851        Ok(())
 852    }
 853
 854    /// Draw pixels to the display for this window based on the contents of its scene.
 855    pub(crate) fn draw(&mut self) {
 856        let root_view = self.window.root_view.take().unwrap();
 857
 858        self.start_frame();
 859
 860        self.stack(0, |cx| {
 861            let available_space = cx.window.content_size.map(Into::into);
 862            root_view.draw(available_space, cx);
 863        });
 864
 865        if let Some(active_drag) = self.app.active_drag.take() {
 866            self.stack(1, |cx| {
 867                let offset = cx.mouse_position() - active_drag.cursor_offset;
 868                cx.with_element_offset(Some(offset), |cx| {
 869                    let available_space =
 870                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
 871                    active_drag.view.draw(available_space, cx);
 872                    cx.active_drag = Some(active_drag);
 873                });
 874            });
 875        }
 876
 877        self.window.root_view = Some(root_view);
 878        let scene = self.window.scene_builder.build();
 879
 880        self.window.platform_window.draw(scene);
 881        self.window.dirty = false;
 882    }
 883
 884    fn start_frame(&mut self) {
 885        self.text_system().start_frame();
 886
 887        let window = &mut *self.window;
 888
 889        // Move the current frame element states to the previous frame.
 890        // The new empty element states map will be populated for any element states we
 891        // reference during the upcoming frame.
 892        mem::swap(
 893            &mut window.element_states,
 894            &mut window.prev_frame_element_states,
 895        );
 896        window.element_states.clear();
 897
 898        // Make the current key matchers the previous, and then clear the current.
 899        // An empty key matcher map will be created for every identified element in the
 900        // upcoming frame.
 901        mem::swap(
 902            &mut window.key_matchers,
 903            &mut window.prev_frame_key_matchers,
 904        );
 905        window.key_matchers.clear();
 906
 907        // Clear mouse event listeners, because elements add new element listeners
 908        // when the upcoming frame is painted.
 909        window.mouse_listeners.values_mut().for_each(Vec::clear);
 910
 911        // Clear focus state, because we determine what is focused when the new elements
 912        // in the upcoming frame are initialized.
 913        window.focus_listeners.clear();
 914        window.key_dispatch_stack.clear();
 915        window.focus_parents_by_child.clear();
 916        window.freeze_key_dispatch_stack = false;
 917    }
 918
 919    /// Dispatch a mouse or keyboard event on the window.
 920    fn dispatch_event(&mut self, event: InputEvent) -> bool {
 921        let event = match event {
 922            // Track the mouse position with our own state, since accessing the platform
 923            // API for the mouse position can only occur on the main thread.
 924            InputEvent::MouseMove(mouse_move) => {
 925                self.window.mouse_position = mouse_move.position;
 926                InputEvent::MouseMove(mouse_move)
 927            }
 928            // Translate dragging and dropping of external files from the operating system
 929            // to internal drag and drop events.
 930            InputEvent::FileDrop(file_drop) => match file_drop {
 931                FileDropEvent::Entered { position, files } => {
 932                    self.window.mouse_position = position;
 933                    if self.active_drag.is_none() {
 934                        self.active_drag = Some(AnyDrag {
 935                            view: self.build_view(|_| files).into(),
 936                            cursor_offset: position,
 937                        });
 938                    }
 939                    InputEvent::MouseDown(MouseDownEvent {
 940                        position,
 941                        button: MouseButton::Left,
 942                        click_count: 1,
 943                        modifiers: Modifiers::default(),
 944                    })
 945                }
 946                FileDropEvent::Pending { position } => {
 947                    self.window.mouse_position = position;
 948                    InputEvent::MouseMove(MouseMoveEvent {
 949                        position,
 950                        pressed_button: Some(MouseButton::Left),
 951                        modifiers: Modifiers::default(),
 952                    })
 953                }
 954                FileDropEvent::Submit { position } => {
 955                    self.window.mouse_position = position;
 956                    InputEvent::MouseUp(MouseUpEvent {
 957                        button: MouseButton::Left,
 958                        position,
 959                        modifiers: Modifiers::default(),
 960                        click_count: 1,
 961                    })
 962                }
 963                FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
 964                    button: MouseButton::Left,
 965                    position: Point::default(),
 966                    modifiers: Modifiers::default(),
 967                    click_count: 1,
 968                }),
 969            },
 970            _ => event,
 971        };
 972
 973        if let Some(any_mouse_event) = event.mouse_event() {
 974            // Handlers may set this to false by calling `stop_propagation`
 975            self.app.propagate_event = true;
 976            self.window.default_prevented = false;
 977
 978            if let Some(mut handlers) = self
 979                .window
 980                .mouse_listeners
 981                .remove(&any_mouse_event.type_id())
 982            {
 983                // Because handlers may add other handlers, we sort every time.
 984                handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
 985
 986                // Capture phase, events bubble from back to front. Handlers for this phase are used for
 987                // special purposes, such as detecting events outside of a given Bounds.
 988                for (_, handler) in &handlers {
 989                    handler(any_mouse_event, DispatchPhase::Capture, self);
 990                    if !self.app.propagate_event {
 991                        break;
 992                    }
 993                }
 994
 995                // Bubble phase, where most normal handlers do their work.
 996                if self.app.propagate_event {
 997                    for (_, handler) in handlers.iter().rev() {
 998                        handler(any_mouse_event, DispatchPhase::Bubble, self);
 999                        if !self.app.propagate_event {
1000                            break;
1001                        }
1002                    }
1003                }
1004
1005                if self.app.propagate_event
1006                    && any_mouse_event.downcast_ref::<MouseUpEvent>().is_some()
1007                {
1008                    self.active_drag = None;
1009                }
1010
1011                // Just in case any handlers added new handlers, which is weird, but possible.
1012                handlers.extend(
1013                    self.window
1014                        .mouse_listeners
1015                        .get_mut(&any_mouse_event.type_id())
1016                        .into_iter()
1017                        .flat_map(|handlers| handlers.drain(..)),
1018                );
1019                self.window
1020                    .mouse_listeners
1021                    .insert(any_mouse_event.type_id(), handlers);
1022            }
1023        } else if let Some(any_key_event) = event.keyboard_event() {
1024            let key_dispatch_stack = mem::take(&mut self.window.key_dispatch_stack);
1025            let key_event_type = any_key_event.type_id();
1026            let mut context_stack = SmallVec::<[&DispatchContext; 16]>::new();
1027
1028            for (ix, frame) in key_dispatch_stack.iter().enumerate() {
1029                match frame {
1030                    KeyDispatchStackFrame::Listener {
1031                        event_type,
1032                        listener,
1033                    } => {
1034                        if key_event_type == *event_type {
1035                            if let Some(action) = listener(
1036                                any_key_event,
1037                                &context_stack,
1038                                DispatchPhase::Capture,
1039                                self,
1040                            ) {
1041                                self.dispatch_action(action, &key_dispatch_stack[..ix]);
1042                            }
1043                            if !self.app.propagate_event {
1044                                break;
1045                            }
1046                        }
1047                    }
1048                    KeyDispatchStackFrame::Context(context) => {
1049                        context_stack.push(&context);
1050                    }
1051                }
1052            }
1053
1054            if self.app.propagate_event {
1055                for (ix, frame) in key_dispatch_stack.iter().enumerate().rev() {
1056                    match frame {
1057                        KeyDispatchStackFrame::Listener {
1058                            event_type,
1059                            listener,
1060                        } => {
1061                            if key_event_type == *event_type {
1062                                if let Some(action) = listener(
1063                                    any_key_event,
1064                                    &context_stack,
1065                                    DispatchPhase::Bubble,
1066                                    self,
1067                                ) {
1068                                    self.dispatch_action(action, &key_dispatch_stack[..ix]);
1069                                }
1070
1071                                if !self.app.propagate_event {
1072                                    break;
1073                                }
1074                            }
1075                        }
1076                        KeyDispatchStackFrame::Context(_) => {
1077                            context_stack.pop();
1078                        }
1079                    }
1080                }
1081            }
1082
1083            drop(context_stack);
1084            self.window.key_dispatch_stack = key_dispatch_stack;
1085        }
1086
1087        true
1088    }
1089
1090    /// Attempt to map a keystroke to an action based on the keymap.
1091    pub fn match_keystroke(
1092        &mut self,
1093        element_id: &GlobalElementId,
1094        keystroke: &Keystroke,
1095        context_stack: &[&DispatchContext],
1096    ) -> KeyMatch {
1097        let key_match = self
1098            .window
1099            .key_matchers
1100            .get_mut(element_id)
1101            .unwrap()
1102            .match_keystroke(keystroke, context_stack);
1103
1104        if key_match.is_some() {
1105            for matcher in self.window.key_matchers.values_mut() {
1106                matcher.clear_pending();
1107            }
1108        }
1109
1110        key_match
1111    }
1112
1113    /// Register the given handler to be invoked whenever the global of the given type
1114    /// is updated.
1115    pub fn observe_global<G: 'static>(
1116        &mut self,
1117        f: impl Fn(&mut WindowContext<'_, '_>) + Send + 'static,
1118    ) -> Subscription {
1119        let window_id = self.window.handle.id;
1120        self.global_observers.insert(
1121            TypeId::of::<G>(),
1122            Box::new(move |cx| cx.update_window(window_id, |cx| f(cx)).is_ok()),
1123        )
1124    }
1125
1126    fn dispatch_action(
1127        &mut self,
1128        action: Box<dyn Action>,
1129        dispatch_stack: &[KeyDispatchStackFrame],
1130    ) {
1131        let action_type = action.as_any().type_id();
1132
1133        if let Some(mut global_listeners) = self.app.global_action_listeners.remove(&action_type) {
1134            for listener in &global_listeners {
1135                listener(action.as_ref(), DispatchPhase::Capture, self);
1136                if !self.app.propagate_event {
1137                    break;
1138                }
1139            }
1140            global_listeners.extend(
1141                self.global_action_listeners
1142                    .remove(&action_type)
1143                    .unwrap_or_default(),
1144            );
1145            self.global_action_listeners
1146                .insert(action_type, global_listeners);
1147        }
1148
1149        if self.app.propagate_event {
1150            for stack_frame in dispatch_stack {
1151                if let KeyDispatchStackFrame::Listener {
1152                    event_type,
1153                    listener,
1154                } = stack_frame
1155                {
1156                    if action_type == *event_type {
1157                        listener(action.as_any(), &[], DispatchPhase::Capture, self);
1158                        if !self.app.propagate_event {
1159                            break;
1160                        }
1161                    }
1162                }
1163            }
1164        }
1165
1166        if self.app.propagate_event {
1167            for stack_frame in dispatch_stack.iter().rev() {
1168                if let KeyDispatchStackFrame::Listener {
1169                    event_type,
1170                    listener,
1171                } = stack_frame
1172                {
1173                    if action_type == *event_type {
1174                        listener(action.as_any(), &[], DispatchPhase::Bubble, self);
1175                        if !self.app.propagate_event {
1176                            break;
1177                        }
1178                    }
1179                }
1180            }
1181        }
1182
1183        if self.app.propagate_event {
1184            if let Some(mut global_listeners) =
1185                self.app.global_action_listeners.remove(&action_type)
1186            {
1187                for listener in global_listeners.iter().rev() {
1188                    listener(action.as_ref(), DispatchPhase::Bubble, self);
1189                    if !self.app.propagate_event {
1190                        break;
1191                    }
1192                }
1193                global_listeners.extend(
1194                    self.global_action_listeners
1195                        .remove(&action_type)
1196                        .unwrap_or_default(),
1197                );
1198                self.global_action_listeners
1199                    .insert(action_type, global_listeners);
1200            }
1201        }
1202    }
1203}
1204
1205impl Context for WindowContext<'_, '_> {
1206    type ModelContext<'a, T> = ModelContext<'a, T>;
1207    type Result<T> = T;
1208
1209    fn build_model<T>(
1210        &mut self,
1211        build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
1212    ) -> Model<T>
1213    where
1214        T: 'static,
1215    {
1216        let slot = self.app.entities.reserve();
1217        let model = build_model(&mut ModelContext::mutable(&mut *self.app, slot.downgrade()));
1218        self.entities.insert(slot, model)
1219    }
1220
1221    fn update_model<T: 'static, R>(
1222        &mut self,
1223        model: &Model<T>,
1224        update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
1225    ) -> R {
1226        let mut entity = self.entities.lease(model);
1227        let result = update(
1228            &mut *entity,
1229            &mut ModelContext::mutable(&mut *self.app, model.downgrade()),
1230        );
1231        self.entities.end_lease(entity);
1232        result
1233    }
1234}
1235
1236impl VisualContext for WindowContext<'_, '_> {
1237    type ViewContext<'a, 'w, V> = ViewContext<'a, 'w, V>;
1238
1239    fn build_view<V>(
1240        &mut self,
1241        build_view_state: impl FnOnce(&mut Self::ViewContext<'_, '_, V>) -> V,
1242    ) -> Self::Result<View<V>>
1243    where
1244        V: 'static,
1245    {
1246        let slot = self.app.entities.reserve();
1247        let view = View {
1248            model: slot.clone(),
1249        };
1250        let mut cx = ViewContext::mutable(&mut *self.app, &mut *self.window, view.downgrade());
1251        let entity = build_view_state(&mut cx);
1252        self.entities.insert(slot, entity);
1253        view
1254    }
1255
1256    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1257    fn update_view<T: 'static, R>(
1258        &mut self,
1259        view: &View<T>,
1260        update: impl FnOnce(&mut T, &mut Self::ViewContext<'_, '_, T>) -> R,
1261    ) -> Self::Result<R> {
1262        let mut lease = self.app.entities.lease(&view.model);
1263        let mut cx = ViewContext::mutable(&mut *self.app, &mut *self.window, view.downgrade());
1264        let result = update(&mut *lease, &mut cx);
1265        cx.app.entities.end_lease(lease);
1266        result
1267    }
1268}
1269
1270impl<'a, 'w> std::ops::Deref for WindowContext<'a, 'w> {
1271    type Target = AppContext;
1272
1273    fn deref(&self) -> &Self::Target {
1274        &self.app
1275    }
1276}
1277
1278impl<'a, 'w> std::ops::DerefMut for WindowContext<'a, 'w> {
1279    fn deref_mut(&mut self) -> &mut Self::Target {
1280        &mut self.app
1281    }
1282}
1283
1284impl<'a, 'w> Borrow<AppContext> for WindowContext<'a, 'w> {
1285    fn borrow(&self) -> &AppContext {
1286        &self.app
1287    }
1288}
1289
1290impl<'a, 'w> BorrowMut<AppContext> for WindowContext<'a, 'w> {
1291    fn borrow_mut(&mut self) -> &mut AppContext {
1292        &mut self.app
1293    }
1294}
1295
1296pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1297    fn app_mut(&mut self) -> &mut AppContext {
1298        self.borrow_mut()
1299    }
1300
1301    fn window(&self) -> &Window {
1302        self.borrow()
1303    }
1304
1305    fn window_mut(&mut self) -> &mut Window {
1306        self.borrow_mut()
1307    }
1308
1309    /// Pushes the given element id onto the global stack and invokes the given closure
1310    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1311    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1312    /// used to associate state with identified elements across separate frames.
1313    fn with_element_id<R>(
1314        &mut self,
1315        id: impl Into<ElementId>,
1316        f: impl FnOnce(GlobalElementId, &mut Self) -> R,
1317    ) -> R {
1318        let keymap = self.app_mut().keymap.clone();
1319        let window = self.window_mut();
1320        window.element_id_stack.push(id.into());
1321        let global_id = window.element_id_stack.clone();
1322
1323        if window.key_matchers.get(&global_id).is_none() {
1324            window.key_matchers.insert(
1325                global_id.clone(),
1326                window
1327                    .prev_frame_key_matchers
1328                    .remove(&global_id)
1329                    .unwrap_or_else(|| KeyMatcher::new(keymap)),
1330            );
1331        }
1332
1333        let result = f(global_id, self);
1334        let window: &mut Window = self.borrow_mut();
1335        window.element_id_stack.pop();
1336        result
1337    }
1338
1339    /// Invoke the given function with the given content mask after intersecting it
1340    /// with the current mask.
1341    fn with_content_mask<R>(
1342        &mut self,
1343        mask: ContentMask<Pixels>,
1344        f: impl FnOnce(&mut Self) -> R,
1345    ) -> R {
1346        let mask = mask.intersect(&self.content_mask());
1347        self.window_mut().content_mask_stack.push(mask);
1348        let result = f(self);
1349        self.window_mut().content_mask_stack.pop();
1350        result
1351    }
1352
1353    /// Update the global element offset based on the given offset. This is used to implement
1354    /// scrolling and position drag handles.
1355    fn with_element_offset<R>(
1356        &mut self,
1357        offset: Option<Point<Pixels>>,
1358        f: impl FnOnce(&mut Self) -> R,
1359    ) -> R {
1360        let Some(offset) = offset else {
1361            return f(self);
1362        };
1363
1364        let offset = self.element_offset() + offset;
1365        self.window_mut().element_offset_stack.push(offset);
1366        let result = f(self);
1367        self.window_mut().element_offset_stack.pop();
1368        result
1369    }
1370
1371    /// Obtain the current element offset.
1372    fn element_offset(&self) -> Point<Pixels> {
1373        self.window()
1374            .element_offset_stack
1375            .last()
1376            .copied()
1377            .unwrap_or_default()
1378    }
1379
1380    /// Update or intialize state for an element with the given id that lives across multiple
1381    /// frames. If an element with this id existed in the previous frame, its state will be passed
1382    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1383    /// when drawing the next frame.
1384    fn with_element_state<S, R>(
1385        &mut self,
1386        id: ElementId,
1387        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1388    ) -> R
1389    where
1390        S: 'static,
1391    {
1392        self.with_element_id(id, |global_id, cx| {
1393            if let Some(any) = cx
1394                .window_mut()
1395                .element_states
1396                .remove(&global_id)
1397                .or_else(|| cx.window_mut().prev_frame_element_states.remove(&global_id))
1398            {
1399                // Using the extra inner option to avoid needing to reallocate a new box.
1400                let mut state_box = any
1401                    .downcast::<Option<S>>()
1402                    .expect("invalid element state type for id");
1403                let state = state_box
1404                    .take()
1405                    .expect("element state is already on the stack");
1406                let (result, state) = f(Some(state), cx);
1407                state_box.replace(state);
1408                cx.window_mut().element_states.insert(global_id, state_box);
1409                result
1410            } else {
1411                let (result, state) = f(None, cx);
1412                cx.window_mut()
1413                    .element_states
1414                    .insert(global_id, Box::new(Some(state)));
1415                result
1416            }
1417        })
1418    }
1419
1420    /// Like `with_element_state`, but for situations where the element_id is optional. If the
1421    /// id is `None`, no state will be retrieved or stored.
1422    fn with_optional_element_state<S, R>(
1423        &mut self,
1424        element_id: Option<ElementId>,
1425        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1426    ) -> R
1427    where
1428        S: 'static,
1429    {
1430        if let Some(element_id) = element_id {
1431            self.with_element_state(element_id, f)
1432        } else {
1433            f(None, self).0
1434        }
1435    }
1436
1437    /// Obtain the current content mask.
1438    fn content_mask(&self) -> ContentMask<Pixels> {
1439        self.window()
1440            .content_mask_stack
1441            .last()
1442            .cloned()
1443            .unwrap_or_else(|| ContentMask {
1444                bounds: Bounds {
1445                    origin: Point::default(),
1446                    size: self.window().content_size,
1447                },
1448            })
1449    }
1450
1451    /// The size of an em for the base font of the application. Adjusting this value allows the
1452    /// UI to scale, just like zooming a web page.
1453    fn rem_size(&self) -> Pixels {
1454        self.window().rem_size
1455    }
1456}
1457
1458impl Borrow<Window> for WindowContext<'_, '_> {
1459    fn borrow(&self) -> &Window {
1460        &self.window
1461    }
1462}
1463
1464impl BorrowMut<Window> for WindowContext<'_, '_> {
1465    fn borrow_mut(&mut self) -> &mut Window {
1466        &mut self.window
1467    }
1468}
1469
1470impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1471
1472pub struct ViewContext<'a, 'w, V> {
1473    window_cx: WindowContext<'a, 'w>,
1474    view: WeakView<V>,
1475}
1476
1477impl<V> Borrow<AppContext> for ViewContext<'_, '_, V> {
1478    fn borrow(&self) -> &AppContext {
1479        &*self.window_cx.app
1480    }
1481}
1482
1483impl<V> BorrowMut<AppContext> for ViewContext<'_, '_, V> {
1484    fn borrow_mut(&mut self) -> &mut AppContext {
1485        &mut *self.window_cx.app
1486    }
1487}
1488
1489impl<V> Borrow<Window> for ViewContext<'_, '_, V> {
1490    fn borrow(&self) -> &Window {
1491        &*self.window_cx.window
1492    }
1493}
1494
1495impl<V> BorrowMut<Window> for ViewContext<'_, '_, V> {
1496    fn borrow_mut(&mut self) -> &mut Window {
1497        &mut *self.window_cx.window
1498    }
1499}
1500
1501impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
1502    pub(crate) fn mutable(
1503        app: &'a mut AppContext,
1504        window: &'w mut Window,
1505        view: WeakView<V>,
1506    ) -> Self {
1507        Self {
1508            window_cx: WindowContext::mutable(app, window),
1509            view,
1510        }
1511    }
1512
1513    pub fn view(&self) -> WeakView<V> {
1514        self.view.clone()
1515    }
1516
1517    pub fn model(&self) -> WeakModel<V> {
1518        self.view.model.clone()
1519    }
1520
1521    pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1522        self.window.z_index_stack.push(order);
1523        let result = f(self);
1524        self.window.z_index_stack.pop();
1525        result
1526    }
1527
1528    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + Send + 'static)
1529    where
1530        V: Any + Send,
1531    {
1532        let view = self.view().upgrade().unwrap();
1533        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1534    }
1535
1536    pub fn observe<V2, E>(
1537        &mut self,
1538        entity: &E,
1539        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, '_, V>) + Send + 'static,
1540    ) -> Subscription
1541    where
1542        V2: 'static,
1543        V: Any + Send,
1544        E: Entity<V2>,
1545    {
1546        let view = self.view();
1547        let entity_id = entity.entity_id();
1548        let entity = entity.downgrade();
1549        let window_handle = self.window.handle;
1550        self.app.observers.insert(
1551            entity_id,
1552            Box::new(move |cx| {
1553                cx.update_window(window_handle.id, |cx| {
1554                    if let Some(handle) = E::upgrade_from(&entity) {
1555                        view.update(cx, |this, cx| on_notify(this, handle, cx))
1556                            .is_ok()
1557                    } else {
1558                        false
1559                    }
1560                })
1561                .unwrap_or(false)
1562            }),
1563        )
1564    }
1565
1566    pub fn subscribe<V2, E>(
1567        &mut self,
1568        entity: &E,
1569        mut on_event: impl FnMut(&mut V, E, &V2::Event, &mut ViewContext<'_, '_, V>) + Send + 'static,
1570    ) -> Subscription
1571    where
1572        V2: EventEmitter,
1573        E: Entity<V2>,
1574    {
1575        let view = self.view();
1576        let entity_id = entity.entity_id();
1577        let handle = entity.downgrade();
1578        let window_handle = self.window.handle;
1579        self.app.event_listeners.insert(
1580            entity_id,
1581            Box::new(move |event, cx| {
1582                cx.update_window(window_handle.id, |cx| {
1583                    if let Some(handle) = E::upgrade_from(&handle) {
1584                        let event = event.downcast_ref().expect("invalid event type");
1585                        view.update(cx, |this, cx| on_event(this, handle, event, cx))
1586                            .is_ok()
1587                    } else {
1588                        false
1589                    }
1590                })
1591                .unwrap_or(false)
1592            }),
1593        )
1594    }
1595
1596    pub fn on_release(
1597        &mut self,
1598        mut on_release: impl FnMut(&mut V, &mut WindowContext) + Send + 'static,
1599    ) -> Subscription {
1600        let window_handle = self.window.handle;
1601        self.app.release_listeners.insert(
1602            self.view.model.entity_id,
1603            Box::new(move |this, cx| {
1604                let this = this.downcast_mut().expect("invalid entity type");
1605                // todo!("are we okay with silently swallowing the error?")
1606                let _ = cx.update_window(window_handle.id, |cx| on_release(this, cx));
1607            }),
1608        )
1609    }
1610
1611    pub fn observe_release<V2, E>(
1612        &mut self,
1613        entity: &E,
1614        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, '_, V>) + Send + 'static,
1615    ) -> Subscription
1616    where
1617        V: Any + Send,
1618        V2: 'static,
1619        E: Entity<V2>,
1620    {
1621        let view = self.view();
1622        let entity_id = entity.entity_id();
1623        let window_handle = self.window.handle;
1624        self.app.release_listeners.insert(
1625            entity_id,
1626            Box::new(move |entity, cx| {
1627                let entity = entity.downcast_mut().expect("invalid entity type");
1628                let _ = cx.update_window(window_handle.id, |cx| {
1629                    view.update(cx, |this, cx| on_release(this, entity, cx))
1630                });
1631            }),
1632        )
1633    }
1634
1635    pub fn notify(&mut self) {
1636        self.window_cx.notify();
1637        self.window_cx.app.push_effect(Effect::Notify {
1638            emitter: self.view.model.entity_id,
1639        });
1640    }
1641
1642    pub fn on_focus_changed(
1643        &mut self,
1644        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,
1645    ) {
1646        let handle = self.view();
1647        self.window.focus_listeners.push(Box::new(move |event, cx| {
1648            handle
1649                .update(cx, |view, cx| listener(view, event, cx))
1650                .log_err();
1651        }));
1652    }
1653
1654    pub fn with_key_listeners<R>(
1655        &mut self,
1656        key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
1657        f: impl FnOnce(&mut Self) -> R,
1658    ) -> R {
1659        let old_stack_len = self.window.key_dispatch_stack.len();
1660        if !self.window.freeze_key_dispatch_stack {
1661            for (event_type, listener) in key_listeners {
1662                let handle = self.view();
1663                let listener = Box::new(
1664                    move |event: &dyn Any,
1665                          context_stack: &[&DispatchContext],
1666                          phase: DispatchPhase,
1667                          cx: &mut WindowContext<'_, '_>| {
1668                        handle
1669                            .update(cx, |view, cx| {
1670                                listener(view, event, context_stack, phase, cx)
1671                            })
1672                            .log_err()
1673                            .flatten()
1674                    },
1675                );
1676                self.window
1677                    .key_dispatch_stack
1678                    .push(KeyDispatchStackFrame::Listener {
1679                        event_type,
1680                        listener,
1681                    });
1682            }
1683        }
1684
1685        let result = f(self);
1686
1687        if !self.window.freeze_key_dispatch_stack {
1688            self.window.key_dispatch_stack.truncate(old_stack_len);
1689        }
1690
1691        result
1692    }
1693
1694    pub fn with_key_dispatch_context<R>(
1695        &mut self,
1696        context: DispatchContext,
1697        f: impl FnOnce(&mut Self) -> R,
1698    ) -> R {
1699        if context.is_empty() {
1700            return f(self);
1701        }
1702
1703        if !self.window.freeze_key_dispatch_stack {
1704            self.window
1705                .key_dispatch_stack
1706                .push(KeyDispatchStackFrame::Context(context));
1707        }
1708
1709        let result = f(self);
1710
1711        if !self.window.freeze_key_dispatch_stack {
1712            self.window.key_dispatch_stack.pop();
1713        }
1714
1715        result
1716    }
1717
1718    pub fn with_focus<R>(
1719        &mut self,
1720        focus_handle: FocusHandle,
1721        f: impl FnOnce(&mut Self) -> R,
1722    ) -> R {
1723        if let Some(parent_focus_id) = self.window.focus_stack.last().copied() {
1724            self.window
1725                .focus_parents_by_child
1726                .insert(focus_handle.id, parent_focus_id);
1727        }
1728        self.window.focus_stack.push(focus_handle.id);
1729
1730        if Some(focus_handle.id) == self.window.focus {
1731            self.window.freeze_key_dispatch_stack = true;
1732        }
1733
1734        let result = f(self);
1735
1736        self.window.focus_stack.pop();
1737        result
1738    }
1739
1740    pub fn spawn<Fut, R>(
1741        &mut self,
1742        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
1743    ) -> Task<R>
1744    where
1745        R: 'static,
1746        Fut: Future<Output = R> + 'static,
1747    {
1748        let view = self.view();
1749        self.window_cx.spawn(move |_, cx| {
1750            let result = f(view, cx);
1751            async move { result.await }
1752        })
1753    }
1754
1755    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
1756    where
1757        G: 'static + Send,
1758    {
1759        let mut global = self.app.lease_global::<G>();
1760        let result = f(&mut global, self);
1761        self.app.end_global_lease(global);
1762        result
1763    }
1764
1765    pub fn observe_global<G: 'static>(
1766        &mut self,
1767        f: impl Fn(&mut V, &mut ViewContext<'_, '_, V>) + Send + 'static,
1768    ) -> Subscription {
1769        let window_id = self.window.handle.id;
1770        let handle = self.view();
1771        self.global_observers.insert(
1772            TypeId::of::<G>(),
1773            Box::new(move |cx| {
1774                cx.update_window(window_id, |cx| {
1775                    handle.update(cx, |view, cx| f(view, cx)).is_ok()
1776                })
1777                .unwrap_or(false)
1778            }),
1779        )
1780    }
1781
1782    pub fn on_mouse_event<Event: 'static>(
1783        &mut self,
1784        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
1785    ) {
1786        let handle = self.view().upgrade().unwrap();
1787        self.window_cx.on_mouse_event(move |event, phase, cx| {
1788            handle.update(cx, |view, cx| {
1789                handler(view, event, phase, cx);
1790            })
1791        });
1792    }
1793}
1794
1795impl<'a, 'w, V> ViewContext<'a, 'w, V>
1796where
1797    V: EventEmitter,
1798    V::Event: Any + Send,
1799{
1800    pub fn emit(&mut self, event: V::Event) {
1801        let emitter = self.view.model.entity_id;
1802        self.app.push_effect(Effect::Emit {
1803            emitter,
1804            event: Box::new(event),
1805        });
1806    }
1807}
1808
1809impl<'a, 'w, V> Context for ViewContext<'a, 'w, V> {
1810    type ModelContext<'b, U> = ModelContext<'b, U>;
1811    type Result<U> = U;
1812
1813    fn build_model<T: 'static>(
1814        &mut self,
1815        build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
1816    ) -> Model<T> {
1817        self.window_cx.build_model(build_model)
1818    }
1819
1820    fn update_model<T: 'static, R>(
1821        &mut self,
1822        model: &Model<T>,
1823        update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
1824    ) -> R {
1825        self.window_cx.update_model(model, update)
1826    }
1827}
1828
1829impl<V: 'static> VisualContext for ViewContext<'_, '_, V> {
1830    type ViewContext<'a, 'w, V2> = ViewContext<'a, 'w, V2>;
1831
1832    fn build_view<W: 'static>(
1833        &mut self,
1834        build_view: impl FnOnce(&mut Self::ViewContext<'_, '_, W>) -> W,
1835    ) -> Self::Result<View<W>> {
1836        self.window_cx.build_view(build_view)
1837    }
1838
1839    fn update_view<V2: 'static, R>(
1840        &mut self,
1841        view: &View<V2>,
1842        update: impl FnOnce(&mut V2, &mut Self::ViewContext<'_, '_, V2>) -> R,
1843    ) -> Self::Result<R> {
1844        self.window_cx.update_view(view, update)
1845    }
1846}
1847
1848impl<'a, 'w, V> std::ops::Deref for ViewContext<'a, 'w, V> {
1849    type Target = WindowContext<'a, 'w>;
1850
1851    fn deref(&self) -> &Self::Target {
1852        &self.window_cx
1853    }
1854}
1855
1856impl<'a, 'w, V> std::ops::DerefMut for ViewContext<'a, 'w, V> {
1857    fn deref_mut(&mut self) -> &mut Self::Target {
1858        &mut self.window_cx
1859    }
1860}
1861
1862// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
1863slotmap::new_key_type! { pub struct WindowId; }
1864
1865impl WindowId {
1866    pub fn as_u64(&self) -> u64 {
1867        self.0.as_ffi()
1868    }
1869}
1870
1871#[derive(PartialEq, Eq)]
1872pub struct WindowHandle<V> {
1873    id: WindowId,
1874    state_type: PhantomData<V>,
1875}
1876
1877impl<S> Copy for WindowHandle<S> {}
1878
1879impl<S> Clone for WindowHandle<S> {
1880    fn clone(&self) -> Self {
1881        WindowHandle {
1882            id: self.id,
1883            state_type: PhantomData,
1884        }
1885    }
1886}
1887
1888impl<S> WindowHandle<S> {
1889    pub fn new(id: WindowId) -> Self {
1890        WindowHandle {
1891            id,
1892            state_type: PhantomData,
1893        }
1894    }
1895}
1896
1897impl<S: 'static> Into<AnyWindowHandle> for WindowHandle<S> {
1898    fn into(self) -> AnyWindowHandle {
1899        AnyWindowHandle {
1900            id: self.id,
1901            state_type: TypeId::of::<S>(),
1902        }
1903    }
1904}
1905
1906#[derive(Copy, Clone, PartialEq, Eq)]
1907pub struct AnyWindowHandle {
1908    pub(crate) id: WindowId,
1909    state_type: TypeId,
1910}
1911
1912impl AnyWindowHandle {
1913    pub fn window_id(&self) -> WindowId {
1914        self.id
1915    }
1916}
1917
1918#[cfg(any(test, feature = "test-support"))]
1919impl From<SmallVec<[u32; 16]>> for StackingOrder {
1920    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
1921        StackingOrder(small_vec)
1922    }
1923}
1924
1925#[derive(Clone, Debug, Eq, PartialEq, Hash)]
1926pub enum ElementId {
1927    View(EntityId),
1928    Number(usize),
1929    Name(SharedString),
1930    FocusHandle(FocusId),
1931}
1932
1933impl From<EntityId> for ElementId {
1934    fn from(id: EntityId) -> Self {
1935        ElementId::View(id)
1936    }
1937}
1938
1939impl From<usize> for ElementId {
1940    fn from(id: usize) -> Self {
1941        ElementId::Number(id)
1942    }
1943}
1944
1945impl From<i32> for ElementId {
1946    fn from(id: i32) -> Self {
1947        Self::Number(id as usize)
1948    }
1949}
1950
1951impl From<SharedString> for ElementId {
1952    fn from(name: SharedString) -> Self {
1953        ElementId::Name(name)
1954    }
1955}
1956
1957impl From<&'static str> for ElementId {
1958    fn from(name: &'static str) -> Self {
1959        ElementId::Name(name.into())
1960    }
1961}
1962
1963impl<'a> From<&'a FocusHandle> for ElementId {
1964    fn from(handle: &'a FocusHandle) -> Self {
1965        ElementId::FocusHandle(handle.id)
1966    }
1967}