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    /// The line height associated with the current text style.
 510    pub fn line_height(&self) -> Pixels {
 511        let rem_size = self.rem_size();
 512        let text_style = self.text_style();
 513        text_style
 514            .line_height
 515            .to_pixels(text_style.font_size.into(), rem_size)
 516    }
 517
 518    /// Call to prevent the default action of an event. Currently only used to prevent
 519    /// parent elements from becoming focused on mouse down.
 520    pub fn prevent_default(&mut self) {
 521        self.window.default_prevented = true;
 522    }
 523
 524    /// Obtain whether default has been prevented for the event currently being dispatched.
 525    pub fn default_prevented(&self) -> bool {
 526        self.window.default_prevented
 527    }
 528
 529    /// Register a mouse event listener on the window for the current frame. The type of event
 530    /// is determined by the first parameter of the given listener. When the next frame is rendered
 531    /// the listener will be cleared.
 532    ///
 533    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
 534    /// a specific need to register a global listener.
 535    pub fn on_mouse_event<Event: 'static>(
 536        &mut self,
 537        handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
 538    ) {
 539        let order = self.window.z_index_stack.clone();
 540        self.window
 541            .mouse_listeners
 542            .entry(TypeId::of::<Event>())
 543            .or_default()
 544            .push((
 545                order,
 546                Box::new(move |event: &dyn Any, phase, cx| {
 547                    handler(event.downcast_ref().unwrap(), phase, cx)
 548                }),
 549            ))
 550    }
 551
 552    /// The position of the mouse relative to the window.
 553    pub fn mouse_position(&self) -> Point<Pixels> {
 554        self.window.mouse_position
 555    }
 556
 557    /// Called during painting to invoke the given closure in a new stacking context. The given
 558    /// z-index is interpreted relative to the previous call to `stack`.
 559    pub fn stack<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
 560        self.window.z_index_stack.push(z_index);
 561        let result = f(self);
 562        self.window.z_index_stack.pop();
 563        result
 564    }
 565
 566    /// Paint one or more drop shadows into the scene for the current frame at the current z-index.
 567    pub fn paint_shadows(
 568        &mut self,
 569        bounds: Bounds<Pixels>,
 570        corner_radii: Corners<Pixels>,
 571        shadows: &[BoxShadow],
 572    ) {
 573        let scale_factor = self.scale_factor();
 574        let content_mask = self.content_mask();
 575        let window = &mut *self.window;
 576        for shadow in shadows {
 577            let mut shadow_bounds = bounds;
 578            shadow_bounds.origin += shadow.offset;
 579            shadow_bounds.dilate(shadow.spread_radius);
 580            window.scene_builder.insert(
 581                &window.z_index_stack,
 582                Shadow {
 583                    order: 0,
 584                    bounds: shadow_bounds.scale(scale_factor),
 585                    content_mask: content_mask.scale(scale_factor),
 586                    corner_radii: corner_radii.scale(scale_factor),
 587                    color: shadow.color,
 588                    blur_radius: shadow.blur_radius.scale(scale_factor),
 589                },
 590            );
 591        }
 592    }
 593
 594    /// Paint one or more quads into the scene for the current frame at the current stacking context.
 595    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
 596    pub fn paint_quad(
 597        &mut self,
 598        bounds: Bounds<Pixels>,
 599        corner_radii: Corners<Pixels>,
 600        background: impl Into<Hsla>,
 601        border_widths: Edges<Pixels>,
 602        border_color: impl Into<Hsla>,
 603    ) {
 604        let scale_factor = self.scale_factor();
 605        let content_mask = self.content_mask();
 606
 607        let window = &mut *self.window;
 608        window.scene_builder.insert(
 609            &window.z_index_stack,
 610            Quad {
 611                order: 0,
 612                bounds: bounds.scale(scale_factor),
 613                content_mask: content_mask.scale(scale_factor),
 614                background: background.into(),
 615                border_color: border_color.into(),
 616                corner_radii: corner_radii.scale(scale_factor),
 617                border_widths: border_widths.scale(scale_factor),
 618            },
 619        );
 620    }
 621
 622    /// Paint the given `Path` into the scene for the current frame at the current z-index.
 623    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
 624        let scale_factor = self.scale_factor();
 625        let content_mask = self.content_mask();
 626        path.content_mask = content_mask;
 627        path.color = color.into();
 628        let window = &mut *self.window;
 629        window
 630            .scene_builder
 631            .insert(&window.z_index_stack, path.scale(scale_factor));
 632    }
 633
 634    /// Paint an underline into the scene for the current frame at the current z-index.
 635    pub fn paint_underline(
 636        &mut self,
 637        origin: Point<Pixels>,
 638        width: Pixels,
 639        style: &UnderlineStyle,
 640    ) -> Result<()> {
 641        let scale_factor = self.scale_factor();
 642        let height = if style.wavy {
 643            style.thickness * 3.
 644        } else {
 645            style.thickness
 646        };
 647        let bounds = Bounds {
 648            origin,
 649            size: size(width, height),
 650        };
 651        let content_mask = self.content_mask();
 652        let window = &mut *self.window;
 653        window.scene_builder.insert(
 654            &window.z_index_stack,
 655            Underline {
 656                order: 0,
 657                bounds: bounds.scale(scale_factor),
 658                content_mask: content_mask.scale(scale_factor),
 659                thickness: style.thickness.scale(scale_factor),
 660                color: style.color.unwrap_or_default(),
 661                wavy: style.wavy,
 662            },
 663        );
 664        Ok(())
 665    }
 666
 667    /// Paint a monochrome (non-emoji) glyph into the scene for the current frame at the current z-index.
 668    pub fn paint_glyph(
 669        &mut self,
 670        origin: Point<Pixels>,
 671        font_id: FontId,
 672        glyph_id: GlyphId,
 673        font_size: Pixels,
 674        color: Hsla,
 675    ) -> Result<()> {
 676        let scale_factor = self.scale_factor();
 677        let glyph_origin = origin.scale(scale_factor);
 678        let subpixel_variant = Point {
 679            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 680            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 681        };
 682        let params = RenderGlyphParams {
 683            font_id,
 684            glyph_id,
 685            font_size,
 686            subpixel_variant,
 687            scale_factor,
 688            is_emoji: false,
 689        };
 690
 691        let raster_bounds = self.text_system().raster_bounds(&params)?;
 692        if !raster_bounds.is_zero() {
 693            let tile =
 694                self.window
 695                    .sprite_atlas
 696                    .get_or_insert_with(&params.clone().into(), &mut || {
 697                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 698                        Ok((size, Cow::Owned(bytes)))
 699                    })?;
 700            let bounds = Bounds {
 701                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 702                size: tile.bounds.size.map(Into::into),
 703            };
 704            let content_mask = self.content_mask().scale(scale_factor);
 705            let window = &mut *self.window;
 706            window.scene_builder.insert(
 707                &window.z_index_stack,
 708                MonochromeSprite {
 709                    order: 0,
 710                    bounds,
 711                    content_mask,
 712                    color,
 713                    tile,
 714                },
 715            );
 716        }
 717        Ok(())
 718    }
 719
 720    /// Paint an emoji glyph into the scene for the current frame at the current z-index.
 721    pub fn paint_emoji(
 722        &mut self,
 723        origin: Point<Pixels>,
 724        font_id: FontId,
 725        glyph_id: GlyphId,
 726        font_size: Pixels,
 727    ) -> Result<()> {
 728        let scale_factor = self.scale_factor();
 729        let glyph_origin = origin.scale(scale_factor);
 730        let params = RenderGlyphParams {
 731            font_id,
 732            glyph_id,
 733            font_size,
 734            // We don't render emojis with subpixel variants.
 735            subpixel_variant: Default::default(),
 736            scale_factor,
 737            is_emoji: true,
 738        };
 739
 740        let raster_bounds = self.text_system().raster_bounds(&params)?;
 741        if !raster_bounds.is_zero() {
 742            let tile =
 743                self.window
 744                    .sprite_atlas
 745                    .get_or_insert_with(&params.clone().into(), &mut || {
 746                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 747                        Ok((size, Cow::Owned(bytes)))
 748                    })?;
 749            let bounds = Bounds {
 750                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 751                size: tile.bounds.size.map(Into::into),
 752            };
 753            let content_mask = self.content_mask().scale(scale_factor);
 754            let window = &mut *self.window;
 755
 756            window.scene_builder.insert(
 757                &window.z_index_stack,
 758                PolychromeSprite {
 759                    order: 0,
 760                    bounds,
 761                    corner_radii: Default::default(),
 762                    content_mask,
 763                    tile,
 764                    grayscale: false,
 765                },
 766            );
 767        }
 768        Ok(())
 769    }
 770
 771    /// Paint a monochrome SVG into the scene for the current frame at the current stacking context.
 772    pub fn paint_svg(
 773        &mut self,
 774        bounds: Bounds<Pixels>,
 775        path: SharedString,
 776        color: Hsla,
 777    ) -> Result<()> {
 778        let scale_factor = self.scale_factor();
 779        let bounds = bounds.scale(scale_factor);
 780        // Render the SVG at twice the size to get a higher quality result.
 781        let params = RenderSvgParams {
 782            path,
 783            size: bounds
 784                .size
 785                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
 786        };
 787
 788        let tile =
 789            self.window
 790                .sprite_atlas
 791                .get_or_insert_with(&params.clone().into(), &mut || {
 792                    let bytes = self.svg_renderer.render(&params)?;
 793                    Ok((params.size, Cow::Owned(bytes)))
 794                })?;
 795        let content_mask = self.content_mask().scale(scale_factor);
 796
 797        let window = &mut *self.window;
 798        window.scene_builder.insert(
 799            &window.z_index_stack,
 800            MonochromeSprite {
 801                order: 0,
 802                bounds,
 803                content_mask,
 804                color,
 805                tile,
 806            },
 807        );
 808
 809        Ok(())
 810    }
 811
 812    /// Paint an image into the scene for the current frame at the current z-index.
 813    pub fn paint_image(
 814        &mut self,
 815        bounds: Bounds<Pixels>,
 816        corner_radii: Corners<Pixels>,
 817        data: Arc<ImageData>,
 818        grayscale: bool,
 819    ) -> Result<()> {
 820        let scale_factor = self.scale_factor();
 821        let bounds = bounds.scale(scale_factor);
 822        let params = RenderImageParams { image_id: data.id };
 823
 824        let tile = self
 825            .window
 826            .sprite_atlas
 827            .get_or_insert_with(&params.clone().into(), &mut || {
 828                Ok((data.size(), Cow::Borrowed(data.as_bytes())))
 829            })?;
 830        let content_mask = self.content_mask().scale(scale_factor);
 831        let corner_radii = corner_radii.scale(scale_factor);
 832
 833        let window = &mut *self.window;
 834        window.scene_builder.insert(
 835            &window.z_index_stack,
 836            PolychromeSprite {
 837                order: 0,
 838                bounds,
 839                content_mask,
 840                corner_radii,
 841                tile,
 842                grayscale,
 843            },
 844        );
 845        Ok(())
 846    }
 847
 848    /// Draw pixels to the display for this window based on the contents of its scene.
 849    pub(crate) fn draw(&mut self) {
 850        let root_view = self.window.root_view.take().unwrap();
 851
 852        self.start_frame();
 853
 854        self.stack(0, |cx| {
 855            let available_space = cx.window.content_size.map(Into::into);
 856            root_view.draw(available_space, cx);
 857        });
 858
 859        if let Some(active_drag) = self.app.active_drag.take() {
 860            self.stack(1, |cx| {
 861                let offset = cx.mouse_position() - active_drag.cursor_offset;
 862                cx.with_element_offset(Some(offset), |cx| {
 863                    let available_space =
 864                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
 865                    active_drag.view.draw(available_space, cx);
 866                    cx.active_drag = Some(active_drag);
 867                });
 868            });
 869        }
 870
 871        self.window.root_view = Some(root_view);
 872        let scene = self.window.scene_builder.build();
 873
 874        self.window.platform_window.draw(scene);
 875        self.window.dirty = false;
 876    }
 877
 878    fn start_frame(&mut self) {
 879        self.text_system().start_frame();
 880
 881        let window = &mut *self.window;
 882
 883        // Move the current frame element states to the previous frame.
 884        // The new empty element states map will be populated for any element states we
 885        // reference during the upcoming frame.
 886        mem::swap(
 887            &mut window.element_states,
 888            &mut window.prev_frame_element_states,
 889        );
 890        window.element_states.clear();
 891
 892        // Make the current key matchers the previous, and then clear the current.
 893        // An empty key matcher map will be created for every identified element in the
 894        // upcoming frame.
 895        mem::swap(
 896            &mut window.key_matchers,
 897            &mut window.prev_frame_key_matchers,
 898        );
 899        window.key_matchers.clear();
 900
 901        // Clear mouse event listeners, because elements add new element listeners
 902        // when the upcoming frame is painted.
 903        window.mouse_listeners.values_mut().for_each(Vec::clear);
 904
 905        // Clear focus state, because we determine what is focused when the new elements
 906        // in the upcoming frame are initialized.
 907        window.focus_listeners.clear();
 908        window.key_dispatch_stack.clear();
 909        window.focus_parents_by_child.clear();
 910        window.freeze_key_dispatch_stack = false;
 911    }
 912
 913    /// Dispatch a mouse or keyboard event on the window.
 914    fn dispatch_event(&mut self, event: InputEvent) -> bool {
 915        let event = match event {
 916            // Track the mouse position with our own state, since accessing the platform
 917            // API for the mouse position can only occur on the main thread.
 918            InputEvent::MouseMove(mouse_move) => {
 919                self.window.mouse_position = mouse_move.position;
 920                InputEvent::MouseMove(mouse_move)
 921            }
 922            // Translate dragging and dropping of external files from the operating system
 923            // to internal drag and drop events.
 924            InputEvent::FileDrop(file_drop) => match file_drop {
 925                FileDropEvent::Entered { position, files } => {
 926                    self.window.mouse_position = position;
 927                    if self.active_drag.is_none() {
 928                        self.active_drag = Some(AnyDrag {
 929                            view: self.build_view(|_| files).into(),
 930                            cursor_offset: position,
 931                        });
 932                    }
 933                    InputEvent::MouseDown(MouseDownEvent {
 934                        position,
 935                        button: MouseButton::Left,
 936                        click_count: 1,
 937                        modifiers: Modifiers::default(),
 938                    })
 939                }
 940                FileDropEvent::Pending { position } => {
 941                    self.window.mouse_position = position;
 942                    InputEvent::MouseMove(MouseMoveEvent {
 943                        position,
 944                        pressed_button: Some(MouseButton::Left),
 945                        modifiers: Modifiers::default(),
 946                    })
 947                }
 948                FileDropEvent::Submit { position } => {
 949                    self.window.mouse_position = position;
 950                    InputEvent::MouseUp(MouseUpEvent {
 951                        button: MouseButton::Left,
 952                        position,
 953                        modifiers: Modifiers::default(),
 954                        click_count: 1,
 955                    })
 956                }
 957                FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
 958                    button: MouseButton::Left,
 959                    position: Point::default(),
 960                    modifiers: Modifiers::default(),
 961                    click_count: 1,
 962                }),
 963            },
 964            _ => event,
 965        };
 966
 967        if let Some(any_mouse_event) = event.mouse_event() {
 968            // Handlers may set this to false by calling `stop_propagation`
 969            self.app.propagate_event = true;
 970            self.window.default_prevented = false;
 971
 972            if let Some(mut handlers) = self
 973                .window
 974                .mouse_listeners
 975                .remove(&any_mouse_event.type_id())
 976            {
 977                // Because handlers may add other handlers, we sort every time.
 978                handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
 979
 980                // Capture phase, events bubble from back to front. Handlers for this phase are used for
 981                // special purposes, such as detecting events outside of a given Bounds.
 982                for (_, handler) in &handlers {
 983                    handler(any_mouse_event, DispatchPhase::Capture, self);
 984                    if !self.app.propagate_event {
 985                        break;
 986                    }
 987                }
 988
 989                // Bubble phase, where most normal handlers do their work.
 990                if self.app.propagate_event {
 991                    for (_, handler) in handlers.iter().rev() {
 992                        handler(any_mouse_event, DispatchPhase::Bubble, self);
 993                        if !self.app.propagate_event {
 994                            break;
 995                        }
 996                    }
 997                }
 998
 999                if self.app.propagate_event
1000                    && any_mouse_event.downcast_ref::<MouseUpEvent>().is_some()
1001                {
1002                    self.active_drag = None;
1003                }
1004
1005                // Just in case any handlers added new handlers, which is weird, but possible.
1006                handlers.extend(
1007                    self.window
1008                        .mouse_listeners
1009                        .get_mut(&any_mouse_event.type_id())
1010                        .into_iter()
1011                        .flat_map(|handlers| handlers.drain(..)),
1012                );
1013                self.window
1014                    .mouse_listeners
1015                    .insert(any_mouse_event.type_id(), handlers);
1016            }
1017        } else if let Some(any_key_event) = event.keyboard_event() {
1018            let key_dispatch_stack = mem::take(&mut self.window.key_dispatch_stack);
1019            let key_event_type = any_key_event.type_id();
1020            let mut context_stack = SmallVec::<[&DispatchContext; 16]>::new();
1021
1022            for (ix, frame) in key_dispatch_stack.iter().enumerate() {
1023                match frame {
1024                    KeyDispatchStackFrame::Listener {
1025                        event_type,
1026                        listener,
1027                    } => {
1028                        if key_event_type == *event_type {
1029                            if let Some(action) = listener(
1030                                any_key_event,
1031                                &context_stack,
1032                                DispatchPhase::Capture,
1033                                self,
1034                            ) {
1035                                self.dispatch_action(action, &key_dispatch_stack[..ix]);
1036                            }
1037                            if !self.app.propagate_event {
1038                                break;
1039                            }
1040                        }
1041                    }
1042                    KeyDispatchStackFrame::Context(context) => {
1043                        context_stack.push(&context);
1044                    }
1045                }
1046            }
1047
1048            if self.app.propagate_event {
1049                for (ix, frame) in key_dispatch_stack.iter().enumerate().rev() {
1050                    match frame {
1051                        KeyDispatchStackFrame::Listener {
1052                            event_type,
1053                            listener,
1054                        } => {
1055                            if key_event_type == *event_type {
1056                                if let Some(action) = listener(
1057                                    any_key_event,
1058                                    &context_stack,
1059                                    DispatchPhase::Bubble,
1060                                    self,
1061                                ) {
1062                                    self.dispatch_action(action, &key_dispatch_stack[..ix]);
1063                                }
1064
1065                                if !self.app.propagate_event {
1066                                    break;
1067                                }
1068                            }
1069                        }
1070                        KeyDispatchStackFrame::Context(_) => {
1071                            context_stack.pop();
1072                        }
1073                    }
1074                }
1075            }
1076
1077            drop(context_stack);
1078            self.window.key_dispatch_stack = key_dispatch_stack;
1079        }
1080
1081        true
1082    }
1083
1084    /// Attempt to map a keystroke to an action based on the keymap.
1085    pub fn match_keystroke(
1086        &mut self,
1087        element_id: &GlobalElementId,
1088        keystroke: &Keystroke,
1089        context_stack: &[&DispatchContext],
1090    ) -> KeyMatch {
1091        let key_match = self
1092            .window
1093            .key_matchers
1094            .get_mut(element_id)
1095            .unwrap()
1096            .match_keystroke(keystroke, context_stack);
1097
1098        if key_match.is_some() {
1099            for matcher in self.window.key_matchers.values_mut() {
1100                matcher.clear_pending();
1101            }
1102        }
1103
1104        key_match
1105    }
1106
1107    /// Register the given handler to be invoked whenever the global of the given type
1108    /// is updated.
1109    pub fn observe_global<G: 'static>(
1110        &mut self,
1111        f: impl Fn(&mut WindowContext<'_, '_>) + Send + 'static,
1112    ) -> Subscription {
1113        let window_id = self.window.handle.id;
1114        self.global_observers.insert(
1115            TypeId::of::<G>(),
1116            Box::new(move |cx| cx.update_window(window_id, |cx| f(cx)).is_ok()),
1117        )
1118    }
1119
1120    fn dispatch_action(
1121        &mut self,
1122        action: Box<dyn Action>,
1123        dispatch_stack: &[KeyDispatchStackFrame],
1124    ) {
1125        let action_type = action.as_any().type_id();
1126
1127        if let Some(mut global_listeners) = self.app.global_action_listeners.remove(&action_type) {
1128            for listener in &global_listeners {
1129                listener(action.as_ref(), DispatchPhase::Capture, self);
1130                if !self.app.propagate_event {
1131                    break;
1132                }
1133            }
1134            global_listeners.extend(
1135                self.global_action_listeners
1136                    .remove(&action_type)
1137                    .unwrap_or_default(),
1138            );
1139            self.global_action_listeners
1140                .insert(action_type, global_listeners);
1141        }
1142
1143        if self.app.propagate_event {
1144            for stack_frame in dispatch_stack {
1145                if let KeyDispatchStackFrame::Listener {
1146                    event_type,
1147                    listener,
1148                } = stack_frame
1149                {
1150                    if action_type == *event_type {
1151                        listener(action.as_any(), &[], DispatchPhase::Capture, self);
1152                        if !self.app.propagate_event {
1153                            break;
1154                        }
1155                    }
1156                }
1157            }
1158        }
1159
1160        if self.app.propagate_event {
1161            for stack_frame in dispatch_stack.iter().rev() {
1162                if let KeyDispatchStackFrame::Listener {
1163                    event_type,
1164                    listener,
1165                } = stack_frame
1166                {
1167                    if action_type == *event_type {
1168                        listener(action.as_any(), &[], DispatchPhase::Bubble, self);
1169                        if !self.app.propagate_event {
1170                            break;
1171                        }
1172                    }
1173                }
1174            }
1175        }
1176
1177        if self.app.propagate_event {
1178            if let Some(mut global_listeners) =
1179                self.app.global_action_listeners.remove(&action_type)
1180            {
1181                for listener in global_listeners.iter().rev() {
1182                    listener(action.as_ref(), DispatchPhase::Bubble, self);
1183                    if !self.app.propagate_event {
1184                        break;
1185                    }
1186                }
1187                global_listeners.extend(
1188                    self.global_action_listeners
1189                        .remove(&action_type)
1190                        .unwrap_or_default(),
1191                );
1192                self.global_action_listeners
1193                    .insert(action_type, global_listeners);
1194            }
1195        }
1196    }
1197}
1198
1199impl Context for WindowContext<'_, '_> {
1200    type ModelContext<'a, T> = ModelContext<'a, T>;
1201    type Result<T> = T;
1202
1203    fn build_model<T>(
1204        &mut self,
1205        build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
1206    ) -> Model<T>
1207    where
1208        T: 'static,
1209    {
1210        let slot = self.app.entities.reserve();
1211        let model = build_model(&mut ModelContext::mutable(&mut *self.app, slot.downgrade()));
1212        self.entities.insert(slot, model)
1213    }
1214
1215    fn update_model<T: 'static, R>(
1216        &mut self,
1217        model: &Model<T>,
1218        update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
1219    ) -> R {
1220        let mut entity = self.entities.lease(model);
1221        let result = update(
1222            &mut *entity,
1223            &mut ModelContext::mutable(&mut *self.app, model.downgrade()),
1224        );
1225        self.entities.end_lease(entity);
1226        result
1227    }
1228}
1229
1230impl VisualContext for WindowContext<'_, '_> {
1231    type ViewContext<'a, 'w, V> = ViewContext<'a, 'w, V>;
1232
1233    fn build_view<V>(
1234        &mut self,
1235        build_view_state: impl FnOnce(&mut Self::ViewContext<'_, '_, V>) -> V,
1236    ) -> Self::Result<View<V>>
1237    where
1238        V: 'static,
1239    {
1240        let slot = self.app.entities.reserve();
1241        let view = View {
1242            model: slot.clone(),
1243        };
1244        let mut cx = ViewContext::mutable(&mut *self.app, &mut *self.window, view.downgrade());
1245        let entity = build_view_state(&mut cx);
1246        self.entities.insert(slot, entity);
1247        view
1248    }
1249
1250    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1251    fn update_view<T: 'static, R>(
1252        &mut self,
1253        view: &View<T>,
1254        update: impl FnOnce(&mut T, &mut Self::ViewContext<'_, '_, T>) -> R,
1255    ) -> Self::Result<R> {
1256        let mut lease = self.app.entities.lease(&view.model);
1257        let mut cx = ViewContext::mutable(&mut *self.app, &mut *self.window, view.downgrade());
1258        let result = update(&mut *lease, &mut cx);
1259        cx.app.entities.end_lease(lease);
1260        result
1261    }
1262}
1263
1264impl<'a, 'w> std::ops::Deref for WindowContext<'a, 'w> {
1265    type Target = AppContext;
1266
1267    fn deref(&self) -> &Self::Target {
1268        &self.app
1269    }
1270}
1271
1272impl<'a, 'w> std::ops::DerefMut for WindowContext<'a, 'w> {
1273    fn deref_mut(&mut self) -> &mut Self::Target {
1274        &mut self.app
1275    }
1276}
1277
1278impl<'a, 'w> Borrow<AppContext> for WindowContext<'a, 'w> {
1279    fn borrow(&self) -> &AppContext {
1280        &self.app
1281    }
1282}
1283
1284impl<'a, 'w> BorrowMut<AppContext> for WindowContext<'a, 'w> {
1285    fn borrow_mut(&mut self) -> &mut AppContext {
1286        &mut self.app
1287    }
1288}
1289
1290pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1291    fn app_mut(&mut self) -> &mut AppContext {
1292        self.borrow_mut()
1293    }
1294
1295    fn window(&self) -> &Window {
1296        self.borrow()
1297    }
1298
1299    fn window_mut(&mut self) -> &mut Window {
1300        self.borrow_mut()
1301    }
1302
1303    /// Pushes the given element id onto the global stack and invokes the given closure
1304    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1305    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1306    /// used to associate state with identified elements across separate frames.
1307    fn with_element_id<R>(
1308        &mut self,
1309        id: impl Into<ElementId>,
1310        f: impl FnOnce(GlobalElementId, &mut Self) -> R,
1311    ) -> R {
1312        let keymap = self.app_mut().keymap.clone();
1313        let window = self.window_mut();
1314        window.element_id_stack.push(id.into());
1315        let global_id = window.element_id_stack.clone();
1316
1317        if window.key_matchers.get(&global_id).is_none() {
1318            window.key_matchers.insert(
1319                global_id.clone(),
1320                window
1321                    .prev_frame_key_matchers
1322                    .remove(&global_id)
1323                    .unwrap_or_else(|| KeyMatcher::new(keymap)),
1324            );
1325        }
1326
1327        let result = f(global_id, self);
1328        let window: &mut Window = self.borrow_mut();
1329        window.element_id_stack.pop();
1330        result
1331    }
1332
1333    /// Invoke the given function with the given content mask after intersecting it
1334    /// with the current mask.
1335    fn with_content_mask<R>(
1336        &mut self,
1337        mask: ContentMask<Pixels>,
1338        f: impl FnOnce(&mut Self) -> R,
1339    ) -> R {
1340        let mask = mask.intersect(&self.content_mask());
1341        self.window_mut().content_mask_stack.push(mask);
1342        let result = f(self);
1343        self.window_mut().content_mask_stack.pop();
1344        result
1345    }
1346
1347    /// Update the global element offset based on the given offset. This is used to implement
1348    /// scrolling and position drag handles.
1349    fn with_element_offset<R>(
1350        &mut self,
1351        offset: Option<Point<Pixels>>,
1352        f: impl FnOnce(&mut Self) -> R,
1353    ) -> R {
1354        let Some(offset) = offset else {
1355            return f(self);
1356        };
1357
1358        let offset = self.element_offset() + offset;
1359        self.window_mut().element_offset_stack.push(offset);
1360        let result = f(self);
1361        self.window_mut().element_offset_stack.pop();
1362        result
1363    }
1364
1365    /// Obtain the current element offset.
1366    fn element_offset(&self) -> Point<Pixels> {
1367        self.window()
1368            .element_offset_stack
1369            .last()
1370            .copied()
1371            .unwrap_or_default()
1372    }
1373
1374    /// Update or intialize state for an element with the given id that lives across multiple
1375    /// frames. If an element with this id existed in the previous frame, its state will be passed
1376    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1377    /// when drawing the next frame.
1378    fn with_element_state<S, R>(
1379        &mut self,
1380        id: ElementId,
1381        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1382    ) -> R
1383    where
1384        S: 'static,
1385    {
1386        self.with_element_id(id, |global_id, cx| {
1387            if let Some(any) = cx
1388                .window_mut()
1389                .element_states
1390                .remove(&global_id)
1391                .or_else(|| cx.window_mut().prev_frame_element_states.remove(&global_id))
1392            {
1393                // Using the extra inner option to avoid needing to reallocate a new box.
1394                let mut state_box = any
1395                    .downcast::<Option<S>>()
1396                    .expect("invalid element state type for id");
1397                let state = state_box
1398                    .take()
1399                    .expect("element state is already on the stack");
1400                let (result, state) = f(Some(state), cx);
1401                state_box.replace(state);
1402                cx.window_mut().element_states.insert(global_id, state_box);
1403                result
1404            } else {
1405                let (result, state) = f(None, cx);
1406                cx.window_mut()
1407                    .element_states
1408                    .insert(global_id, Box::new(Some(state)));
1409                result
1410            }
1411        })
1412    }
1413
1414    /// Like `with_element_state`, but for situations where the element_id is optional. If the
1415    /// id is `None`, no state will be retrieved or stored.
1416    fn with_optional_element_state<S, R>(
1417        &mut self,
1418        element_id: Option<ElementId>,
1419        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1420    ) -> R
1421    where
1422        S: 'static,
1423    {
1424        if let Some(element_id) = element_id {
1425            self.with_element_state(element_id, f)
1426        } else {
1427            f(None, self).0
1428        }
1429    }
1430
1431    /// Obtain the current content mask.
1432    fn content_mask(&self) -> ContentMask<Pixels> {
1433        self.window()
1434            .content_mask_stack
1435            .last()
1436            .cloned()
1437            .unwrap_or_else(|| ContentMask {
1438                bounds: Bounds {
1439                    origin: Point::default(),
1440                    size: self.window().content_size,
1441                },
1442            })
1443    }
1444
1445    /// The size of an em for the base font of the application. Adjusting this value allows the
1446    /// UI to scale, just like zooming a web page.
1447    fn rem_size(&self) -> Pixels {
1448        self.window().rem_size
1449    }
1450}
1451
1452impl Borrow<Window> for WindowContext<'_, '_> {
1453    fn borrow(&self) -> &Window {
1454        &self.window
1455    }
1456}
1457
1458impl BorrowMut<Window> for WindowContext<'_, '_> {
1459    fn borrow_mut(&mut self) -> &mut Window {
1460        &mut self.window
1461    }
1462}
1463
1464impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1465
1466pub struct ViewContext<'a, 'w, V> {
1467    window_cx: WindowContext<'a, 'w>,
1468    view: WeakView<V>,
1469}
1470
1471impl<V> Borrow<AppContext> for ViewContext<'_, '_, V> {
1472    fn borrow(&self) -> &AppContext {
1473        &*self.window_cx.app
1474    }
1475}
1476
1477impl<V> BorrowMut<AppContext> for ViewContext<'_, '_, V> {
1478    fn borrow_mut(&mut self) -> &mut AppContext {
1479        &mut *self.window_cx.app
1480    }
1481}
1482
1483impl<V> Borrow<Window> for ViewContext<'_, '_, V> {
1484    fn borrow(&self) -> &Window {
1485        &*self.window_cx.window
1486    }
1487}
1488
1489impl<V> BorrowMut<Window> for ViewContext<'_, '_, V> {
1490    fn borrow_mut(&mut self) -> &mut Window {
1491        &mut *self.window_cx.window
1492    }
1493}
1494
1495impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
1496    pub(crate) fn mutable(
1497        app: &'a mut AppContext,
1498        window: &'w mut Window,
1499        view: WeakView<V>,
1500    ) -> Self {
1501        Self {
1502            window_cx: WindowContext::mutable(app, window),
1503            view,
1504        }
1505    }
1506
1507    pub fn view(&self) -> WeakView<V> {
1508        self.view.clone()
1509    }
1510
1511    pub fn model(&self) -> WeakModel<V> {
1512        self.view.model.clone()
1513    }
1514
1515    pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1516        self.window.z_index_stack.push(order);
1517        let result = f(self);
1518        self.window.z_index_stack.pop();
1519        result
1520    }
1521
1522    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + Send + 'static)
1523    where
1524        V: Any + Send,
1525    {
1526        let view = self.view().upgrade().unwrap();
1527        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1528    }
1529
1530    pub fn observe<V2, E>(
1531        &mut self,
1532        entity: &E,
1533        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, '_, V>) + Send + 'static,
1534    ) -> Subscription
1535    where
1536        V2: 'static,
1537        V: Any + Send,
1538        E: Entity<V2>,
1539    {
1540        let view = self.view();
1541        let entity_id = entity.entity_id();
1542        let entity = entity.downgrade();
1543        let window_handle = self.window.handle;
1544        self.app.observers.insert(
1545            entity_id,
1546            Box::new(move |cx| {
1547                cx.update_window(window_handle.id, |cx| {
1548                    if let Some(handle) = E::upgrade_from(&entity) {
1549                        view.update(cx, |this, cx| on_notify(this, handle, cx))
1550                            .is_ok()
1551                    } else {
1552                        false
1553                    }
1554                })
1555                .unwrap_or(false)
1556            }),
1557        )
1558    }
1559
1560    pub fn subscribe<V2, E>(
1561        &mut self,
1562        entity: &E,
1563        mut on_event: impl FnMut(&mut V, E, &V2::Event, &mut ViewContext<'_, '_, V>) + Send + 'static,
1564    ) -> Subscription
1565    where
1566        V2: EventEmitter,
1567        E: Entity<V2>,
1568    {
1569        let view = self.view();
1570        let entity_id = entity.entity_id();
1571        let handle = entity.downgrade();
1572        let window_handle = self.window.handle;
1573        self.app.event_listeners.insert(
1574            entity_id,
1575            Box::new(move |event, cx| {
1576                cx.update_window(window_handle.id, |cx| {
1577                    if let Some(handle) = E::upgrade_from(&handle) {
1578                        let event = event.downcast_ref().expect("invalid event type");
1579                        view.update(cx, |this, cx| on_event(this, handle, event, cx))
1580                            .is_ok()
1581                    } else {
1582                        false
1583                    }
1584                })
1585                .unwrap_or(false)
1586            }),
1587        )
1588    }
1589
1590    pub fn on_release(
1591        &mut self,
1592        mut on_release: impl FnMut(&mut V, &mut WindowContext) + Send + 'static,
1593    ) -> Subscription {
1594        let window_handle = self.window.handle;
1595        self.app.release_listeners.insert(
1596            self.view.model.entity_id,
1597            Box::new(move |this, cx| {
1598                let this = this.downcast_mut().expect("invalid entity type");
1599                // todo!("are we okay with silently swallowing the error?")
1600                let _ = cx.update_window(window_handle.id, |cx| on_release(this, cx));
1601            }),
1602        )
1603    }
1604
1605    pub fn observe_release<V2, E>(
1606        &mut self,
1607        entity: &E,
1608        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, '_, V>) + Send + 'static,
1609    ) -> Subscription
1610    where
1611        V: Any + Send,
1612        V2: 'static,
1613        E: Entity<V2>,
1614    {
1615        let view = self.view();
1616        let entity_id = entity.entity_id();
1617        let window_handle = self.window.handle;
1618        self.app.release_listeners.insert(
1619            entity_id,
1620            Box::new(move |entity, cx| {
1621                let entity = entity.downcast_mut().expect("invalid entity type");
1622                let _ = cx.update_window(window_handle.id, |cx| {
1623                    view.update(cx, |this, cx| on_release(this, entity, cx))
1624                });
1625            }),
1626        )
1627    }
1628
1629    pub fn notify(&mut self) {
1630        self.window_cx.notify();
1631        self.window_cx.app.push_effect(Effect::Notify {
1632            emitter: self.view.model.entity_id,
1633        });
1634    }
1635
1636    pub fn on_focus_changed(
1637        &mut self,
1638        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,
1639    ) {
1640        let handle = self.view();
1641        self.window.focus_listeners.push(Box::new(move |event, cx| {
1642            handle
1643                .update(cx, |view, cx| listener(view, event, cx))
1644                .log_err();
1645        }));
1646    }
1647
1648    pub fn with_key_listeners<R>(
1649        &mut self,
1650        key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
1651        f: impl FnOnce(&mut Self) -> R,
1652    ) -> R {
1653        let old_stack_len = self.window.key_dispatch_stack.len();
1654        if !self.window.freeze_key_dispatch_stack {
1655            for (event_type, listener) in key_listeners {
1656                let handle = self.view();
1657                let listener = Box::new(
1658                    move |event: &dyn Any,
1659                          context_stack: &[&DispatchContext],
1660                          phase: DispatchPhase,
1661                          cx: &mut WindowContext<'_, '_>| {
1662                        handle
1663                            .update(cx, |view, cx| {
1664                                listener(view, event, context_stack, phase, cx)
1665                            })
1666                            .log_err()
1667                            .flatten()
1668                    },
1669                );
1670                self.window
1671                    .key_dispatch_stack
1672                    .push(KeyDispatchStackFrame::Listener {
1673                        event_type,
1674                        listener,
1675                    });
1676            }
1677        }
1678
1679        let result = f(self);
1680
1681        if !self.window.freeze_key_dispatch_stack {
1682            self.window.key_dispatch_stack.truncate(old_stack_len);
1683        }
1684
1685        result
1686    }
1687
1688    pub fn with_key_dispatch_context<R>(
1689        &mut self,
1690        context: DispatchContext,
1691        f: impl FnOnce(&mut Self) -> R,
1692    ) -> R {
1693        if context.is_empty() {
1694            return f(self);
1695        }
1696
1697        if !self.window.freeze_key_dispatch_stack {
1698            self.window
1699                .key_dispatch_stack
1700                .push(KeyDispatchStackFrame::Context(context));
1701        }
1702
1703        let result = f(self);
1704
1705        if !self.window.freeze_key_dispatch_stack {
1706            self.window.key_dispatch_stack.pop();
1707        }
1708
1709        result
1710    }
1711
1712    pub fn with_focus<R>(
1713        &mut self,
1714        focus_handle: FocusHandle,
1715        f: impl FnOnce(&mut Self) -> R,
1716    ) -> R {
1717        if let Some(parent_focus_id) = self.window.focus_stack.last().copied() {
1718            self.window
1719                .focus_parents_by_child
1720                .insert(focus_handle.id, parent_focus_id);
1721        }
1722        self.window.focus_stack.push(focus_handle.id);
1723
1724        if Some(focus_handle.id) == self.window.focus {
1725            self.window.freeze_key_dispatch_stack = true;
1726        }
1727
1728        let result = f(self);
1729
1730        self.window.focus_stack.pop();
1731        result
1732    }
1733
1734    pub fn spawn<Fut, R>(
1735        &mut self,
1736        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
1737    ) -> Task<R>
1738    where
1739        R: 'static,
1740        Fut: Future<Output = R> + 'static,
1741    {
1742        let view = self.view();
1743        self.window_cx.spawn(move |_, cx| {
1744            let result = f(view, cx);
1745            async move { result.await }
1746        })
1747    }
1748
1749    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
1750    where
1751        G: 'static + Send,
1752    {
1753        let mut global = self.app.lease_global::<G>();
1754        let result = f(&mut global, self);
1755        self.app.end_global_lease(global);
1756        result
1757    }
1758
1759    pub fn observe_global<G: 'static>(
1760        &mut self,
1761        f: impl Fn(&mut V, &mut ViewContext<'_, '_, V>) + Send + 'static,
1762    ) -> Subscription {
1763        let window_id = self.window.handle.id;
1764        let handle = self.view();
1765        self.global_observers.insert(
1766            TypeId::of::<G>(),
1767            Box::new(move |cx| {
1768                cx.update_window(window_id, |cx| {
1769                    handle.update(cx, |view, cx| f(view, cx)).is_ok()
1770                })
1771                .unwrap_or(false)
1772            }),
1773        )
1774    }
1775
1776    pub fn on_mouse_event<Event: 'static>(
1777        &mut self,
1778        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
1779    ) {
1780        let handle = self.view().upgrade().unwrap();
1781        self.window_cx.on_mouse_event(move |event, phase, cx| {
1782            handle.update(cx, |view, cx| {
1783                handler(view, event, phase, cx);
1784            })
1785        });
1786    }
1787}
1788
1789impl<'a, 'w, V> ViewContext<'a, 'w, V>
1790where
1791    V: EventEmitter,
1792    V::Event: Any + Send,
1793{
1794    pub fn emit(&mut self, event: V::Event) {
1795        let emitter = self.view.model.entity_id;
1796        self.app.push_effect(Effect::Emit {
1797            emitter,
1798            event: Box::new(event),
1799        });
1800    }
1801}
1802
1803impl<'a, 'w, V> Context for ViewContext<'a, 'w, V> {
1804    type ModelContext<'b, U> = ModelContext<'b, U>;
1805    type Result<U> = U;
1806
1807    fn build_model<T: 'static>(
1808        &mut self,
1809        build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
1810    ) -> Model<T> {
1811        self.window_cx.build_model(build_model)
1812    }
1813
1814    fn update_model<T: 'static, R>(
1815        &mut self,
1816        model: &Model<T>,
1817        update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
1818    ) -> R {
1819        self.window_cx.update_model(model, update)
1820    }
1821}
1822
1823impl<V: 'static> VisualContext for ViewContext<'_, '_, V> {
1824    type ViewContext<'a, 'w, V2> = ViewContext<'a, 'w, V2>;
1825
1826    fn build_view<W: 'static>(
1827        &mut self,
1828        build_view: impl FnOnce(&mut Self::ViewContext<'_, '_, W>) -> W,
1829    ) -> Self::Result<View<W>> {
1830        self.window_cx.build_view(build_view)
1831    }
1832
1833    fn update_view<V2: 'static, R>(
1834        &mut self,
1835        view: &View<V2>,
1836        update: impl FnOnce(&mut V2, &mut Self::ViewContext<'_, '_, V2>) -> R,
1837    ) -> Self::Result<R> {
1838        self.window_cx.update_view(view, update)
1839    }
1840}
1841
1842impl<'a, 'w, V> std::ops::Deref for ViewContext<'a, 'w, V> {
1843    type Target = WindowContext<'a, 'w>;
1844
1845    fn deref(&self) -> &Self::Target {
1846        &self.window_cx
1847    }
1848}
1849
1850impl<'a, 'w, V> std::ops::DerefMut for ViewContext<'a, 'w, V> {
1851    fn deref_mut(&mut self) -> &mut Self::Target {
1852        &mut self.window_cx
1853    }
1854}
1855
1856// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
1857slotmap::new_key_type! { pub struct WindowId; }
1858
1859impl WindowId {
1860    pub fn as_u64(&self) -> u64 {
1861        self.0.as_ffi()
1862    }
1863}
1864
1865#[derive(PartialEq, Eq)]
1866pub struct WindowHandle<V> {
1867    id: WindowId,
1868    state_type: PhantomData<V>,
1869}
1870
1871impl<S> Copy for WindowHandle<S> {}
1872
1873impl<S> Clone for WindowHandle<S> {
1874    fn clone(&self) -> Self {
1875        WindowHandle {
1876            id: self.id,
1877            state_type: PhantomData,
1878        }
1879    }
1880}
1881
1882impl<S> WindowHandle<S> {
1883    pub fn new(id: WindowId) -> Self {
1884        WindowHandle {
1885            id,
1886            state_type: PhantomData,
1887        }
1888    }
1889}
1890
1891impl<S: 'static> Into<AnyWindowHandle> for WindowHandle<S> {
1892    fn into(self) -> AnyWindowHandle {
1893        AnyWindowHandle {
1894            id: self.id,
1895            state_type: TypeId::of::<S>(),
1896        }
1897    }
1898}
1899
1900#[derive(Copy, Clone, PartialEq, Eq)]
1901pub struct AnyWindowHandle {
1902    pub(crate) id: WindowId,
1903    state_type: TypeId,
1904}
1905
1906impl AnyWindowHandle {
1907    pub fn window_id(&self) -> WindowId {
1908        self.id
1909    }
1910}
1911
1912#[cfg(any(test, feature = "test-support"))]
1913impl From<SmallVec<[u32; 16]>> for StackingOrder {
1914    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
1915        StackingOrder(small_vec)
1916    }
1917}
1918
1919#[derive(Clone, Debug, Eq, PartialEq, Hash)]
1920pub enum ElementId {
1921    View(EntityId),
1922    Number(usize),
1923    Name(SharedString),
1924    FocusHandle(FocusId),
1925}
1926
1927impl From<EntityId> for ElementId {
1928    fn from(id: EntityId) -> Self {
1929        ElementId::View(id)
1930    }
1931}
1932
1933impl From<usize> for ElementId {
1934    fn from(id: usize) -> Self {
1935        ElementId::Number(id)
1936    }
1937}
1938
1939impl From<i32> for ElementId {
1940    fn from(id: i32) -> Self {
1941        Self::Number(id as usize)
1942    }
1943}
1944
1945impl From<SharedString> for ElementId {
1946    fn from(name: SharedString) -> Self {
1947        ElementId::Name(name)
1948    }
1949}
1950
1951impl From<&'static str> for ElementId {
1952    fn from(name: &'static str) -> Self {
1953        ElementId::Name(name.into())
1954    }
1955}
1956
1957impl<'a> From<&'a FocusHandle> for ElementId {
1958    fn from(handle: &'a FocusHandle) -> Self {
1959        ElementId::FocusHandle(handle.id)
1960    }
1961}