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