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