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