| 1 | #[cfg(feature = "profiler")] |
| 2 | use crate::DebugFrameOverlayMode; |
| 3 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 4 | use crate::Inspector; |
| 5 | #[cfg(feature = "profiler")] |
| 6 | use crate::profiler; |
| 7 | use crate::{ |
| 8 | Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset, |
| 9 | AsyncWindowContext, AtlasTile, AvailableSpace, Background, BorderStyle, Bounds, BoxShadow, |
| 10 | Capslock, Context, Corners, CursorHideMode, CursorStyle, Decorations, DevicePixels, |
| 11 | DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity, |
| 12 | EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs, |
| 13 | Hsla, InputHandler, InputPreference, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent, |
| 14 | Keystroke, KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent, |
| 15 | MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, |
| 16 | PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point, |
| 17 | PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams, |
| 18 | RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR, |
| 19 | SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size, |
| 20 | StrikethroughStyle, Style, SubpixelSprite, SubscriberSet, Subscription, SystemWindowTab, |
| 21 | SystemWindowTabController, TabStopMap, TaffyLayoutEngine, Task, TextInputConfiguration, |
| 22 | TextInputStateChange, TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState, |
| 23 | TransformationMatrix, Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance, |
| 24 | WindowBounds, WindowControls, WindowDecorations, WindowOptions, WindowParams, WindowTextSystem, |
| 25 | WindowVisibility, point, prelude::*, px, rems, size, transparent_black, |
| 26 | }; |
| 27 | |
| 28 | use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer}; |
| 29 | use crate::interactive::TouchEvent; |
| 30 | use anyhow::{Context as _, Result, anyhow}; |
| 31 | use collections::{FxHashMap, FxHashSet}; |
| 32 | #[cfg(any(target_os = "macos", target_os = "ios"))] |
| 33 | use core_video::pixel_buffer::CVPixelBuffer; |
| 34 | use derive_more::{Deref, DerefMut}; |
| 35 | use futures::channel::oneshot; |
| 36 | use gpui_util::post_inc; |
| 37 | use gpui_util::{ResultExt, measure}; |
| 38 | use itertools::FoldWhile::{Continue, Done}; |
| 39 | use itertools::Itertools; |
| 40 | use parking_lot::RwLock; |
| 41 | use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle}; |
| 42 | use refineable::Refineable; |
| 43 | use scheduler::Instant; |
| 44 | use slotmap::SlotMap; |
| 45 | use smallvec::SmallVec; |
| 46 | use std::{ |
| 47 | any::{Any, TypeId}, |
| 48 | borrow::Cow, |
| 49 | cell::{Cell, RefCell}, |
| 50 | cmp, |
| 51 | fmt::{Debug, Display}, |
| 52 | hash::{Hash, Hasher}, |
| 53 | marker::PhantomData, |
| 54 | mem, |
| 55 | ops::{DerefMut, Range}, |
| 56 | rc::Rc, |
| 57 | sync::{ |
| 58 | Arc, Weak, |
| 59 | atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst}, |
| 60 | }, |
| 61 | thread::AccessError, |
| 62 | time::Duration, |
| 63 | }; |
| 64 | use uuid::Uuid; |
| 65 | |
| 66 | pub(crate) mod a11y; |
| 67 | mod prompts; |
| 68 | |
| 69 | pub use a11y::A11ySubtreeBuilder; |
| 70 | |
| 71 | use self::a11y::A11y; |
| 72 | #[cfg(not(target_family = "wasm"))] |
| 73 | use self::a11y::ROOT_NODE_ID; |
| 74 | use crate::util::{ |
| 75 | atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero, |
| 76 | round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel, |
| 77 | }; |
| 78 | pub use prompts::*; |
| 79 | |
| 80 | /// Default window size used when no explicit size is provided. |
| 81 | pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(1095.)); |
| 82 | |
| 83 | /// A 6:5 aspect ratio minimum window size to be used for functional, |
| 84 | /// additional-to-main-Zed windows, like the settings and rules library windows. |
| 85 | pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size { |
| 86 | width: Pixels(900.), |
| 87 | height: Pixels(750.), |
| 88 | }; |
| 89 | |
| 90 | /// Represents the two different phases when dispatching events. |
| 91 | #[derive(Default, Copy, Clone, Debug, Eq, PartialEq)] |
| 92 | pub enum DispatchPhase { |
| 93 | /// After the capture phase comes the bubble phase, in which mouse event listeners are |
| 94 | /// invoked front to back and keyboard event listeners are invoked from the focused element |
| 95 | /// to the root of the element tree. This is the phase you'll most commonly want to use when |
| 96 | /// registering event listeners. |
| 97 | #[default] |
| 98 | Bubble, |
| 99 | /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard |
| 100 | /// listeners are invoked from the root of the tree downward toward the focused element. This phase |
| 101 | /// is used for special purposes such as clearing the "pressed" state for click events. If |
| 102 | /// you stop event propagation during this phase, you need to know what you're doing. Handlers |
| 103 | /// outside of the immediate region may rely on detecting non-local events during this phase. |
| 104 | Capture, |
| 105 | } |
| 106 | |
| 107 | impl DispatchPhase { |
| 108 | /// Returns true if this represents the "bubble" phase. |
| 109 | #[inline] |
| 110 | pub fn bubble(self) -> bool { |
| 111 | self == DispatchPhase::Bubble |
| 112 | } |
| 113 | |
| 114 | /// Returns true if this represents the "capture" phase. |
| 115 | #[inline] |
| 116 | pub fn capture(self) -> bool { |
| 117 | self == DispatchPhase::Capture |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | struct WindowInvalidatorInner { |
| 122 | #[cfg(feature = "profiler")] |
| 123 | pub window_id: WindowId, |
| 124 | pub dirty: bool, |
| 125 | pub draw_phase: DrawPhase, |
| 126 | pub dirty_views: FxHashSet<EntityId>, |
| 127 | pub update_count: usize, |
| 128 | #[cfg(feature = "profiler")] |
| 129 | pub frame_dirty: FrameDirtyAccumulator, |
| 130 | pub platform_waker: Option<Rc<dyn Fn()>>, |
| 131 | } |
| 132 | |
| 133 | /// Per-frame invalidation bookkeeping, drained at draw time and emitted to the |
| 134 | /// frame profiler. Tracks when the current frame first became dirty and how |
| 135 | /// many invalidations were coalesced into it, whenever the profiler is |
| 136 | /// compiled in. Retention of the resulting per-frame records is what |
| 137 | /// `profiler::trace_enabled()` controls, not this measurement. |
| 138 | #[cfg(feature = "profiler")] |
| 139 | #[derive(Default)] |
| 140 | struct FrameDirtyAccumulator { |
| 141 | dirty_at: Option<Instant>, |
| 142 | invalidations: u64, |
| 143 | } |
| 144 | |
| 145 | /// Why GPUI capped a window's frame rate. |
| 146 | #[derive(Clone, Copy)] |
| 147 | enum FrameRateLimit { |
| 148 | /// The window isn't focused. |
| 149 | Inactive, |
| 150 | /// The system is under thermal pressure. |
| 151 | Thermal, |
| 152 | } |
| 153 | |
| 154 | #[derive(Clone)] |
| 155 | pub(crate) struct WindowInvalidator { |
| 156 | inner: Rc<RefCell<WindowInvalidatorInner>>, |
| 157 | } |
| 158 | |
| 159 | impl WindowInvalidator { |
| 160 | pub fn new(#[allow(unused_variables)] window_id: WindowId) -> Self { |
| 161 | WindowInvalidator { |
| 162 | inner: Rc::new(RefCell::new(WindowInvalidatorInner { |
| 163 | #[cfg(feature = "profiler")] |
| 164 | window_id, |
| 165 | dirty: true, |
| 166 | draw_phase: DrawPhase::None, |
| 167 | dirty_views: FxHashSet::default(), |
| 168 | update_count: 0, |
| 169 | #[cfg(feature = "profiler")] |
| 170 | frame_dirty: FrameDirtyAccumulator::default(), |
| 171 | platform_waker: None, |
| 172 | })), |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool { |
| 177 | let mut inner = self.inner.borrow_mut(); |
| 178 | inner.update_count += 1; |
| 179 | inner.dirty_views.insert(entity); |
| 180 | if inner.draw_phase == DrawPhase::None { |
| 181 | #[cfg(feature = "profiler")] |
| 182 | let dirty_at = Self::record_frame_dirty(&mut inner); |
| 183 | let became_dirty = !inner.dirty; |
| 184 | inner.dirty = true; |
| 185 | let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten(); |
| 186 | #[cfg(feature = "profiler")] |
| 187 | let window_id = inner.window_id; |
| 188 | drop(inner); |
| 189 | #[cfg(feature = "profiler")] |
| 190 | if became_dirty { |
| 191 | profiler::journal::record_frame_pending(window_id, dirty_at); |
| 192 | } |
| 193 | cx.push_effect(Effect::Notify { emitter: entity }); |
| 194 | if let Some(waker) = waker { |
| 195 | waker(); |
| 196 | } |
| 197 | true |
| 198 | } else { |
| 199 | false |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | pub fn is_dirty(&self) -> bool { |
| 204 | self.inner.borrow().dirty |
| 205 | } |
| 206 | |
| 207 | pub fn set_dirty(&self, dirty: bool) { |
| 208 | let mut inner = self.inner.borrow_mut(); |
| 209 | let became_dirty = dirty && !inner.dirty; |
| 210 | inner.dirty = dirty; |
| 211 | if dirty { |
| 212 | inner.update_count += 1; |
| 213 | } |
| 214 | #[cfg(feature = "profiler")] |
| 215 | let dirty_at = dirty.then(|| Self::record_frame_dirty(&mut inner)); |
| 216 | let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten(); |
| 217 | #[cfg(feature = "profiler")] |
| 218 | let window_id = inner.window_id; |
| 219 | drop(inner); |
| 220 | #[cfg(feature = "profiler")] |
| 221 | if became_dirty && let Some(dirty_at) = dirty_at { |
| 222 | profiler::journal::record_frame_pending(window_id, dirty_at); |
| 223 | } |
| 224 | if let Some(waker) = waker { |
| 225 | waker(); |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | pub fn set_platform_waker(&self, waker: Option<Rc<dyn Fn()>>) { |
| 230 | let mut inner = self.inner.borrow_mut(); |
| 231 | inner.platform_waker = waker; |
| 232 | let waker = inner.dirty.then(|| inner.platform_waker.clone()).flatten(); |
| 233 | drop(inner); |
| 234 | if let Some(waker) = waker { |
| 235 | waker(); |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | /// Wakes the platform's frame-request source so a frame request is |
| 240 | /// delivered even if the platform stops requesting frames for idle |
| 241 | /// windows. No-op on platforms without a frame waker. |
| 242 | pub fn wake_platform(&self) { |
| 243 | let waker = self.inner.borrow().platform_waker.clone(); |
| 244 | if let Some(waker) = waker { |
| 245 | waker(); |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | pub fn set_phase(&self, phase: DrawPhase) { |
| 250 | self.inner.borrow_mut().draw_phase = phase |
| 251 | } |
| 252 | |
| 253 | pub fn update_count(&self) -> usize { |
| 254 | self.inner.borrow().update_count |
| 255 | } |
| 256 | |
| 257 | #[cfg(feature = "profiler")] |
| 258 | fn record_frame_dirty(inner: &mut WindowInvalidatorInner) -> Instant { |
| 259 | let dirty_at = *inner.frame_dirty.dirty_at.get_or_insert_with(Instant::now); |
| 260 | inner.frame_dirty.invalidations += 1; |
| 261 | dirty_at |
| 262 | } |
| 263 | |
| 264 | #[cfg(feature = "profiler")] |
| 265 | fn take_frame_dirty(&self) -> FrameDirtyAccumulator { |
| 266 | mem::take(&mut self.inner.borrow_mut().frame_dirty) |
| 267 | } |
| 268 | |
| 269 | pub fn take_views(&self) -> FxHashSet<EntityId> { |
| 270 | mem::take(&mut self.inner.borrow_mut().dirty_views) |
| 271 | } |
| 272 | |
| 273 | pub fn replace_views(&self, views: FxHashSet<EntityId>) { |
| 274 | self.inner.borrow_mut().dirty_views = views; |
| 275 | } |
| 276 | |
| 277 | pub fn not_drawing(&self) -> bool { |
| 278 | self.inner.borrow().draw_phase == DrawPhase::None |
| 279 | } |
| 280 | |
| 281 | #[track_caller] |
| 282 | pub fn debug_assert_paint(&self) { |
| 283 | debug_assert!( |
| 284 | matches!(self.inner.borrow().draw_phase, DrawPhase::Paint), |
| 285 | "this method can only be called during paint" |
| 286 | ); |
| 287 | } |
| 288 | |
| 289 | #[track_caller] |
| 290 | pub fn debug_assert_prepaint(&self) { |
| 291 | debug_assert!( |
| 292 | matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint), |
| 293 | "this method can only be called during request_layout, or prepaint" |
| 294 | ); |
| 295 | } |
| 296 | |
| 297 | #[track_caller] |
| 298 | pub fn debug_assert_paint_or_prepaint(&self) { |
| 299 | debug_assert!( |
| 300 | matches!( |
| 301 | self.inner.borrow().draw_phase, |
| 302 | DrawPhase::Paint | DrawPhase::Prepaint |
| 303 | ), |
| 304 | "this method can only be called during request_layout, prepaint, or paint" |
| 305 | ); |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>; |
| 310 | |
| 311 | pub(crate) type AnyWindowFocusListener = |
| 312 | Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>; |
| 313 | |
| 314 | pub(crate) struct WindowFocusEvent { |
| 315 | pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>, |
| 316 | pub(crate) current_focus_path: SmallVec<[FocusId; 8]>, |
| 317 | } |
| 318 | |
| 319 | impl WindowFocusEvent { |
| 320 | pub fn is_focus_in(&self, focus_id: FocusId) -> bool { |
| 321 | !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id) |
| 322 | } |
| 323 | |
| 324 | pub fn is_focus_out(&self, focus_id: FocusId) -> bool { |
| 325 | self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id) |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | /// This is provided when subscribing for `Context::on_focus_out` events. |
| 330 | pub struct FocusOutEvent { |
| 331 | /// A weak focus handle representing what was blurred. |
| 332 | pub blurred: WeakFocusHandle, |
| 333 | } |
| 334 | |
| 335 | slotmap::new_key_type! { |
| 336 | /// A globally unique identifier for a focusable element. |
| 337 | pub struct FocusId; |
| 338 | } |
| 339 | |
| 340 | thread_local! { |
| 341 | /// Fallback arena used when no app-specific arena is active. |
| 342 | /// In production, each window draw sets CURRENT_ELEMENT_ARENA to the app's arena. |
| 343 | pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024)); |
| 344 | |
| 345 | /// Points to the current App's element arena during draw operations. |
| 346 | /// This allows multiple test Apps to have isolated arenas, preventing |
| 347 | /// cross-session corruption when the scheduler interleaves their tasks. |
| 348 | static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) }; |
| 349 | } |
| 350 | |
| 351 | /// Whether a window draw is currently in progress on this thread. |
| 352 | /// |
| 353 | /// This holds exactly while an `ElementArenaScope` is active: nested scopes |
| 354 | /// restore the previous (still set) arena pointer, so `CURRENT_ELEMENT_ARENA` |
| 355 | /// is `Some` from the outermost draw's start to its end. |
| 356 | /// |
| 357 | /// The `on_request_frame` callback uses this to defer draw requests that |
| 358 | /// arrive re-entrantly while a draw is already on the stack (e.g. via nested |
| 359 | /// message pumping in the Windows window procedure), instead of running a |
| 360 | /// nested draw or panicking on the already-borrowed App. |
| 361 | fn draw_in_progress() -> bool { |
| 362 | CURRENT_ELEMENT_ARENA.with(|current| current.get().is_some()) |
| 363 | } |
| 364 | |
| 365 | /// Allocates an element in the current arena. Uses the app-specific arena if one |
| 366 | /// is active (during draw), otherwise falls back to the thread-local ELEMENT_ARENA. |
| 367 | #[inline(always)] |
| 368 | pub(crate) fn with_element_arena<R>(callback: impl FnOnce(&mut Arena) -> R) -> R { |
| 369 | let mut callback = Some(callback); |
| 370 | let mut result = None; |
| 371 | let access = with_element_arena_erased(&mut |arena| { |
| 372 | result = Some(callback.take().expect("arena callback runs once")(arena)); |
| 373 | }); |
| 374 | drop(callback); |
| 375 | access.expect("cannot access a Thread Local Storage value during or after destruction"); |
| 376 | result.expect("arena callback produces a result") |
| 377 | } |
| 378 | |
| 379 | /// Scope guard that sets CURRENT_ELEMENT_ARENA for the duration of a draw |
| 380 | /// operation and tracks the arena's scope depth, so that a nested draw's |
| 381 | /// `ArenaClearNeeded::clear` is deferred rather than freeing memory the outer |
| 382 | /// draw still references (see `Arena::clear`). |
| 383 | /// |
| 384 | /// Call [`ElementArenaScope::exit`] with the same arena that was entered to |
| 385 | /// obtain the [`ArenaClearNeeded`] token the draw now owes; requiring `exit` |
| 386 | /// makes it impossible to request a clear before the scope has ended. The |
| 387 | /// scope's teardown — restoring the thread-local and balancing `begin_scope` |
| 388 | /// with `end_scope` — happens in `Drop`, so the arena's scope depth stays |
| 389 | /// balanced on every path, including when a panic unwinds a draw before `exit` |
| 390 | /// is reached. (If teardown lived only in `exit`, such a panic would leave the |
| 391 | /// scope depth permanently elevated and defer every future clear, leaking |
| 392 | /// memory unboundedly.) |
| 393 | pub(crate) struct ElementArenaScope { |
| 394 | /// The entered arena: compared against the argument in `exit`, and |
| 395 | /// dereferenced in `Drop` to end its scope (see the SAFETY note there). |
| 396 | entered: *const RefCell<Arena>, |
| 397 | previous: Option<*const RefCell<Arena>>, |
| 398 | exited: bool, |
| 399 | } |
| 400 | |
| 401 | impl ElementArenaScope { |
| 402 | /// Enter a scope where element allocations use the given arena. |
| 403 | pub(crate) fn enter(arena: &RefCell<Arena>) -> Self { |
| 404 | arena.borrow_mut().begin_scope(); |
| 405 | let previous = CURRENT_ELEMENT_ARENA.with(|current| { |
| 406 | let prev = current.get(); |
| 407 | current.set(Some(arena as *const RefCell<Arena>)); |
| 408 | prev |
| 409 | }); |
| 410 | Self { |
| 411 | entered: arena as *const RefCell<Arena>, |
| 412 | previous, |
| 413 | exited: false, |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | /// End the scope: restores the previously-current arena and ends the |
| 418 | /// arena's clear-deferral scope. Returns the token for the arena clear the |
| 419 | /// draw now owes; producing it here makes it impossible to request a clear |
| 420 | /// before the scope has ended (which would be silently deferred forever). |
| 421 | /// |
| 422 | /// Panics if passed a different arena than was entered: ending the scope |
| 423 | /// of the wrong arena would unbalance two arenas' scope depths, allowing |
| 424 | /// one of them to clear while a draw still references its memory. |
| 425 | pub(crate) fn exit(mut self, arena: &RefCell<Arena>) -> ArenaClearNeeded { |
| 426 | assert!( |
| 427 | std::ptr::eq(self.entered, arena), |
| 428 | "ElementArenaScope::exit called with a different arena than was entered" |
| 429 | ); |
| 430 | self.exited = true; |
| 431 | // Teardown (restoring the thread-local and ending the arena's |
| 432 | // clear-deferral scope) runs in `Drop`, which fires both here — `self` |
| 433 | // is dropped as `exit` returns, before the token reaches the caller — |
| 434 | // and when a panic unwinds the draw before `exit` is reached. |
| 435 | ArenaClearNeeded::new(arena) |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | impl Drop for ElementArenaScope { |
| 440 | fn drop(&mut self) { |
| 441 | // Teardown lives here (rather than in `exit`) so it runs exactly once on |
| 442 | // every path: `exit` consumes and drops the guard on the normal path, |
| 443 | // and unwinding drops it on the panic path. Balancing `begin_scope` here |
| 444 | // keeps the arena's scope depth correct even when a draw panics; if this |
| 445 | // only happened in `exit`, a panic between `enter` and `exit` would leave |
| 446 | // the depth elevated and defer every future clear. |
| 447 | CURRENT_ELEMENT_ARENA.with(|current| { |
| 448 | current.set(self.previous); |
| 449 | }); |
| 450 | // SAFETY: `entered` came from a `&RefCell<Arena>` in `enter`, and the |
| 451 | // arena (owned by the `App` being drawn) outlives this guard on both the |
| 452 | // normal and unwinding paths, since the guard is a local of the draw. |
| 453 | unsafe { &*self.entered }.borrow_mut().end_scope(); |
| 454 | if !self.exited && !std::thread::panicking() { |
| 455 | debug_assert!(false, "ElementArenaScope dropped without calling exit()"); |
| 456 | log::error!( |
| 457 | "ElementArenaScope dropped without calling exit(); \ |
| 458 | the arena clear for this draw was never requested" |
| 459 | ); |
| 460 | } |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | /// Returned when the element arena has been used and so must be cleared before the next draw. |
| 465 | #[must_use] |
| 466 | pub struct ArenaClearNeeded { |
| 467 | /// Identity of the arena that was drawn into. Only ever compared against |
| 468 | /// another pointer in `clear`; never dereferenced. |
| 469 | arena: *const RefCell<Arena>, |
| 470 | } |
| 471 | |
| 472 | impl ArenaClearNeeded { |
| 473 | /// Create a new ArenaClearNeeded token for the App whose arena was drawn |
| 474 | /// into. Private: the only way to obtain one is [`ElementArenaScope::exit`]. |
| 475 | fn new(arena: &RefCell<Arena>) -> Self { |
| 476 | Self { |
| 477 | arena: arena as *const RefCell<Arena>, |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | /// Clear the element arena of the App the draw ran against. If an enclosing |
| 482 | /// draw is still in progress (this draw was nested inside it), the clear is |
| 483 | /// deferred to the enclosing draw's own `ArenaClearNeeded` so that its live |
| 484 | /// allocations aren't freed. |
| 485 | /// |
| 486 | /// Panics if passed a different App than the draw ran against, since |
| 487 | /// clearing another App's arena could free memory its draws still |
| 488 | /// reference. |
| 489 | pub fn clear(self, cx: &mut App) { |
| 490 | assert!( |
| 491 | std::ptr::eq(self.arena, &cx.element_arena), |
| 492 | "ArenaClearNeeded::clear called with a different App than the draw ran against" |
| 493 | ); |
| 494 | cx.element_arena.borrow_mut().clear(); |
| 495 | } |
| 496 | } |
| 497 | |
| 498 | pub(crate) type FocusMap = RwLock<SlotMap<FocusId, FocusRef>>; |
| 499 | pub(crate) struct FocusRef { |
| 500 | pub(crate) ref_count: AtomicUsize, |
| 501 | pub(crate) tab_index: isize, |
| 502 | pub(crate) tab_stop: bool, |
| 503 | } |
| 504 | |
| 505 | impl FocusId { |
| 506 | /// Obtains whether the element associated with this handle is currently focused. |
| 507 | pub fn is_focused(&self, window: &Window) -> bool { |
| 508 | window.focus == Some(*self) |
| 509 | } |
| 510 | |
| 511 | /// Obtains whether the element associated with this handle contains the focused |
| 512 | /// element or is itself focused. |
| 513 | pub fn contains_focused(&self, window: &Window, cx: &App) -> bool { |
| 514 | window |
| 515 | .focused(cx) |
| 516 | .is_some_and(|focused| self.contains(focused.id, window)) |
| 517 | } |
| 518 | |
| 519 | /// Obtains whether the element associated with this handle is contained within the |
| 520 | /// focused element or is itself focused. |
| 521 | pub fn within_focused(&self, window: &Window, cx: &App) -> bool { |
| 522 | let focused = window.focused(cx); |
| 523 | focused.is_some_and(|focused| focused.id.contains(*self, window)) |
| 524 | } |
| 525 | |
| 526 | /// Obtains whether this handle contains the given handle in the most recently rendered frame. |
| 527 | pub(crate) fn contains(&self, other: Self, window: &Window) -> bool { |
| 528 | window |
| 529 | .rendered_frame |
| 530 | .dispatch_tree |
| 531 | .focus_contains(*self, other) |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | /// A handle which can be used to track and manipulate the focused element in a window. |
| 536 | pub struct FocusHandle { |
| 537 | pub(crate) id: FocusId, |
| 538 | handles: Arc<FocusMap>, |
| 539 | /// The index of this element in the tab order. |
| 540 | pub tab_index: isize, |
| 541 | /// Whether this element can be focused by tab navigation. |
| 542 | pub tab_stop: bool, |
| 543 | } |
| 544 | |
| 545 | impl std::fmt::Debug for FocusHandle { |
| 546 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 547 | f.write_fmt(format_args!("FocusHandle({:?})", self.id)) |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | impl FocusHandle { |
| 552 | pub(crate) fn new(handles: &Arc<FocusMap>) -> Self { |
| 553 | let id = handles.write().insert(FocusRef { |
| 554 | ref_count: AtomicUsize::new(1), |
| 555 | tab_index: 0, |
| 556 | tab_stop: false, |
| 557 | }); |
| 558 | |
| 559 | Self { |
| 560 | id, |
| 561 | tab_index: 0, |
| 562 | tab_stop: false, |
| 563 | handles: handles.clone(), |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> { |
| 568 | let lock = handles.read(); |
| 569 | let focus = lock.get(id)?; |
| 570 | if atomic_incr_if_not_zero(&focus.ref_count) == 0 { |
| 571 | return None; |
| 572 | } |
| 573 | Some(Self { |
| 574 | id, |
| 575 | tab_index: focus.tab_index, |
| 576 | tab_stop: focus.tab_stop, |
| 577 | handles: handles.clone(), |
| 578 | }) |
| 579 | } |
| 580 | |
| 581 | /// Sets the tab index of the element associated with this handle. |
| 582 | pub fn tab_index(mut self, index: isize) -> Self { |
| 583 | self.tab_index = index; |
| 584 | if let Some(focus) = self.handles.write().get_mut(self.id) { |
| 585 | focus.tab_index = index; |
| 586 | } |
| 587 | self |
| 588 | } |
| 589 | |
| 590 | /// Sets whether the element associated with this handle is a tab stop. |
| 591 | /// |
| 592 | /// When `false`, the element will not be included in the tab order. |
| 593 | pub fn tab_stop(mut self, tab_stop: bool) -> Self { |
| 594 | self.tab_stop = tab_stop; |
| 595 | if let Some(focus) = self.handles.write().get_mut(self.id) { |
| 596 | focus.tab_stop = tab_stop; |
| 597 | } |
| 598 | self |
| 599 | } |
| 600 | |
| 601 | /// Converts this focus handle into a weak variant, which does not prevent it from being released. |
| 602 | pub fn downgrade(&self) -> WeakFocusHandle { |
| 603 | WeakFocusHandle { |
| 604 | id: self.id, |
| 605 | handles: Arc::downgrade(&self.handles), |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | /// Moves the focus to the element associated with this handle. |
| 610 | pub fn focus(&self, window: &mut Window, cx: &mut App) { |
| 611 | window.focus(self, cx) |
| 612 | } |
| 613 | |
| 614 | /// Obtains whether the element associated with this handle is currently focused. |
| 615 | pub fn is_focused(&self, window: &Window) -> bool { |
| 616 | self.id.is_focused(window) |
| 617 | } |
| 618 | |
| 619 | /// Obtains whether the element associated with this handle contains the focused |
| 620 | /// element or is itself focused. |
| 621 | pub fn contains_focused(&self, window: &Window, cx: &App) -> bool { |
| 622 | self.id.contains_focused(window, cx) |
| 623 | } |
| 624 | |
| 625 | /// Obtains whether the element associated with this handle is contained within the |
| 626 | /// focused element or is itself focused. |
| 627 | pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool { |
| 628 | self.id.within_focused(window, cx) |
| 629 | } |
| 630 | |
| 631 | /// Obtains whether this handle contains the given handle in the most recently rendered frame. |
| 632 | pub fn contains(&self, other: &Self, window: &Window) -> bool { |
| 633 | self.id.contains(other.id, window) |
| 634 | } |
| 635 | |
| 636 | /// Dispatch an action on the element that rendered this focus handle |
| 637 | pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) { |
| 638 | if let Some(node_id) = window |
| 639 | .rendered_frame |
| 640 | .dispatch_tree |
| 641 | .focusable_node_id(self.id) |
| 642 | { |
| 643 | window.dispatch_action_on_node(node_id, action, cx) |
| 644 | } |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | impl Clone for FocusHandle { |
| 649 | fn clone(&self) -> Self { |
| 650 | Self::for_id(self.id, &self.handles).unwrap() |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | impl PartialEq for FocusHandle { |
| 655 | fn eq(&self, other: &Self) -> bool { |
| 656 | self.id == other.id |
| 657 | } |
| 658 | } |
| 659 | |
| 660 | impl Eq for FocusHandle {} |
| 661 | |
| 662 | impl Drop for FocusHandle { |
| 663 | fn drop(&mut self) { |
| 664 | self.handles |
| 665 | .read() |
| 666 | .get(self.id) |
| 667 | .unwrap() |
| 668 | .ref_count |
| 669 | .fetch_sub(1, SeqCst); |
| 670 | } |
| 671 | } |
| 672 | |
| 673 | /// A weak reference to a focus handle. |
| 674 | #[derive(Clone, Debug)] |
| 675 | pub struct WeakFocusHandle { |
| 676 | pub(crate) id: FocusId, |
| 677 | pub(crate) handles: Weak<FocusMap>, |
| 678 | } |
| 679 | |
| 680 | impl WeakFocusHandle { |
| 681 | /// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle]. |
| 682 | pub fn upgrade(&self) -> Option<FocusHandle> { |
| 683 | let handles = self.handles.upgrade()?; |
| 684 | FocusHandle::for_id(self.id, &handles) |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | impl PartialEq for WeakFocusHandle { |
| 689 | fn eq(&self, other: &WeakFocusHandle) -> bool { |
| 690 | self.id == other.id |
| 691 | } |
| 692 | } |
| 693 | |
| 694 | impl Eq for WeakFocusHandle {} |
| 695 | |
| 696 | impl PartialEq<FocusHandle> for WeakFocusHandle { |
| 697 | fn eq(&self, other: &FocusHandle) -> bool { |
| 698 | self.id == other.id |
| 699 | } |
| 700 | } |
| 701 | |
| 702 | impl PartialEq<WeakFocusHandle> for FocusHandle { |
| 703 | fn eq(&self, other: &WeakFocusHandle) -> bool { |
| 704 | self.id == other.id |
| 705 | } |
| 706 | } |
| 707 | |
| 708 | /// Focusable allows users of your view to easily |
| 709 | /// focus it (using window.focus_view(cx, view)) |
| 710 | pub trait Focusable: 'static { |
| 711 | /// Returns the focus handle associated with this view. |
| 712 | fn focus_handle(&self, cx: &App) -> FocusHandle; |
| 713 | } |
| 714 | |
| 715 | impl<V: Focusable> Focusable for Entity<V> { |
| 716 | fn focus_handle(&self, cx: &App) -> FocusHandle { |
| 717 | self.read(cx).focus_handle(cx) |
| 718 | } |
| 719 | } |
| 720 | |
| 721 | /// ManagedView is a view (like a Modal, Popover, Menu, etc.) |
| 722 | /// where the lifecycle of the view is handled by another view. |
| 723 | pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {} |
| 724 | |
| 725 | impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {} |
| 726 | |
| 727 | /// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal. |
| 728 | pub struct DismissEvent; |
| 729 | |
| 730 | type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>; |
| 731 | |
| 732 | pub(crate) type AnyMouseListener = |
| 733 | Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>; |
| 734 | |
| 735 | #[derive(Clone)] |
| 736 | pub(crate) struct CursorStyleRequest { |
| 737 | pub(crate) hitbox_id: Option<HitboxId>, |
| 738 | pub(crate) style: CursorStyle, |
| 739 | } |
| 740 | |
| 741 | #[derive(Default, Eq, PartialEq)] |
| 742 | pub(crate) struct HitTest { |
| 743 | pub(crate) ids: SmallVec<[HitboxId; 8]>, |
| 744 | pub(crate) hover_hitbox_count: usize, |
| 745 | } |
| 746 | |
| 747 | /// A type of window control area that corresponds to the platform window. |
| 748 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 749 | pub enum WindowControlArea { |
| 750 | /// An area that allows dragging of the platform window. |
| 751 | Drag, |
| 752 | /// An area that allows closing of the platform window. |
| 753 | Close, |
| 754 | /// An area that allows maximizing of the platform window. |
| 755 | Max, |
| 756 | /// An area that allows minimizing of the platform window. |
| 757 | Min, |
| 758 | } |
| 759 | |
| 760 | /// An identifier for a [Hitbox] which also includes [HitboxBehavior]. |
| 761 | #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] |
| 762 | pub struct HitboxId(u64); |
| 763 | |
| 764 | #[cfg(feature = "test-support")] |
| 765 | impl HitboxId { |
| 766 | /// A placeholder HitboxId exclusively for integration testing API's that |
| 767 | /// need a hitbox but where the value of the hitbox does not matter. The |
| 768 | /// alternative is to make the Hitbox optional but that complicates the |
| 769 | /// implementation. |
| 770 | pub const fn placeholder() -> Self { |
| 771 | Self(0) |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | impl HitboxId { |
| 776 | /// Checks if the hitbox with this ID is currently hovered. Returns `false` during keyboard |
| 777 | /// input modality so that keyboard navigation suppresses hover highlights. Except when handling |
| 778 | /// `ScrollWheelEvent`, this is typically what you want when determining whether to handle mouse |
| 779 | /// events or paint hover styles. |
| 780 | /// |
| 781 | /// See [`Hitbox::is_hovered`] for details. |
| 782 | pub fn is_hovered(self, window: &Window) -> bool { |
| 783 | // If this hitbox has captured the pointer, it's always considered hovered |
| 784 | if window.captured_hitbox == Some(self) { |
| 785 | return true; |
| 786 | } |
| 787 | if window.last_input_was_keyboard() { |
| 788 | return false; |
| 789 | } |
| 790 | self.hit_test(window) |
| 791 | } |
| 792 | |
| 793 | /// Checks if the hitbox with this ID is currently hovered, regardless of the last |
| 794 | /// input modality used. |
| 795 | /// |
| 796 | /// See [`HitboxId::is_hovered`] for more details. |
| 797 | pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool { |
| 798 | // If this hitbox has captured the pointer, it's always considered hovered |
| 799 | if window.captured_hitbox == Some(self) { |
| 800 | return true; |
| 801 | } |
| 802 | self.hit_test(window) |
| 803 | } |
| 804 | |
| 805 | fn hit_test(self, window: &Window) -> bool { |
| 806 | let hit_test = &window.mouse_hit_test; |
| 807 | for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) { |
| 808 | if self == *id { |
| 809 | return true; |
| 810 | } |
| 811 | } |
| 812 | false |
| 813 | } |
| 814 | |
| 815 | /// Checks if the hitbox with this ID contains the mouse and should handle scroll events. |
| 816 | /// Typically this should only be used when handling `ScrollWheelEvent`, and otherwise |
| 817 | /// `is_hovered` should be used. See the documentation of `Hitbox::is_hovered` for details about |
| 818 | /// this distinction. |
| 819 | pub fn should_handle_scroll(self, window: &Window) -> bool { |
| 820 | window.mouse_hit_test.ids.contains(&self) |
| 821 | } |
| 822 | |
| 823 | fn next(mut self) -> HitboxId { |
| 824 | HitboxId(self.0.wrapping_add(1)) |
| 825 | } |
| 826 | } |
| 827 | |
| 828 | /// A rectangular region that potentially blocks hitboxes inserted prior. |
| 829 | /// See [Window::insert_hitbox] for more details. |
| 830 | #[derive(Clone, Debug, Deref)] |
| 831 | pub struct Hitbox { |
| 832 | /// A unique identifier for the hitbox. |
| 833 | pub id: HitboxId, |
| 834 | /// The bounds of the hitbox. |
| 835 | #[deref] |
| 836 | pub bounds: Bounds<Pixels>, |
| 837 | /// The content mask when the hitbox was inserted. |
| 838 | pub content_mask: ContentMask<Pixels>, |
| 839 | /// Flags that specify hitbox behavior. |
| 840 | pub behavior: HitboxBehavior, |
| 841 | } |
| 842 | |
| 843 | impl Hitbox { |
| 844 | /// Checks if the hitbox is currently hovered. Returns `false` during keyboard input modality |
| 845 | /// so that keyboard navigation suppresses hover highlights. Except when handling |
| 846 | /// `ScrollWheelEvent`, this is typically what you want when determining whether to handle mouse |
| 847 | /// events or paint hover styles. |
| 848 | /// |
| 849 | /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of |
| 850 | /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`) or |
| 851 | /// `HitboxBehavior::BlockMouseExceptScroll` (`InteractiveElement::block_mouse_except_scroll`), |
| 852 | /// or if the current input modality is keyboard (see [`Window::last_input_was_keyboard`]). |
| 853 | /// |
| 854 | /// Handling of `ScrollWheelEvent` should typically use `should_handle_scroll` instead. |
| 855 | /// Concretely, this is due to use-cases like overlays that cause the elements under to be |
| 856 | /// non-interactive while still allowing scrolling. More abstractly, this is because |
| 857 | /// `is_hovered` is about element interactions directly under the mouse - mouse moves, clicks, |
| 858 | /// hover styling, etc. In contrast, scrolling is about finding the current outer scrollable |
| 859 | /// container. |
| 860 | pub fn is_hovered(&self, window: &Window) -> bool { |
| 861 | self.id.is_hovered(window) |
| 862 | } |
| 863 | |
| 864 | /// Checks whether this hitbox would be hovered at `position`, regardless of the current input |
| 865 | /// modality or mouse position. |
| 866 | pub fn is_hovered_at(&self, position: Point<Pixels>, window: &Window) -> bool { |
| 867 | let hit_test = window.rendered_frame.hit_test(position); |
| 868 | hit_test |
| 869 | .ids |
| 870 | .iter() |
| 871 | .take(hit_test.hover_hitbox_count) |
| 872 | .any(|id| self.id == *id) |
| 873 | } |
| 874 | |
| 875 | /// Checks if the hitbox contains the mouse and should handle scroll events. Typically this |
| 876 | /// should only be used when handling `ScrollWheelEvent`, and otherwise `is_hovered` should be |
| 877 | /// used. See the documentation of `Hitbox::is_hovered` for details about this distinction. |
| 878 | /// |
| 879 | /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of |
| 880 | /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`). |
| 881 | pub fn should_handle_scroll(&self, window: &Window) -> bool { |
| 882 | self.id.should_handle_scroll(window) |
| 883 | } |
| 884 | } |
| 885 | |
| 886 | /// How the hitbox affects mouse behavior. |
| 887 | #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] |
| 888 | pub enum HitboxBehavior { |
| 889 | /// Normal hitbox mouse behavior, doesn't affect mouse handling for other hitboxes. |
| 890 | #[default] |
| 891 | Normal, |
| 892 | |
| 893 | /// All hitboxes behind this hitbox will be ignored and so will have `hitbox.is_hovered() == |
| 894 | /// false` and `hitbox.should_handle_scroll() == false`. Typically for elements this causes |
| 895 | /// skipping of all mouse events, hover styles, and tooltips. This flag is set by |
| 896 | /// [`InteractiveElement::occlude`]. |
| 897 | /// |
| 898 | /// For mouse handlers that check those hitboxes, this behaves the same as registering a |
| 899 | /// bubble-phase handler for every mouse event type: |
| 900 | /// |
| 901 | /// ```ignore |
| 902 | /// window.on_mouse_event(move |_: &EveryMouseEventTypeHere, phase, window, cx| { |
| 903 | /// if phase == DispatchPhase::Capture && hitbox.is_hovered(window) { |
| 904 | /// cx.stop_propagation(); |
| 905 | /// } |
| 906 | /// }) |
| 907 | /// ``` |
| 908 | /// |
| 909 | /// This has effects beyond event handling - any use of hitbox checking, such as hover |
| 910 | /// styles and tooltips. These other behaviors are the main point of this mechanism. An |
| 911 | /// alternative might be to not affect mouse event handling - but this would allow |
| 912 | /// inconsistent UI where clicks and moves interact with elements that are not considered to |
| 913 | /// be hovered. |
| 914 | BlockMouse, |
| 915 | |
| 916 | /// All hitboxes behind this hitbox will have `hitbox.is_hovered() == false`, even when |
| 917 | /// `hitbox.should_handle_scroll() == true`. Typically for elements this causes all mouse |
| 918 | /// interaction except scroll events to be ignored - see the documentation of |
| 919 | /// [`Hitbox::is_hovered`] for details. This flag is set by |
| 920 | /// [`InteractiveElement::block_mouse_except_scroll`]. |
| 921 | /// |
| 922 | /// For mouse handlers that check those hitboxes, this behaves the same as registering a |
| 923 | /// bubble-phase handler for every mouse event type **except** `ScrollWheelEvent`: |
| 924 | /// |
| 925 | /// ```ignore |
| 926 | /// window.on_mouse_event(move |_: &EveryMouseEventTypeExceptScroll, phase, window, cx| { |
| 927 | /// if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) { |
| 928 | /// cx.stop_propagation(); |
| 929 | /// } |
| 930 | /// }) |
| 931 | /// ``` |
| 932 | /// |
| 933 | /// See the documentation of [`Hitbox::is_hovered`] for details of why `ScrollWheelEvent` is |
| 934 | /// handled differently than other mouse events. If also blocking these scroll events is |
| 935 | /// desired, then a `cx.stop_propagation()` handler like the one above can be used. |
| 936 | /// |
| 937 | /// This has effects beyond event handling - this affects any use of `is_hovered`, such as |
| 938 | /// hover styles and tooltips. These other behaviors are the main point of this mechanism. |
| 939 | /// An alternative might be to not affect mouse event handling - but this would allow |
| 940 | /// inconsistent UI where clicks and moves interact with elements that are not considered to |
| 941 | /// be hovered. |
| 942 | BlockMouseExceptScroll, |
| 943 | } |
| 944 | |
| 945 | /// An identifier for a tooltip. |
| 946 | #[derive(Copy, Clone, Debug, Default, Eq, PartialEq)] |
| 947 | pub struct TooltipId(usize); |
| 948 | |
| 949 | impl TooltipId { |
| 950 | /// Checks if the tooltip is currently hovered. |
| 951 | pub fn is_hovered(&self, window: &Window) -> bool { |
| 952 | window |
| 953 | .tooltip_bounds |
| 954 | .as_ref() |
| 955 | .is_some_and(|tooltip_bounds| { |
| 956 | tooltip_bounds.id == *self |
| 957 | && tooltip_bounds.bounds.contains(&window.mouse_position()) |
| 958 | }) |
| 959 | } |
| 960 | } |
| 961 | |
| 962 | pub(crate) struct TooltipBounds { |
| 963 | id: TooltipId, |
| 964 | bounds: Bounds<Pixels>, |
| 965 | } |
| 966 | |
| 967 | #[derive(Clone)] |
| 968 | pub(crate) struct TooltipRequest { |
| 969 | id: TooltipId, |
| 970 | tooltip: AnyTooltip, |
| 971 | } |
| 972 | |
| 973 | pub(crate) struct DeferredDraw { |
| 974 | current_view: EntityId, |
| 975 | priority: usize, |
| 976 | parent_node: DispatchNodeId, |
| 977 | element_id_stack: SmallVec<[ElementId; 32]>, |
| 978 | text_style_stack: Vec<TextStyleRefinement>, |
| 979 | content_mask: Option<ContentMask<Pixels>>, |
| 980 | rem_size: Pixels, |
| 981 | element: Option<AnyElement>, |
| 982 | absolute_offset: Point<Pixels>, |
| 983 | prepaint_range: Range<PrepaintStateIndex>, |
| 984 | paint_range: Range<PaintIndex>, |
| 985 | } |
| 986 | |
| 987 | pub(crate) struct Frame { |
| 988 | pub(crate) focus: Option<FocusId>, |
| 989 | pub(crate) window_active: bool, |
| 990 | pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>, |
| 991 | accessed_element_states: Vec<(GlobalElementId, TypeId)>, |
| 992 | pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>, |
| 993 | pub(crate) dispatch_tree: DispatchTree, |
| 994 | pub(crate) scene: Scene, |
| 995 | pub(crate) hitboxes: Vec<Hitbox>, |
| 996 | pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>, |
| 997 | pub(crate) deferred_draws: Vec<DeferredDraw>, |
| 998 | pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>, |
| 999 | pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>, |
| 1000 | pub(crate) cursor_styles: Vec<CursorStyleRequest>, |
| 1001 | #[cfg(any(test, feature = "test-support"))] |
| 1002 | pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>, |
| 1003 | #[cfg(any(test, feature = "test-support"))] |
| 1004 | debug_bounds_records: Vec<(String, Bounds<Pixels>)>, |
| 1005 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 1006 | pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>, |
| 1007 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 1008 | pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>, |
| 1009 | pub(crate) tab_stops: TabStopMap, |
| 1010 | } |
| 1011 | |
| 1012 | #[derive(Clone, Default)] |
| 1013 | pub(crate) struct PrepaintStateIndex { |
| 1014 | hitboxes_index: usize, |
| 1015 | tooltips_index: usize, |
| 1016 | deferred_draws_index: usize, |
| 1017 | dispatch_tree_index: usize, |
| 1018 | accessed_element_states_index: usize, |
| 1019 | line_layout_index: LineLayoutIndex, |
| 1020 | } |
| 1021 | |
| 1022 | #[derive(Clone, Default)] |
| 1023 | pub(crate) struct PaintIndex { |
| 1024 | scene_index: usize, |
| 1025 | #[cfg(any(test, feature = "test-support"))] |
| 1026 | debug_bounds_index: usize, |
| 1027 | mouse_listeners_index: usize, |
| 1028 | input_handlers_index: usize, |
| 1029 | cursor_styles_index: usize, |
| 1030 | accessed_element_states_index: usize, |
| 1031 | tab_handle_index: usize, |
| 1032 | line_layout_index: LineLayoutIndex, |
| 1033 | } |
| 1034 | |
| 1035 | impl Frame { |
| 1036 | #[cfg(any(test, feature = "test-support"))] |
| 1037 | pub(crate) fn record_debug_bounds(&mut self, selector: String, bounds: Bounds<Pixels>) { |
| 1038 | self.debug_bounds.insert(selector.clone(), bounds); |
| 1039 | self.debug_bounds_records.push((selector, bounds)); |
| 1040 | } |
| 1041 | |
| 1042 | pub(crate) fn new(dispatch_tree: DispatchTree) -> Self { |
| 1043 | Frame { |
| 1044 | focus: None, |
| 1045 | window_active: false, |
| 1046 | element_states: FxHashMap::default(), |
| 1047 | accessed_element_states: Vec::new(), |
| 1048 | mouse_listeners: Vec::new(), |
| 1049 | dispatch_tree, |
| 1050 | scene: Scene::default(), |
| 1051 | hitboxes: Vec::new(), |
| 1052 | window_control_hitboxes: Vec::new(), |
| 1053 | deferred_draws: Vec::new(), |
| 1054 | input_handlers: Vec::new(), |
| 1055 | tooltip_requests: Vec::new(), |
| 1056 | cursor_styles: Vec::new(), |
| 1057 | |
| 1058 | #[cfg(any(test, feature = "test-support"))] |
| 1059 | debug_bounds: FxHashMap::default(), |
| 1060 | #[cfg(any(test, feature = "test-support"))] |
| 1061 | debug_bounds_records: Vec::new(), |
| 1062 | |
| 1063 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 1064 | next_inspector_instance_ids: FxHashMap::default(), |
| 1065 | |
| 1066 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 1067 | inspector_hitboxes: FxHashMap::default(), |
| 1068 | tab_stops: TabStopMap::default(), |
| 1069 | } |
| 1070 | } |
| 1071 | |
| 1072 | pub(crate) fn clear(&mut self) { |
| 1073 | self.element_states.clear(); |
| 1074 | self.accessed_element_states.clear(); |
| 1075 | self.mouse_listeners.clear(); |
| 1076 | self.dispatch_tree.clear(); |
| 1077 | self.scene.clear(); |
| 1078 | self.input_handlers.clear(); |
| 1079 | self.tooltip_requests.clear(); |
| 1080 | self.cursor_styles.clear(); |
| 1081 | self.hitboxes.clear(); |
| 1082 | self.window_control_hitboxes.clear(); |
| 1083 | self.deferred_draws.clear(); |
| 1084 | self.tab_stops.clear(); |
| 1085 | self.focus = None; |
| 1086 | |
| 1087 | #[cfg(any(test, feature = "test-support"))] |
| 1088 | { |
| 1089 | self.debug_bounds.clear(); |
| 1090 | self.debug_bounds_records.clear(); |
| 1091 | } |
| 1092 | |
| 1093 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 1094 | { |
| 1095 | self.next_inspector_instance_ids.clear(); |
| 1096 | self.inspector_hitboxes.clear(); |
| 1097 | } |
| 1098 | } |
| 1099 | |
| 1100 | pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> { |
| 1101 | self.cursor_styles |
| 1102 | .iter() |
| 1103 | .rev() |
| 1104 | .fold_while(None, |style, request| match request.hitbox_id { |
| 1105 | None => Done(Some(request.style)), |
| 1106 | Some(hitbox_id) => Continue(style.or_else(|| { |
| 1107 | hitbox_id |
| 1108 | .is_hovered_ignoring_last_input(window) |
| 1109 | .then_some(request.style) |
| 1110 | })), |
| 1111 | }) |
| 1112 | .into_inner() |
| 1113 | } |
| 1114 | |
| 1115 | pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest { |
| 1116 | let mut set_hover_hitbox_count = false; |
| 1117 | let mut hit_test = HitTest::default(); |
| 1118 | for hitbox in self.hitboxes.iter().rev() { |
| 1119 | let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds); |
| 1120 | if bounds.contains(&position) { |
| 1121 | hit_test.ids.push(hitbox.id); |
| 1122 | if !set_hover_hitbox_count |
| 1123 | && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll |
| 1124 | { |
| 1125 | hit_test.hover_hitbox_count = hit_test.ids.len(); |
| 1126 | set_hover_hitbox_count = true; |
| 1127 | } |
| 1128 | if hitbox.behavior == HitboxBehavior::BlockMouse { |
| 1129 | break; |
| 1130 | } |
| 1131 | } |
| 1132 | } |
| 1133 | if !set_hover_hitbox_count { |
| 1134 | hit_test.hover_hitbox_count = hit_test.ids.len(); |
| 1135 | } |
| 1136 | hit_test |
| 1137 | } |
| 1138 | |
| 1139 | pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> { |
| 1140 | self.focus |
| 1141 | .map(|focus_id| self.dispatch_tree.focus_path(focus_id)) |
| 1142 | .unwrap_or_default() |
| 1143 | } |
| 1144 | |
| 1145 | pub(crate) fn finish(&mut self, prev_frame: &mut Self) { |
| 1146 | for element_state_key in &self.accessed_element_states { |
| 1147 | if let Some((element_state_key, element_state)) = |
| 1148 | prev_frame.element_states.remove_entry(element_state_key) |
| 1149 | { |
| 1150 | self.element_states.insert(element_state_key, element_state); |
| 1151 | } |
| 1152 | } |
| 1153 | |
| 1154 | self.scene.finish(); |
| 1155 | } |
| 1156 | } |
| 1157 | |
| 1158 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)] |
| 1159 | enum InputModality { |
| 1160 | Mouse, |
| 1161 | Keyboard, |
| 1162 | Touch, |
| 1163 | } |
| 1164 | |
| 1165 | /// Holds the state for a specific window. |
| 1166 | pub struct Window { |
| 1167 | pub(crate) handle: AnyWindowHandle, |
| 1168 | pub(crate) invalidator: WindowInvalidator, |
| 1169 | pub(crate) removed: bool, |
| 1170 | pub(crate) platform_window: Box<dyn PlatformWindow>, |
| 1171 | display_id: Option<DisplayId>, |
| 1172 | is_resizable: bool, |
| 1173 | is_minimizable: bool, |
| 1174 | sprite_atlas: Arc<dyn PlatformAtlas>, |
| 1175 | text_system: Arc<WindowTextSystem>, |
| 1176 | text_rendering_mode: Rc<Cell<TextRenderingMode>>, |
| 1177 | rem_size: Pixels, |
| 1178 | /// The stack of override values for the window's rem size. |
| 1179 | /// |
| 1180 | /// This is used by `with_rem_size` to allow rendering an element tree with |
| 1181 | /// a given rem size. |
| 1182 | rem_size_override_stack: SmallVec<[Pixels; 8]>, |
| 1183 | pub(crate) viewport_size: Size<Pixels>, |
| 1184 | layout_engine: Option<TaffyLayoutEngine>, |
| 1185 | pub(crate) root: Option<AnyView>, |
| 1186 | pub(crate) element_id_stack: SmallVec<[ElementId; 32]>, |
| 1187 | pub(crate) text_style_stack: Vec<TextStyleRefinement>, |
| 1188 | pub(crate) rendered_entity_stack: Vec<EntityId>, |
| 1189 | pub(crate) element_offset_stack: Vec<Point<Pixels>>, |
| 1190 | pub(crate) element_opacity: f32, |
| 1191 | pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>, |
| 1192 | pub(crate) requested_autoscroll: Option<Bounds<Pixels>>, |
| 1193 | /// The [`TextInputConfiguration`] most recently forwarded to the platform |
| 1194 | /// window, so that only actual changes are forwarded (reconfiguring a live |
| 1195 | /// input session can restart the IME connection). |
| 1196 | last_text_input_configuration: Option<TextInputConfiguration>, |
| 1197 | focused_text_input_active: bool, |
| 1198 | pub(crate) image_cache_stack: Vec<AnyImageCache>, |
| 1199 | pub(crate) rendered_frame: Frame, |
| 1200 | pub(crate) next_frame: Frame, |
| 1201 | next_hitbox_id: HitboxId, |
| 1202 | pub(crate) next_tooltip_id: TooltipId, |
| 1203 | pub(crate) tooltip_bounds: Option<TooltipBounds>, |
| 1204 | pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>, |
| 1205 | pub(crate) dirty_views: FxHashSet<EntityId>, |
| 1206 | focus_listeners: SubscriberSet<(), AnyWindowFocusListener>, |
| 1207 | pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>, |
| 1208 | focus_lost_path: SmallVec<[FocusId; 8]>, |
| 1209 | default_prevented: bool, |
| 1210 | mouse_position: Point<Pixels>, |
| 1211 | mouse_hit_test: HitTest, |
| 1212 | modifiers: Modifiers, |
| 1213 | capslock: Capslock, |
| 1214 | scale_factor: f32, |
| 1215 | pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>, |
| 1216 | appearance: WindowAppearance, |
| 1217 | pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>, |
| 1218 | pub(crate) button_layout_observers: SubscriberSet<(), AnyObserver>, |
| 1219 | active: Rc<Cell<bool>>, |
| 1220 | visibility: WindowVisibility, |
| 1221 | pub(crate) visibility_observers: |
| 1222 | SubscriberSet<(), Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>, |
| 1223 | hovered: Rc<Cell<bool>>, |
| 1224 | pub(crate) needs_present: Rc<Cell<bool>>, |
| 1225 | /// Tracks recent input event timestamps to determine if input is arriving at a high rate. |
| 1226 | /// Used to selectively enable VRR optimization only when input rate exceeds 60fps. |
| 1227 | pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>, |
| 1228 | #[cfg(feature = "profiler")] |
| 1229 | window_profiler: profiler::WindowProfiler, |
| 1230 | last_input_modality: InputModality, |
| 1231 | touch_gestures: TouchGestureRecognizer, |
| 1232 | touch_prediction_enabled: bool, |
| 1233 | long_press_timer: Option<Task<()>>, |
| 1234 | long_press_capture: Option<EntityId>, |
| 1235 | pub(crate) refreshing: bool, |
| 1236 | pub(crate) activation_observers: SubscriberSet<(), AnyObserver>, |
| 1237 | pub(crate) focus: Option<FocusId>, |
| 1238 | focus_enabled: bool, |
| 1239 | /// Incremented every time focus moves. Used to invalidate a |
| 1240 | /// pending keyboard activation state when focus changes. |
| 1241 | pub(crate) focus_generation: u64, |
| 1242 | pending_input: Option<PendingInput>, |
| 1243 | pending_modifier: ModifierState, |
| 1244 | pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>, |
| 1245 | prompt: Option<RenderablePromptHandle>, |
| 1246 | pub(crate) client_inset: Option<Pixels>, |
| 1247 | /// The hitbox that has captured the pointer, if any. |
| 1248 | /// While captured, mouse events route to this hitbox regardless of hit testing. |
| 1249 | captured_hitbox: Option<HitboxId>, |
| 1250 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 1251 | inspector: Option<Entity<Inspector>>, |
| 1252 | #[cfg(feature = "profiler")] |
| 1253 | debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay, |
| 1254 | pub(crate) a11y: A11y, |
| 1255 | } |
| 1256 | |
| 1257 | #[derive(Clone, Debug, Default)] |
| 1258 | struct ModifierState { |
| 1259 | modifiers: Modifiers, |
| 1260 | saw_other_input: bool, |
| 1261 | } |
| 1262 | |
| 1263 | /// Tracks input event timestamps to determine if input is arriving at a high rate. |
| 1264 | /// Used for selective VRR (Variable Refresh Rate) optimization. |
| 1265 | #[derive(Clone, Debug)] |
| 1266 | pub(crate) struct InputRateTracker { |
| 1267 | timestamps: Vec<Instant>, |
| 1268 | window: Duration, |
| 1269 | inputs_per_second: u32, |
| 1270 | sustain_until: Instant, |
| 1271 | sustain_duration: Duration, |
| 1272 | } |
| 1273 | |
| 1274 | impl Default for InputRateTracker { |
| 1275 | fn default() -> Self { |
| 1276 | Self { |
| 1277 | timestamps: Vec::new(), |
| 1278 | window: Duration::from_millis(100), |
| 1279 | inputs_per_second: 60, |
| 1280 | sustain_until: Instant::now(), |
| 1281 | sustain_duration: Duration::from_secs(1), |
| 1282 | } |
| 1283 | } |
| 1284 | } |
| 1285 | |
| 1286 | impl InputRateTracker { |
| 1287 | pub fn record_input(&mut self) { |
| 1288 | let now = Instant::now(); |
| 1289 | self.timestamps.push(now); |
| 1290 | self.prune_old_timestamps(now); |
| 1291 | |
| 1292 | let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000; |
| 1293 | if self.timestamps.len() as u128 >= min_events { |
| 1294 | self.sustain_until = now + self.sustain_duration; |
| 1295 | } |
| 1296 | } |
| 1297 | |
| 1298 | pub fn is_high_rate(&self) -> bool { |
| 1299 | Instant::now() < self.sustain_until |
| 1300 | } |
| 1301 | |
| 1302 | fn prune_old_timestamps(&mut self, now: Instant) { |
| 1303 | self.timestamps |
| 1304 | .retain(|&t| now.duration_since(t) <= self.window); |
| 1305 | } |
| 1306 | } |
| 1307 | |
| 1308 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 1309 | pub(crate) enum DrawPhase { |
| 1310 | None, |
| 1311 | Prepaint, |
| 1312 | Paint, |
| 1313 | Focus, |
| 1314 | } |
| 1315 | |
| 1316 | pub(crate) const PENDING_INPUT_TIMEOUT: Duration = Duration::from_secs(1); |
| 1317 | |
| 1318 | /// Pending input for a potential multi-stroke key binding. |
| 1319 | pub struct PendingInputStatus<'a> { |
| 1320 | keystrokes: &'a [Keystroke], |
| 1321 | timeout: Option<PendingInputTimeoutStatus>, |
| 1322 | } |
| 1323 | |
| 1324 | impl<'a> PendingInputStatus<'a> { |
| 1325 | /// Returns the keystrokes entered so far. |
| 1326 | pub fn keystrokes(&self) -> &'a [Keystroke] { |
| 1327 | self.keystrokes |
| 1328 | } |
| 1329 | |
| 1330 | /// Returns the timeout state for flushing this input, if it needs a timeout. |
| 1331 | pub fn timeout(&self) -> Option<PendingInputTimeoutStatus> { |
| 1332 | self.timeout |
| 1333 | } |
| 1334 | } |
| 1335 | |
| 1336 | /// The timeout state for pending input. |
| 1337 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 1338 | pub struct PendingInputTimeoutStatus { |
| 1339 | duration: Duration, |
| 1340 | remaining: Duration, |
| 1341 | started_at: Option<Instant>, |
| 1342 | paused: bool, |
| 1343 | } |
| 1344 | |
| 1345 | impl PendingInputTimeoutStatus { |
| 1346 | /// Returns the full timeout duration. |
| 1347 | pub fn duration(&self) -> Duration { |
| 1348 | self.duration |
| 1349 | } |
| 1350 | |
| 1351 | /// Returns the duration remaining before pending input is flushed. |
| 1352 | pub fn remaining(&self, cx: &App) -> Duration { |
| 1353 | self.started_at |
| 1354 | .map(|started_at| { |
| 1355 | self.remaining |
| 1356 | .saturating_sub(cx.background_executor().now() - started_at) |
| 1357 | }) |
| 1358 | .unwrap_or(self.remaining) |
| 1359 | } |
| 1360 | |
| 1361 | /// Returns whether the timeout is paused. |
| 1362 | pub fn is_paused(&self) -> bool { |
| 1363 | self.paused |
| 1364 | } |
| 1365 | } |
| 1366 | |
| 1367 | #[derive(Debug)] |
| 1368 | struct PendingInputTimeout { |
| 1369 | duration: Duration, |
| 1370 | remaining: Duration, |
| 1371 | state: PendingInputTimeoutState, |
| 1372 | } |
| 1373 | |
| 1374 | #[derive(Debug)] |
| 1375 | enum PendingInputTimeoutState { |
| 1376 | Running { started_at: Instant, task: Task<()> }, |
| 1377 | Paused { pause: PendingInputTimeoutPause }, |
| 1378 | } |
| 1379 | |
| 1380 | #[derive(Debug)] |
| 1381 | struct PendingInputTimeoutPause { |
| 1382 | owner_id: EntityId, |
| 1383 | _release_subscription: Subscription, |
| 1384 | } |
| 1385 | |
| 1386 | impl PendingInputTimeout { |
| 1387 | fn is_paused(&self) -> bool { |
| 1388 | matches!(&self.state, PendingInputTimeoutState::Paused { .. }) |
| 1389 | } |
| 1390 | |
| 1391 | fn pause(&mut self, pause: PendingInputTimeoutPause, now: Instant) -> bool { |
| 1392 | match std::mem::replace(&mut self.state, PendingInputTimeoutState::Paused { pause }) { |
| 1393 | PendingInputTimeoutState::Running { started_at, task } => { |
| 1394 | self.remaining = self.remaining.saturating_sub(now - started_at); |
| 1395 | drop(task); |
| 1396 | true |
| 1397 | } |
| 1398 | previous_state @ PendingInputTimeoutState::Paused { .. } => { |
| 1399 | self.state = previous_state; |
| 1400 | false |
| 1401 | } |
| 1402 | } |
| 1403 | } |
| 1404 | |
| 1405 | fn pause_owner_id(&self) -> Option<EntityId> { |
| 1406 | match &self.state { |
| 1407 | PendingInputTimeoutState::Running { .. } => None, |
| 1408 | PendingInputTimeoutState::Paused { pause } => Some(pause.owner_id), |
| 1409 | } |
| 1410 | } |
| 1411 | |
| 1412 | fn resume(&mut self, owner_id: EntityId, started_at: Instant, task: Task<()>) -> bool { |
| 1413 | match std::mem::replace( |
| 1414 | &mut self.state, |
| 1415 | PendingInputTimeoutState::Running { started_at, task }, |
| 1416 | ) { |
| 1417 | PendingInputTimeoutState::Paused { pause } if pause.owner_id == owner_id => true, |
| 1418 | previous_state => { |
| 1419 | self.state = previous_state; |
| 1420 | false |
| 1421 | } |
| 1422 | } |
| 1423 | } |
| 1424 | |
| 1425 | fn reset_duration(&mut self, duration: Duration) { |
| 1426 | self.duration = duration; |
| 1427 | self.remaining = duration; |
| 1428 | } |
| 1429 | |
| 1430 | fn status(&self) -> PendingInputTimeoutStatus { |
| 1431 | let (started_at, paused) = match &self.state { |
| 1432 | PendingInputTimeoutState::Running { started_at, .. } => (Some(*started_at), false), |
| 1433 | PendingInputTimeoutState::Paused { .. } => (None, true), |
| 1434 | }; |
| 1435 | PendingInputTimeoutStatus { |
| 1436 | duration: self.duration, |
| 1437 | remaining: self.remaining, |
| 1438 | started_at, |
| 1439 | paused, |
| 1440 | } |
| 1441 | } |
| 1442 | } |
| 1443 | |
| 1444 | #[derive(Default, Debug)] |
| 1445 | struct PendingInput { |
| 1446 | keystrokes: SmallVec<[Keystroke; 1]>, |
| 1447 | focus: Option<FocusId>, |
| 1448 | timeout: Option<PendingInputTimeout>, |
| 1449 | } |
| 1450 | |
| 1451 | pub(crate) struct ElementStateBox { |
| 1452 | pub(crate) inner: Box<dyn Any>, |
| 1453 | #[cfg(debug_assertions)] |
| 1454 | pub(crate) type_name: &'static str, |
| 1455 | } |
| 1456 | |
| 1457 | fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds { |
| 1458 | // TODO, BUG: if you open a window with the currently active window |
| 1459 | // on the stack, this will erroneously fallback to `None` |
| 1460 | // |
| 1461 | // TODO these should be the initial window bounds not considering maximized/fullscreen |
| 1462 | let active_window_bounds = cx |
| 1463 | .active_window() |
| 1464 | .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok()); |
| 1465 | |
| 1466 | const CASCADE_OFFSET: f32 = 25.0; |
| 1467 | |
| 1468 | let display = display_id |
| 1469 | .map(|id| cx.find_display(id)) |
| 1470 | .unwrap_or_else(|| cx.primary_display()); |
| 1471 | |
| 1472 | let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE); |
| 1473 | |
| 1474 | // Use visible_bounds to exclude taskbar/dock areas |
| 1475 | let display_bounds = display |
| 1476 | .as_ref() |
| 1477 | .map(|d| d.visible_bounds()) |
| 1478 | .unwrap_or_else(default_placement); |
| 1479 | |
| 1480 | let ( |
| 1481 | Bounds { |
| 1482 | origin: base_origin, |
| 1483 | size: base_size, |
| 1484 | }, |
| 1485 | window_bounds_ctor, |
| 1486 | ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds { |
| 1487 | Some(bounds) => match bounds { |
| 1488 | WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed), |
| 1489 | WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized), |
| 1490 | WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen), |
| 1491 | }, |
| 1492 | None => ( |
| 1493 | display |
| 1494 | .as_ref() |
| 1495 | .map(|d| d.default_bounds()) |
| 1496 | .unwrap_or_else(default_placement), |
| 1497 | WindowBounds::Windowed, |
| 1498 | ), |
| 1499 | }; |
| 1500 | |
| 1501 | let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET)); |
| 1502 | let proposed_origin = base_origin + cascade_offset; |
| 1503 | let proposed_bounds = Bounds::new(proposed_origin, base_size); |
| 1504 | |
| 1505 | let display_right = display_bounds.origin.x + display_bounds.size.width; |
| 1506 | let display_bottom = display_bounds.origin.y + display_bounds.size.height; |
| 1507 | let window_right = proposed_bounds.origin.x + proposed_bounds.size.width; |
| 1508 | let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height; |
| 1509 | |
| 1510 | let fits_horizontally = window_right <= display_right; |
| 1511 | let fits_vertically = window_bottom <= display_bottom; |
| 1512 | |
| 1513 | let final_origin = match (fits_horizontally, fits_vertically) { |
| 1514 | (true, true) => proposed_origin, |
| 1515 | (false, true) => point(display_bounds.origin.x, base_origin.y), |
| 1516 | (true, false) => point(base_origin.x, display_bounds.origin.y), |
| 1517 | (false, false) => display_bounds.origin, |
| 1518 | }; |
| 1519 | window_bounds_ctor(Bounds::new(final_origin, base_size)) |
| 1520 | } |
| 1521 | |
| 1522 | impl Window { |
| 1523 | pub(crate) fn new( |
| 1524 | handle: AnyWindowHandle, |
| 1525 | options: WindowOptions, |
| 1526 | cx: &mut App, |
| 1527 | ) -> Result<Self> { |
| 1528 | let WindowOptions { |
| 1529 | window_bounds, |
| 1530 | titlebar, |
| 1531 | focus, |
| 1532 | show, |
| 1533 | kind, |
| 1534 | is_movable, |
| 1535 | app_owns_titlebar_drag, |
| 1536 | inactive_frame_interval, |
| 1537 | is_resizable, |
| 1538 | is_minimizable, |
| 1539 | display_id, |
| 1540 | window_background, |
| 1541 | app_id, |
| 1542 | window_min_size, |
| 1543 | window_decorations, |
| 1544 | #[cfg_attr( |
| 1545 | not(any(target_os = "linux", target_os = "freebsd")), |
| 1546 | allow(unused_variables) |
| 1547 | )] |
| 1548 | icon, |
| 1549 | #[cfg_attr(not(target_os = "macos"), allow(unused_variables))] |
| 1550 | tabbing_identifier, |
| 1551 | } = options; |
| 1552 | |
| 1553 | let initial_window_title = titlebar |
| 1554 | .as_ref() |
| 1555 | .and_then(|titlebar| titlebar.title.clone()); |
| 1556 | |
| 1557 | let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx)); |
| 1558 | let mut platform_window = cx.platform.open_window( |
| 1559 | handle, |
| 1560 | WindowParams { |
| 1561 | bounds: window_bounds.get_bounds(), |
| 1562 | titlebar, |
| 1563 | kind, |
| 1564 | is_movable, |
| 1565 | app_owns_titlebar_drag, |
| 1566 | is_resizable, |
| 1567 | is_minimizable, |
| 1568 | focus, |
| 1569 | show, |
| 1570 | display_id, |
| 1571 | window_min_size, |
| 1572 | app_id: app_id.clone(), |
| 1573 | icon, |
| 1574 | #[cfg(target_os = "macos")] |
| 1575 | tabbing_identifier, |
| 1576 | }, |
| 1577 | )?; |
| 1578 | |
| 1579 | let tab_bar_visible = platform_window.tab_bar_visible(); |
| 1580 | SystemWindowTabController::init_visible(cx, tab_bar_visible); |
| 1581 | if let Some(tabs) = platform_window.tabbed_windows() { |
| 1582 | SystemWindowTabController::add_tab(cx, handle.window_id(), tabs); |
| 1583 | } |
| 1584 | |
| 1585 | let display_id = platform_window.display().map(|display| display.id()); |
| 1586 | let sprite_atlas = platform_window.sprite_atlas(); |
| 1587 | let mouse_position = platform_window.mouse_position(); |
| 1588 | let modifiers = platform_window.modifiers(); |
| 1589 | let capslock = platform_window.capslock(); |
| 1590 | let content_size = platform_window.content_size(); |
| 1591 | let scale_factor = platform_window.scale_factor(); |
| 1592 | let appearance = platform_window.appearance(); |
| 1593 | let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone())); |
| 1594 | let invalidator = WindowInvalidator::new(handle.window_id()); |
| 1595 | let active = Rc::new(Cell::new(platform_window.is_active())); |
| 1596 | let visibility = platform_window.visibility(); |
| 1597 | #[cfg(feature = "profiler")] |
| 1598 | profiler::journal::record_window_visibility(handle.window_id(), visibility); |
| 1599 | let hovered = Rc::new(Cell::new(platform_window.is_hovered())); |
| 1600 | let needs_present = Rc::new(Cell::new(false)); |
| 1601 | let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default(); |
| 1602 | let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default())); |
| 1603 | let last_frame_time = Rc::new(Cell::new(None)); |
| 1604 | |
| 1605 | platform_window |
| 1606 | .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server)); |
| 1607 | platform_window.set_background_appearance(window_background); |
| 1608 | |
| 1609 | match window_bounds { |
| 1610 | WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(), |
| 1611 | WindowBounds::Maximized(_) => platform_window.zoom(), |
| 1612 | WindowBounds::Windowed(_) => {} |
| 1613 | } |
| 1614 | |
| 1615 | let accessibility_force_disabled = cx.accessibility_force_disabled; |
| 1616 | let a11y_active_flag = Arc::new(AtomicBool::new(false)); |
| 1617 | |
| 1618 | #[cfg(not(target_family = "wasm"))] |
| 1619 | if !accessibility_force_disabled { |
| 1620 | let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window); |
| 1621 | if let Some(title) = &initial_window_title { |
| 1622 | initial_root_node.set_label(title.to_string()); |
| 1623 | } |
| 1624 | let initial_tree = accesskit::TreeUpdate { |
| 1625 | nodes: vec![(ROOT_NODE_ID, initial_root_node)], |
| 1626 | tree: Some(accesskit::Tree::new(ROOT_NODE_ID)), |
| 1627 | tree_id: accesskit::TreeId::ROOT, |
| 1628 | focus: ROOT_NODE_ID, |
| 1629 | }; |
| 1630 | let (activation_sender, activation_receiver) = async_channel::unbounded::<()>(); |
| 1631 | let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>(); |
| 1632 | let (action_sender, action_receiver) = |
| 1633 | async_channel::unbounded::<accesskit::ActionRequest>(); |
| 1634 | |
| 1635 | platform_window.a11y_init(crate::A11yCallbacks { |
| 1636 | activation: { |
| 1637 | let active_flag = a11y_active_flag.clone(); |
| 1638 | Box::new(move || { |
| 1639 | log::info!("Accessibility activated"); |
| 1640 | active_flag.store(true, SeqCst); |
| 1641 | activation_sender.send_blocking(()).log_err(); |
| 1642 | Some(initial_tree.clone()) |
| 1643 | }) |
| 1644 | }, |
| 1645 | action: Box::new(move |request| { |
| 1646 | action_sender.send_blocking(request).log_err(); |
| 1647 | }), |
| 1648 | deactivation: { |
| 1649 | let active_flag = a11y_active_flag.clone(); |
| 1650 | Box::new(move || { |
| 1651 | log::info!("Accessibility deactivated"); |
| 1652 | active_flag.store(false, SeqCst); |
| 1653 | deactivation_sender.send_blocking(()).log_err(); |
| 1654 | }) |
| 1655 | }, |
| 1656 | }); |
| 1657 | |
| 1658 | // A11y can be activated at any time, and so we cannot compute a |
| 1659 | // correct `TreeUpdate` on-demand. When this happens, we return a |
| 1660 | // default empty `TreeUpdate`. |
| 1661 | // |
| 1662 | // So we force a new frame, which will then send a correct `TreeUpdate`. |
| 1663 | let mut async_cx = cx.to_async(); |
| 1664 | cx.foreground_executor() |
| 1665 | .spawn(async move { |
| 1666 | while activation_receiver.recv().await.is_ok() { |
| 1667 | handle |
| 1668 | .update(&mut async_cx, |_, window, _| window.refresh()) |
| 1669 | .log_err(); |
| 1670 | } |
| 1671 | }) |
| 1672 | .detach(); |
| 1673 | |
| 1674 | let mut async_cx = cx.to_async(); |
| 1675 | cx.foreground_executor() |
| 1676 | .spawn(async move { |
| 1677 | while deactivation_receiver.recv().await.is_ok() { |
| 1678 | handle |
| 1679 | .update(&mut async_cx, |_, window, _| window.refresh()) |
| 1680 | .log_err(); |
| 1681 | } |
| 1682 | }) |
| 1683 | .detach(); |
| 1684 | |
| 1685 | let mut async_cx = cx.to_async(); |
| 1686 | cx.foreground_executor() |
| 1687 | .spawn(async move { |
| 1688 | while let Ok(request) = action_receiver.recv().await { |
| 1689 | handle |
| 1690 | .update(&mut async_cx, |_, window, cx| { |
| 1691 | window.handle_a11y_action(request, cx); |
| 1692 | }) |
| 1693 | .log_err(); |
| 1694 | } |
| 1695 | }) |
| 1696 | .detach(); |
| 1697 | } |
| 1698 | |
| 1699 | platform_window.on_close(Box::new({ |
| 1700 | let window_id = handle.window_id(); |
| 1701 | let mut cx = cx.to_async(); |
| 1702 | move || { |
| 1703 | let _ = handle.update(&mut cx, |_, window, _| window.remove_window()); |
| 1704 | let _ = cx.update(|cx| { |
| 1705 | SystemWindowTabController::remove_tab(cx, window_id); |
| 1706 | }); |
| 1707 | } |
| 1708 | })); |
| 1709 | platform_window.on_request_frame(Box::new({ |
| 1710 | let mut cx = cx.to_async(); |
| 1711 | let invalidator = invalidator.clone(); |
| 1712 | let active = active.clone(); |
| 1713 | let needs_present = needs_present.clone(); |
| 1714 | let next_frame_callbacks = next_frame_callbacks.clone(); |
| 1715 | let input_rate_tracker = input_rate_tracker.clone(); |
| 1716 | let mut deferred_force_render = false; |
| 1717 | move |request_frame_options| { |
| 1718 | #[cfg(feature = "profiler")] |
| 1719 | let (_foreground_turn, window_id) = { |
| 1720 | let foreground_turn = profiler::journal::foreground_turn(); |
| 1721 | let window_id = handle.window_id(); |
| 1722 | profiler::journal::record_platform_signal(profiler::journal::PlatformSignal { |
| 1723 | window_id, |
| 1724 | signal_at: request_frame_options.signal_at, |
| 1725 | handled_at: Instant::now(), |
| 1726 | source: request_frame_options.signal_source, |
| 1727 | }); |
| 1728 | (foreground_turn, window_id) |
| 1729 | }; |
| 1730 | // This must be checked before accessing App: if this request |
| 1731 | // arrived re-entrantly while a draw is on this thread's stack |
| 1732 | // (e.g. via a nested message pump in the Windows window |
| 1733 | // procedure), drawing would nest draws, and even touching the |
| 1734 | // App would panic on its already-mutable borrow. Skip instead; |
| 1735 | // the platform leaves the window invalidated (or re-invalidates |
| 1736 | // it), so a fresh request arrives once the in-progress draw |
| 1737 | // unwinds. Remember force_render so the deferred frame still |
| 1738 | // bypasses the view cache. |
| 1739 | // |
| 1740 | // Returning here skips `complete_frame`, which on Wayland would |
| 1741 | // stall the window's frame callbacks (no `surface.commit()`) — |
| 1742 | // but calling it would hit the App borrow panic above, and this |
| 1743 | // branch is unreachable there in practice: only Windows pumps |
| 1744 | // platform events (and thus requests frames) mid-draw. |
| 1745 | if draw_in_progress() { |
| 1746 | log::debug!("deferring re-entrant window draw request"); |
| 1747 | deferred_force_render |= request_frame_options.force_render; |
| 1748 | #[cfg(feature = "profiler")] |
| 1749 | profiler::journal::record_reentrant_frame_skipped(window_id, Instant::now()); |
| 1750 | return; |
| 1751 | } |
| 1752 | // Take the deferred flag first: `||` short-circuits, and leaving |
| 1753 | // the flag set when this request already forces a render would |
| 1754 | // force a second, redundant render on the next frame. |
| 1755 | let force_render = |
| 1756 | mem::take(&mut deferred_force_render) || request_frame_options.force_render; |
| 1757 | |
| 1758 | let thermal_state = handle |
| 1759 | .update(&mut cx, |_, _, cx| cx.thermal_state()) |
| 1760 | .log_err(); |
| 1761 | |
| 1762 | // Throttle frame rate based on conditions: |
| 1763 | // - Thermal pressure (Serious/Critical): cap to ~60fps |
| 1764 | // - Inactive window (not focused): cap to ~30fps to save energy |
| 1765 | let min_frame_interval = if request_frame_options.require_presentation |
| 1766 | || (!request_frame_options.force_render |
| 1767 | && next_frame_callbacks.borrow().is_empty()) |
| 1768 | { |
| 1769 | None |
| 1770 | } else if !active.get() && !input_rate_tracker.borrow_mut().is_high_rate() { |
| 1771 | inactive_frame_interval.map(|interval| (interval, FrameRateLimit::Inactive)) |
| 1772 | } else if let Some(ThermalState::Critical | ThermalState::Serious) = thermal_state { |
| 1773 | Some((Duration::from_micros(16667), FrameRateLimit::Thermal)) |
| 1774 | } else { |
| 1775 | None |
| 1776 | }; |
| 1777 | |
| 1778 | let now = Instant::now(); |
| 1779 | #[cfg_attr(not(feature = "profiler"), expect(unused_variables))] |
| 1780 | if let Some((min_interval, limit)) = min_frame_interval { |
| 1781 | if let Some(last_frame) = last_frame_time.get() |
| 1782 | && now.duration_since(last_frame) < min_interval |
| 1783 | { |
| 1784 | // Don't lose a pending forced render to throttling. |
| 1785 | deferred_force_render |= force_render; |
| 1786 | // Deferred by throttling: ask demand-driven platforms to retry. |
| 1787 | handle |
| 1788 | .update(&mut cx, |_, window, _| { |
| 1789 | window.platform_window.schedule_frame(); |
| 1790 | }) |
| 1791 | .log_err(); |
| 1792 | // The demand that entered this branch (a deferred forced |
| 1793 | // render or pending next-frame callbacks) is still |
| 1794 | // unserved; platforms that stop requesting frames for |
| 1795 | // idle windows need a wakeup to deliver the retry. |
| 1796 | invalidator.wake_platform(); |
| 1797 | #[cfg(feature = "profiler")] |
| 1798 | profiler::journal::record_frame_skipped( |
| 1799 | window_id, |
| 1800 | Instant::now(), |
| 1801 | match limit { |
| 1802 | FrameRateLimit::Inactive => { |
| 1803 | profiler::journal::FrameSkipReason::InactiveFrameRateLimit |
| 1804 | } |
| 1805 | FrameRateLimit::Thermal => { |
| 1806 | profiler::journal::FrameSkipReason::ThermalFrameRateLimit |
| 1807 | } |
| 1808 | }, |
| 1809 | ); |
| 1810 | return; |
| 1811 | } |
| 1812 | } |
| 1813 | last_frame_time.set(Some(now)); |
| 1814 | |
| 1815 | let pending_next_frame_callbacks = next_frame_callbacks.take(); |
| 1816 | if !pending_next_frame_callbacks.is_empty() { |
| 1817 | handle |
| 1818 | .update(&mut cx, |_, window, cx| { |
| 1819 | for callback in pending_next_frame_callbacks { |
| 1820 | callback(window, cx); |
| 1821 | } |
| 1822 | }) |
| 1823 | .log_err(); |
| 1824 | } |
| 1825 | |
| 1826 | // Keep presenting if input was recently arriving at a high rate (>= 60fps). |
| 1827 | // Once high-rate input is detected, we sustain presentation for 1 second |
| 1828 | // to prevent display underclocking during active input. |
| 1829 | let needs_present = request_frame_options.require_presentation |
| 1830 | || needs_present.get() |
| 1831 | || input_rate_tracker.borrow_mut().is_high_rate(); |
| 1832 | |
| 1833 | let should_draw = invalidator.is_dirty() || force_render; |
| 1834 | if should_draw { |
| 1835 | measure("frame duration", || { |
| 1836 | handle |
| 1837 | .update(&mut cx, |_, window, cx| { |
| 1838 | if force_render { |
| 1839 | // Bypass cached view reuse so we don't replay stale |
| 1840 | // atlas tile references after a GPU device recovery. |
| 1841 | window.refresh(); |
| 1842 | } |
| 1843 | let arena_clear_needed = window.draw(cx); |
| 1844 | window.present(); |
| 1845 | arena_clear_needed.clear(cx); |
| 1846 | }) |
| 1847 | .log_err(); |
| 1848 | }) |
| 1849 | } else if needs_present { |
| 1850 | handle |
| 1851 | .update(&mut cx, |_, window, _| window.present()) |
| 1852 | .log_err(); |
| 1853 | } |
| 1854 | |
| 1855 | handle |
| 1856 | .update(&mut cx, |_, window, _| { |
| 1857 | if window.invalidator.is_dirty() |
| 1858 | || !window.next_frame_callbacks.borrow().is_empty() |
| 1859 | { |
| 1860 | window.platform_window.schedule_frame(); |
| 1861 | } |
| 1862 | }) |
| 1863 | .log_err(); |
| 1864 | |
| 1865 | // Platforms that stop requesting frames for idle windows only |
| 1866 | // deliver another request after a wakeup. If demand remains |
| 1867 | // after this frame (the window was re-invalidated mid-draw, or |
| 1868 | // animations scheduled next-frame callbacks), re-arm the frame |
| 1869 | // source explicitly. |
| 1870 | if invalidator.is_dirty() || !next_frame_callbacks.borrow().is_empty() { |
| 1871 | invalidator.wake_platform(); |
| 1872 | } |
| 1873 | #[cfg(feature = "profiler")] |
| 1874 | if !should_draw { |
| 1875 | profiler::journal::record_frame_skipped( |
| 1876 | window_id, |
| 1877 | Instant::now(), |
| 1878 | profiler::journal::FrameSkipReason::NoRenderNeeded, |
| 1879 | ); |
| 1880 | } |
| 1881 | } |
| 1882 | })); |
| 1883 | invalidator.set_platform_waker(platform_window.frame_waker()); |
| 1884 | platform_window.on_visual_viewport_changed(Box::new({ |
| 1885 | let mut cx = cx.to_async(); |
| 1886 | move || { |
| 1887 | handle |
| 1888 | .update(&mut cx, |_, window, _| window.refresh()) |
| 1889 | .log_err(); |
| 1890 | } |
| 1891 | })); |
| 1892 | platform_window.on_insets_changed(Box::new({ |
| 1893 | let mut cx = cx.to_async(); |
| 1894 | move |_| { |
| 1895 | handle |
| 1896 | .update(&mut cx, |_, window, _| window.refresh()) |
| 1897 | .log_err(); |
| 1898 | } |
| 1899 | })); |
| 1900 | platform_window.on_resize(Box::new({ |
| 1901 | let mut cx = cx.to_async(); |
| 1902 | move |_, _| { |
| 1903 | handle |
| 1904 | .update(&mut cx, |_, window, cx| window.bounds_changed(cx)) |
| 1905 | .log_err(); |
| 1906 | } |
| 1907 | })); |
| 1908 | platform_window.on_moved(Box::new({ |
| 1909 | let mut cx = cx.to_async(); |
| 1910 | move || { |
| 1911 | handle |
| 1912 | .update(&mut cx, |_, window, cx| window.bounds_changed(cx)) |
| 1913 | .log_err(); |
| 1914 | } |
| 1915 | })); |
| 1916 | platform_window.on_appearance_changed(Box::new({ |
| 1917 | let cx = cx.to_async(); |
| 1918 | let foreground_executor = cx.foreground_executor().clone(); |
| 1919 | move || { |
| 1920 | let mut cx = cx.clone(); |
| 1921 | // Defer the update because changing the AppKit appearance may |
| 1922 | // synchronously invoke this callback while App is already borrowed. |
| 1923 | foreground_executor |
| 1924 | .spawn(async move { |
| 1925 | handle |
| 1926 | .update(&mut cx, |_, window, cx| window.appearance_changed(cx)) |
| 1927 | .log_err(); |
| 1928 | }) |
| 1929 | .detach(); |
| 1930 | } |
| 1931 | })); |
| 1932 | platform_window.on_button_layout_changed(Box::new({ |
| 1933 | let mut cx = cx.to_async(); |
| 1934 | move || { |
| 1935 | handle |
| 1936 | .update(&mut cx, |_, window, cx| window.button_layout_changed(cx)) |
| 1937 | .log_err(); |
| 1938 | } |
| 1939 | })); |
| 1940 | platform_window.on_active_status_change(Box::new({ |
| 1941 | let mut cx = cx.to_async(); |
| 1942 | move |active| { |
| 1943 | handle |
| 1944 | .update(&mut cx, |_, window, cx| { |
| 1945 | window.active.set(active); |
| 1946 | window.modifiers = window.platform_window.modifiers(); |
| 1947 | window.capslock = window.platform_window.capslock(); |
| 1948 | window |
| 1949 | .activation_observers |
| 1950 | .clone() |
| 1951 | .retain(&(), |callback| callback(window, cx)); |
| 1952 | |
| 1953 | window.bounds_changed(cx); |
| 1954 | window.refresh(); |
| 1955 | |
| 1956 | SystemWindowTabController::update_last_active(cx, window.handle.id); |
| 1957 | }) |
| 1958 | .log_err(); |
| 1959 | } |
| 1960 | })); |
| 1961 | platform_window.on_visibility_change(Box::new({ |
| 1962 | let mut cx = cx.to_async(); |
| 1963 | move |_| { |
| 1964 | handle |
| 1965 | .update(&mut cx, |_, window, cx| { |
| 1966 | window.refresh_visibility(cx); |
| 1967 | }) |
| 1968 | .log_err(); |
| 1969 | } |
| 1970 | })); |
| 1971 | platform_window.on_hover_status_change(Box::new({ |
| 1972 | let mut cx = cx.to_async(); |
| 1973 | move |active| { |
| 1974 | handle |
| 1975 | .update(&mut cx, |_, window, _| { |
| 1976 | window.hovered.set(active); |
| 1977 | window.refresh(); |
| 1978 | }) |
| 1979 | .log_err(); |
| 1980 | } |
| 1981 | })); |
| 1982 | platform_window.on_input({ |
| 1983 | let mut cx = cx.to_async(); |
| 1984 | Box::new(move |event| { |
| 1985 | handle |
| 1986 | .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx)) |
| 1987 | .log_err() |
| 1988 | .unwrap_or(DispatchEventResult::default()) |
| 1989 | }) |
| 1990 | }); |
| 1991 | platform_window.on_hit_test_window_control({ |
| 1992 | let mut cx = cx.to_async(); |
| 1993 | Box::new(move || { |
| 1994 | handle |
| 1995 | .update(&mut cx, |_, window, _cx| { |
| 1996 | for (area, hitbox) in &window.rendered_frame.window_control_hitboxes { |
| 1997 | if window.mouse_hit_test.ids.contains(&hitbox.id) { |
| 1998 | return Some(*area); |
| 1999 | } |
| 2000 | } |
| 2001 | None |
| 2002 | }) |
| 2003 | .log_err() |
| 2004 | .unwrap_or(None) |
| 2005 | }) |
| 2006 | }); |
| 2007 | platform_window.on_move_tab_to_new_window({ |
| 2008 | let mut cx = cx.to_async(); |
| 2009 | Box::new(move || { |
| 2010 | handle |
| 2011 | .update(&mut cx, |_, _window, cx| { |
| 2012 | SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id()); |
| 2013 | }) |
| 2014 | .log_err(); |
| 2015 | }) |
| 2016 | }); |
| 2017 | platform_window.on_merge_all_windows({ |
| 2018 | let mut cx = cx.to_async(); |
| 2019 | Box::new(move || { |
| 2020 | handle |
| 2021 | .update(&mut cx, |_, _window, cx| { |
| 2022 | SystemWindowTabController::merge_all_windows(cx, handle.window_id()); |
| 2023 | }) |
| 2024 | .log_err(); |
| 2025 | }) |
| 2026 | }); |
| 2027 | platform_window.on_select_next_tab({ |
| 2028 | let mut cx = cx.to_async(); |
| 2029 | Box::new(move || { |
| 2030 | handle |
| 2031 | .update(&mut cx, |_, _window, cx| { |
| 2032 | SystemWindowTabController::select_next_tab(cx, handle.window_id()); |
| 2033 | }) |
| 2034 | .log_err(); |
| 2035 | }) |
| 2036 | }); |
| 2037 | platform_window.on_select_previous_tab({ |
| 2038 | let mut cx = cx.to_async(); |
| 2039 | Box::new(move || { |
| 2040 | handle |
| 2041 | .update(&mut cx, |_, _window, cx| { |
| 2042 | SystemWindowTabController::select_previous_tab(cx, handle.window_id()) |
| 2043 | }) |
| 2044 | .log_err(); |
| 2045 | }) |
| 2046 | }); |
| 2047 | platform_window.on_toggle_tab_bar({ |
| 2048 | let mut cx = cx.to_async(); |
| 2049 | Box::new(move || { |
| 2050 | handle |
| 2051 | .update(&mut cx, |_, window, cx| { |
| 2052 | let tab_bar_visible = window.platform_window.tab_bar_visible(); |
| 2053 | SystemWindowTabController::set_visible(cx, tab_bar_visible); |
| 2054 | }) |
| 2055 | .log_err(); |
| 2056 | }) |
| 2057 | }); |
| 2058 | |
| 2059 | if let Some(app_id) = app_id { |
| 2060 | platform_window.set_app_id(&app_id); |
| 2061 | } |
| 2062 | |
| 2063 | platform_window.map_window().unwrap(); |
| 2064 | |
| 2065 | Ok(Window { |
| 2066 | handle, |
| 2067 | invalidator, |
| 2068 | removed: false, |
| 2069 | platform_window, |
| 2070 | display_id, |
| 2071 | is_resizable, |
| 2072 | is_minimizable, |
| 2073 | sprite_atlas, |
| 2074 | text_system, |
| 2075 | text_rendering_mode: cx.text_rendering_mode.clone(), |
| 2076 | rem_size: px(16.), |
| 2077 | rem_size_override_stack: SmallVec::new(), |
| 2078 | viewport_size: content_size, |
| 2079 | layout_engine: Some(TaffyLayoutEngine::new()), |
| 2080 | root: None, |
| 2081 | element_id_stack: SmallVec::default(), |
| 2082 | text_style_stack: Vec::new(), |
| 2083 | rendered_entity_stack: Vec::new(), |
| 2084 | element_offset_stack: Vec::new(), |
| 2085 | content_mask_stack: Vec::new(), |
| 2086 | element_opacity: 1.0, |
| 2087 | requested_autoscroll: None, |
| 2088 | last_text_input_configuration: None, |
| 2089 | focused_text_input_active: false, |
| 2090 | rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())), |
| 2091 | next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())), |
| 2092 | next_frame_callbacks, |
| 2093 | next_hitbox_id: HitboxId(0), |
| 2094 | next_tooltip_id: TooltipId::default(), |
| 2095 | tooltip_bounds: None, |
| 2096 | dirty_views: FxHashSet::default(), |
| 2097 | focus_listeners: SubscriberSet::new(), |
| 2098 | focus_lost_listeners: SubscriberSet::new(), |
| 2099 | focus_lost_path: SmallVec::new(), |
| 2100 | default_prevented: true, |
| 2101 | mouse_position, |
| 2102 | mouse_hit_test: HitTest::default(), |
| 2103 | modifiers, |
| 2104 | capslock, |
| 2105 | scale_factor, |
| 2106 | bounds_observers: SubscriberSet::new(), |
| 2107 | appearance, |
| 2108 | appearance_observers: SubscriberSet::new(), |
| 2109 | button_layout_observers: SubscriberSet::new(), |
| 2110 | active, |
| 2111 | visibility, |
| 2112 | visibility_observers: SubscriberSet::new(), |
| 2113 | hovered, |
| 2114 | needs_present, |
| 2115 | input_rate_tracker, |
| 2116 | #[cfg(feature = "profiler")] |
| 2117 | window_profiler: profiler::WindowProfiler::new(handle.window_id())?, |
| 2118 | last_input_modality: InputModality::Mouse, |
| 2119 | touch_gestures: TouchGestureRecognizer::new( |
| 2120 | cx.platform |
| 2121 | .gestures() |
| 2122 | .map_or_else(GestureTuning::default, |gestures| gestures.tuning()), |
| 2123 | ), |
| 2124 | touch_prediction_enabled: true, |
| 2125 | long_press_timer: None, |
| 2126 | long_press_capture: None, |
| 2127 | refreshing: false, |
| 2128 | activation_observers: SubscriberSet::new(), |
| 2129 | focus: None, |
| 2130 | focus_enabled: true, |
| 2131 | focus_generation: 0, |
| 2132 | pending_input: None, |
| 2133 | pending_modifier: ModifierState::default(), |
| 2134 | pending_input_observers: SubscriberSet::new(), |
| 2135 | prompt: None, |
| 2136 | client_inset: None, |
| 2137 | image_cache_stack: Vec::new(), |
| 2138 | captured_hitbox: None, |
| 2139 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 2140 | inspector: None, |
| 2141 | #[cfg(feature = "profiler")] |
| 2142 | debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay::new(), |
| 2143 | a11y: A11y::new( |
| 2144 | a11y_active_flag, |
| 2145 | accessibility_force_disabled, |
| 2146 | initial_window_title, |
| 2147 | ), |
| 2148 | }) |
| 2149 | } |
| 2150 | |
| 2151 | pub(crate) fn new_focus_listener( |
| 2152 | &self, |
| 2153 | value: AnyWindowFocusListener, |
| 2154 | ) -> (Subscription, impl FnOnce() + use<>) { |
| 2155 | self.focus_listeners.insert((), value) |
| 2156 | } |
| 2157 | } |
| 2158 | |
| 2159 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 2160 | #[expect(missing_docs)] |
| 2161 | pub struct DispatchEventResult { |
| 2162 | pub propagate: bool, |
| 2163 | pub default_prevented: bool, |
| 2164 | } |
| 2165 | |
| 2166 | /// Indicates which region of the window is visible. Content falling outside of this mask will not be |
| 2167 | /// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type |
| 2168 | /// to leave room to support more complex shapes in the future. |
| 2169 | #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] |
| 2170 | #[repr(C)] |
| 2171 | pub struct ContentMask<P: Clone + Debug + Default + PartialEq> { |
| 2172 | /// The bounds |
| 2173 | pub bounds: Bounds<P>, |
| 2174 | } |
| 2175 | |
| 2176 | impl ContentMask<Pixels> { |
| 2177 | /// Scale the content mask's pixel units by the given scaling factor. |
| 2178 | pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> { |
| 2179 | ContentMask { |
| 2180 | bounds: self.bounds.scale(factor), |
| 2181 | } |
| 2182 | } |
| 2183 | |
| 2184 | /// Intersect the content mask with the given content mask. |
| 2185 | pub fn intersect(&self, other: &Self) -> Self { |
| 2186 | let bounds = self.bounds.intersect(&other.bounds); |
| 2187 | ContentMask { bounds } |
| 2188 | } |
| 2189 | } |
| 2190 | |
| 2191 | impl Window { |
| 2192 | fn mark_view_dirty(&mut self, view_id: EntityId) { |
| 2193 | // Mark ancestor views as dirty. If already in the `dirty_views` set, then all its ancestors |
| 2194 | // should already be dirty. |
| 2195 | for view_id in self |
| 2196 | .rendered_frame |
| 2197 | .dispatch_tree |
| 2198 | .view_path_reversed(view_id) |
| 2199 | { |
| 2200 | if !self.dirty_views.insert(view_id) { |
| 2201 | break; |
| 2202 | } |
| 2203 | } |
| 2204 | } |
| 2205 | |
| 2206 | pub(crate) fn refresh_visibility(&mut self, cx: &mut App) { |
| 2207 | let visibility = self.platform_window.visibility(); |
| 2208 | if self.visibility != visibility { |
| 2209 | self.visibility = visibility; |
| 2210 | #[cfg(feature = "profiler")] |
| 2211 | profiler::journal::record_window_visibility(self.handle.window_id(), visibility); |
| 2212 | self.visibility_observers |
| 2213 | .clone() |
| 2214 | .retain(&(), |callback| callback(visibility, self, cx)); |
| 2215 | } |
| 2216 | #[cfg(feature = "profiler")] |
| 2217 | if self.invalidator.is_dirty() || self.needs_present.get() { |
| 2218 | profiler::journal::record_frame_pending(self.handle.window_id(), Instant::now()); |
| 2219 | } |
| 2220 | } |
| 2221 | |
| 2222 | /// Whether the platform is presenting this window's frames (see |
| 2223 | /// [`WindowVisibility`]). |
| 2224 | pub fn visibility(&self) -> WindowVisibility { |
| 2225 | self.visibility |
| 2226 | } |
| 2227 | |
| 2228 | /// Whether frames drawn for this window will be shown. |
| 2229 | /// |
| 2230 | /// This is not the window's shown/hidden state: a shown window that is |
| 2231 | /// fully behind another window, minimized, or on a sleeping display is not |
| 2232 | /// visible here. |
| 2233 | pub fn is_visible(&self) -> bool { |
| 2234 | self.visibility.is_visible() |
| 2235 | } |
| 2236 | |
| 2237 | /// Registers a callback to be invoked when the window's visibility changes. |
| 2238 | pub fn observe_window_visibility( |
| 2239 | &self, |
| 2240 | mut callback: impl FnMut(WindowVisibility, &mut Window, &mut App) + 'static, |
| 2241 | ) -> Subscription { |
| 2242 | let (subscription, activate) = self.visibility_observers.insert( |
| 2243 | (), |
| 2244 | Box::new(move |visibility, window, cx| { |
| 2245 | callback(visibility, window, cx); |
| 2246 | true |
| 2247 | }), |
| 2248 | ); |
| 2249 | activate(); |
| 2250 | subscription |
| 2251 | } |
| 2252 | |
| 2253 | /// Registers a callback to be invoked when the window appearance changes. |
| 2254 | pub fn observe_window_appearance( |
| 2255 | &self, |
| 2256 | mut callback: impl FnMut(&mut Window, &mut App) + 'static, |
| 2257 | ) -> Subscription { |
| 2258 | let (subscription, activate) = self.appearance_observers.insert( |
| 2259 | (), |
| 2260 | Box::new(move |window, cx| { |
| 2261 | callback(window, cx); |
| 2262 | true |
| 2263 | }), |
| 2264 | ); |
| 2265 | activate(); |
| 2266 | subscription |
| 2267 | } |
| 2268 | |
| 2269 | /// Registers a callback to be invoked when the window button layout changes. |
| 2270 | pub fn observe_button_layout_changed( |
| 2271 | &self, |
| 2272 | mut callback: impl FnMut(&mut Window, &mut App) + 'static, |
| 2273 | ) -> Subscription { |
| 2274 | let (subscription, activate) = self.button_layout_observers.insert( |
| 2275 | (), |
| 2276 | Box::new(move |window, cx| { |
| 2277 | callback(window, cx); |
| 2278 | true |
| 2279 | }), |
| 2280 | ); |
| 2281 | activate(); |
| 2282 | subscription |
| 2283 | } |
| 2284 | |
| 2285 | /// Replaces the root entity of the window with a new one. |
| 2286 | pub fn replace_root<E>( |
| 2287 | &mut self, |
| 2288 | cx: &mut App, |
| 2289 | build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E, |
| 2290 | ) -> Entity<E> |
| 2291 | where |
| 2292 | E: 'static + Render, |
| 2293 | { |
| 2294 | let view = cx.new(|cx| build_view(self, cx)); |
| 2295 | self.root = Some(view.clone().into()); |
| 2296 | self.refresh(); |
| 2297 | view |
| 2298 | } |
| 2299 | |
| 2300 | /// Returns the root entity of the window, if it has one. |
| 2301 | pub fn root<E>(&self) -> Option<Option<Entity<E>>> |
| 2302 | where |
| 2303 | E: 'static + Render, |
| 2304 | { |
| 2305 | self.root |
| 2306 | .as_ref() |
| 2307 | .map(|view| view.clone().downcast::<E>().ok()) |
| 2308 | } |
| 2309 | |
| 2310 | /// Obtain a handle to the window that belongs to this context. |
| 2311 | pub fn window_handle(&self) -> AnyWindowHandle { |
| 2312 | self.handle |
| 2313 | } |
| 2314 | |
| 2315 | /// Mark the window as dirty, scheduling it to be redrawn on the next frame. |
| 2316 | pub fn refresh(&mut self) { |
| 2317 | if self.invalidator.not_drawing() { |
| 2318 | self.refreshing = true; |
| 2319 | self.invalidator.set_dirty(true); |
| 2320 | } |
| 2321 | } |
| 2322 | |
| 2323 | /// Close this window. |
| 2324 | pub fn remove_window(&mut self) { |
| 2325 | self.removed = true; |
| 2326 | } |
| 2327 | |
| 2328 | /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`. |
| 2329 | pub fn focused(&self, cx: &App) -> Option<FocusHandle> { |
| 2330 | self.focus |
| 2331 | .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles)) |
| 2332 | } |
| 2333 | |
| 2334 | /// While focus-lost listeners are being dispatched, returns the closest ancestor of the |
| 2335 | /// previously focused element that can still receive focus, making it a suitable target |
| 2336 | /// for focus restoration. Returns `None` at all other times, or when no such ancestor exists. |
| 2337 | pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> { |
| 2338 | let (_leaf, ancestors) = self.focus_lost_path.split_last()?; |
| 2339 | ancestors.iter().rev().find_map(|id| { |
| 2340 | self.rendered_frame.dispatch_tree.focusable_node_id(*id)?; |
| 2341 | FocusHandle::for_id(*id, &cx.focus_handles) |
| 2342 | }) |
| 2343 | } |
| 2344 | |
| 2345 | /// Move focus to the element associated with the given [`FocusHandle`]. |
| 2346 | pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) { |
| 2347 | if !self.focus_enabled || self.focus == Some(handle.id) { |
| 2348 | return; |
| 2349 | } |
| 2350 | |
| 2351 | self.focus = Some(handle.id); |
| 2352 | self.focus_generation = self.focus_generation.wrapping_add(1); |
| 2353 | self.clear_pending_keystrokes(cx); |
| 2354 | |
| 2355 | self.refresh(); |
| 2356 | } |
| 2357 | |
| 2358 | /// Remove focus from all elements within this context's window. |
| 2359 | pub fn blur(&mut self, cx: &mut App) { |
| 2360 | self.clear_pending_keystrokes(cx); |
| 2361 | |
| 2362 | if !self.focus_enabled { |
| 2363 | return; |
| 2364 | } |
| 2365 | |
| 2366 | if self.focus.is_some() { |
| 2367 | self.focus_generation = self.focus_generation.wrapping_add(1); |
| 2368 | } |
| 2369 | self.focus = None; |
| 2370 | self.refresh(); |
| 2371 | } |
| 2372 | |
| 2373 | /// Blur the window and don't allow anything in it to be focused again. |
| 2374 | pub fn disable_focus(&mut self, cx: &mut App) { |
| 2375 | self.blur(cx); |
| 2376 | self.focus_enabled = false; |
| 2377 | } |
| 2378 | |
| 2379 | /// Move focus to next tab stop. |
| 2380 | pub fn focus_next(&mut self, cx: &mut App) { |
| 2381 | if !self.focus_enabled { |
| 2382 | return; |
| 2383 | } |
| 2384 | |
| 2385 | if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) { |
| 2386 | self.focus(&handle, cx) |
| 2387 | } |
| 2388 | } |
| 2389 | |
| 2390 | /// Move focus to previous tab stop. |
| 2391 | pub fn focus_prev(&mut self, cx: &mut App) { |
| 2392 | if !self.focus_enabled { |
| 2393 | return; |
| 2394 | } |
| 2395 | |
| 2396 | if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) { |
| 2397 | self.focus(&handle, cx) |
| 2398 | } |
| 2399 | } |
| 2400 | |
| 2401 | /// Accessor for the text system. |
| 2402 | pub fn text_system(&self) -> &Arc<WindowTextSystem> { |
| 2403 | &self.text_system |
| 2404 | } |
| 2405 | |
| 2406 | /// The current text style. Which is composed of all the style refinements provided to `with_text_style`. |
| 2407 | pub fn text_style(&self) -> TextStyle { |
| 2408 | let mut style = TextStyle::default(); |
| 2409 | for refinement in &self.text_style_stack { |
| 2410 | style.refine(refinement); |
| 2411 | } |
| 2412 | style |
| 2413 | } |
| 2414 | |
| 2415 | /// Check if the platform window is maximized. |
| 2416 | /// |
| 2417 | /// On some platforms (namely Windows) this is different than the bounds being the size of the display |
| 2418 | pub fn is_maximized(&self) -> bool { |
| 2419 | self.platform_window.is_maximized() |
| 2420 | } |
| 2421 | |
| 2422 | /// request a certain window decoration (Wayland) |
| 2423 | pub fn request_decorations(&self, decorations: WindowDecorations) { |
| 2424 | self.platform_window.request_decorations(decorations); |
| 2425 | } |
| 2426 | |
| 2427 | /// Set the exclusive zone for a layer-shell surface: how much screen space it |
| 2428 | /// reserves so other surfaces avoid occluding it (e.g. a panel reserving space). |
| 2429 | /// Positive values reserve that distance from the anchored edge, 0 lets the |
| 2430 | /// surface be moved out of others' exclusive zones, and -1 ignores reserved |
| 2431 | /// space and may extend under other surfaces. (Wayland layer-shell windows only) |
| 2432 | pub fn set_exclusive_zone(&self, zone: Pixels) { |
| 2433 | self.platform_window.set_exclusive_zone(zone); |
| 2434 | } |
| 2435 | |
| 2436 | /// Set which anchored edge a layer-shell surface's exclusive zone applies to. |
| 2437 | /// This is only needed to disambiguate a corner-anchored surface; otherwise the |
| 2438 | /// edge is deduced from the anchor. The edge must be a single edge the surface |
| 2439 | /// is anchored to, or it is ignored. (Wayland layer-shell windows only) |
| 2440 | #[cfg(all(target_os = "linux", feature = "wayland"))] |
| 2441 | pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) { |
| 2442 | self.platform_window.set_exclusive_edge(edge); |
| 2443 | } |
| 2444 | |
| 2445 | /// Start an interactive window resize operation if this window is resizable. |
| 2446 | pub fn start_window_resize(&self, edge: ResizeEdge) { |
| 2447 | if self.is_resizable { |
| 2448 | self.platform_window.start_window_resize(edge); |
| 2449 | } |
| 2450 | } |
| 2451 | |
| 2452 | /// Linux (wayland) only: Set the window's input region, the area that receives pointer |
| 2453 | /// and touch input. Events outside it pass through to whatever is below the window. |
| 2454 | /// |
| 2455 | /// - `Some(rects)` restricts input to the union of `rects`, in window coordinates. |
| 2456 | /// - `Some(&[])` is an empty region, so the window receives no pointer or touch input. |
| 2457 | /// - `None` resets the region to the default, so the whole window receives input again. |
| 2458 | pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) { |
| 2459 | self.platform_window.set_input_region(region); |
| 2460 | } |
| 2461 | |
| 2462 | /// Return the `WindowBounds` to indicate that how a window should be opened |
| 2463 | /// after it has been closed |
| 2464 | pub fn window_bounds(&self) -> WindowBounds { |
| 2465 | self.platform_window.window_bounds() |
| 2466 | } |
| 2467 | |
| 2468 | /// Return the `WindowBounds` excluding insets (Wayland and X11) |
| 2469 | pub fn inner_window_bounds(&self) -> WindowBounds { |
| 2470 | self.platform_window.inner_window_bounds() |
| 2471 | } |
| 2472 | |
| 2473 | /// Encode the window's native restorable state into an opaque blob. |
| 2474 | /// Returns `None` on platforms without native state restoration or if encoding fails. |
| 2475 | pub fn native_window_state(&self) -> Option<Vec<u8>> { |
| 2476 | self.platform_window.native_window_state() |
| 2477 | } |
| 2478 | |
| 2479 | /// Restore the window's native state from a blob previously produced |
| 2480 | /// by [`Window::native_window_state`]. A no-op on platforms without native state restoration. |
| 2481 | pub fn restore_native_window_state(&self, state: &[u8]) { |
| 2482 | self.platform_window.restore_native_window_state(state); |
| 2483 | } |
| 2484 | |
| 2485 | /// Dispatch the given action on the currently focused element. |
| 2486 | pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) { |
| 2487 | let focus_id = self.focused(cx).map(|handle| handle.id); |
| 2488 | |
| 2489 | let window = self.handle; |
| 2490 | cx.defer(move |cx| { |
| 2491 | window |
| 2492 | .update(cx, |_, window, cx| { |
| 2493 | let node_id = window.focus_node_id_in_rendered_frame(focus_id); |
| 2494 | window.dispatch_action_on_node(node_id, action.as_ref(), cx); |
| 2495 | }) |
| 2496 | .log_err(); |
| 2497 | }) |
| 2498 | } |
| 2499 | |
| 2500 | pub(crate) fn dispatch_keystroke_observers( |
| 2501 | &mut self, |
| 2502 | keystroke: &Keystroke, |
| 2503 | input_preference: InputPreference, |
| 2504 | action: Option<&dyn Action>, |
| 2505 | context_stack: Vec<KeyContext>, |
| 2506 | cx: &mut App, |
| 2507 | ) { |
| 2508 | cx.keystroke_observers.clone().retain(&(), move |callback| { |
| 2509 | (callback)( |
| 2510 | &KeystrokeEvent { |
| 2511 | keystroke: keystroke.clone(), |
| 2512 | input_preference, |
| 2513 | action: action.map(|action| action.boxed_clone()), |
| 2514 | context_stack: context_stack.clone(), |
| 2515 | }, |
| 2516 | self, |
| 2517 | cx, |
| 2518 | ) |
| 2519 | }); |
| 2520 | } |
| 2521 | |
| 2522 | pub(crate) fn dispatch_keystroke_interceptors( |
| 2523 | &mut self, |
| 2524 | keystroke: &Keystroke, |
| 2525 | input_preference: InputPreference, |
| 2526 | context_stack: Vec<KeyContext>, |
| 2527 | cx: &mut App, |
| 2528 | ) { |
| 2529 | cx.keystroke_interceptors |
| 2530 | .clone() |
| 2531 | .retain(&(), move |callback| { |
| 2532 | (callback)( |
| 2533 | &KeystrokeEvent { |
| 2534 | keystroke: keystroke.clone(), |
| 2535 | input_preference, |
| 2536 | action: None, |
| 2537 | context_stack: context_stack.clone(), |
| 2538 | }, |
| 2539 | self, |
| 2540 | cx, |
| 2541 | ) |
| 2542 | }); |
| 2543 | } |
| 2544 | |
| 2545 | /// Schedules the given function to be run at the end of the current effect cycle, allowing entities |
| 2546 | /// that are currently on the stack to be returned to the app. |
| 2547 | pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) { |
| 2548 | let handle = self.handle; |
| 2549 | cx.defer(move |cx| { |
| 2550 | handle.update(cx, |_, window, cx| f(window, cx)).ok(); |
| 2551 | }); |
| 2552 | } |
| 2553 | |
| 2554 | /// Subscribe to events emitted by a entity. |
| 2555 | /// The entity to which you're subscribing must implement the [`EventEmitter`] trait. |
| 2556 | /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window. |
| 2557 | pub fn observe<T: 'static>( |
| 2558 | &mut self, |
| 2559 | observed: &Entity<T>, |
| 2560 | cx: &mut App, |
| 2561 | mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static, |
| 2562 | ) -> Subscription { |
| 2563 | let entity_id = observed.entity_id(); |
| 2564 | let observed = observed.downgrade(); |
| 2565 | let window_handle = self.handle; |
| 2566 | cx.new_observer( |
| 2567 | entity_id, |
| 2568 | Box::new(move |cx| { |
| 2569 | window_handle |
| 2570 | .update(cx, |_, window, cx| { |
| 2571 | if let Some(handle) = observed.upgrade() { |
| 2572 | on_notify(handle, window, cx); |
| 2573 | true |
| 2574 | } else { |
| 2575 | false |
| 2576 | } |
| 2577 | }) |
| 2578 | .unwrap_or(false) |
| 2579 | }), |
| 2580 | ) |
| 2581 | } |
| 2582 | |
| 2583 | /// Subscribe to events emitted by a entity. |
| 2584 | /// The entity to which you're subscribing must implement the [`EventEmitter`] trait. |
| 2585 | /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window. |
| 2586 | pub fn subscribe<Emitter, Evt>( |
| 2587 | &mut self, |
| 2588 | entity: &Entity<Emitter>, |
| 2589 | cx: &mut App, |
| 2590 | mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static, |
| 2591 | ) -> Subscription |
| 2592 | where |
| 2593 | Emitter: EventEmitter<Evt>, |
| 2594 | Evt: 'static, |
| 2595 | { |
| 2596 | let entity_id = entity.entity_id(); |
| 2597 | let handle = entity.downgrade(); |
| 2598 | let window_handle = self.handle; |
| 2599 | cx.new_subscription( |
| 2600 | entity_id, |
| 2601 | ( |
| 2602 | TypeId::of::<Evt>(), |
| 2603 | Box::new(move |event, cx| { |
| 2604 | window_handle |
| 2605 | .update(cx, |_, window, cx| { |
| 2606 | if let Some(entity) = handle.upgrade() { |
| 2607 | let event = event.downcast_ref().expect("invalid event type"); |
| 2608 | on_event(entity, event, window, cx); |
| 2609 | true |
| 2610 | } else { |
| 2611 | false |
| 2612 | } |
| 2613 | }) |
| 2614 | .unwrap_or(false) |
| 2615 | }), |
| 2616 | ), |
| 2617 | ) |
| 2618 | } |
| 2619 | |
| 2620 | /// Register a callback to be invoked when the given `Entity` is released. |
| 2621 | pub fn observe_release<T>( |
| 2622 | &self, |
| 2623 | entity: &Entity<T>, |
| 2624 | cx: &mut App, |
| 2625 | mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static, |
| 2626 | ) -> Subscription |
| 2627 | where |
| 2628 | T: 'static, |
| 2629 | { |
| 2630 | let entity_id = entity.entity_id(); |
| 2631 | let window_handle = self.handle; |
| 2632 | let (subscription, activate) = cx.release_listeners.insert( |
| 2633 | entity_id, |
| 2634 | Box::new(move |entity, cx| { |
| 2635 | let entity = entity.downcast_mut().expect("invalid entity type"); |
| 2636 | let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx)); |
| 2637 | }), |
| 2638 | ); |
| 2639 | activate(); |
| 2640 | subscription |
| 2641 | } |
| 2642 | |
| 2643 | /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across |
| 2644 | /// await points in async code. |
| 2645 | pub fn to_async(&self, cx: &App) -> AsyncWindowContext { |
| 2646 | AsyncWindowContext::new_context(cx.to_async(), self.handle) |
| 2647 | } |
| 2648 | |
| 2649 | /// Schedule the given closure to be run directly after the current frame is rendered. |
| 2650 | pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) { |
| 2651 | RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback)); |
| 2652 | self.platform_window.schedule_frame(); |
| 2653 | // Next-frame callbacks create frame demand without dirtying the |
| 2654 | // window, so the platform's frame source must be woken explicitly. |
| 2655 | self.invalidator.wake_platform(); |
| 2656 | } |
| 2657 | |
| 2658 | /// Schedule a frame to be drawn on the next animation frame. |
| 2659 | /// |
| 2660 | /// This is useful for elements that need to animate continuously, such as a video player or an animated GIF. |
| 2661 | /// It will cause the window to redraw on the next frame, even if no other changes have occurred. |
| 2662 | /// |
| 2663 | /// If called from within a view, it will notify that view on the next frame. Otherwise, it will refresh the entire window. |
| 2664 | /// |
| 2665 | /// Callers driving purely decorative animations (spinners, pulses, and the |
| 2666 | /// like) should prefer [`AnimationExt::with_animation`](crate::AnimationExt::with_animation), |
| 2667 | /// which automatically respects [`App::reduce_motion`]. When using this |
| 2668 | /// method directly for decorative motion, check [`App::reduce_motion`] |
| 2669 | /// and skip the frame request when it is set. |
| 2670 | pub fn request_animation_frame(&self) { |
| 2671 | let entity = self.current_view(); |
| 2672 | self.on_next_frame(move |_, cx| cx.notify(entity)); |
| 2673 | } |
| 2674 | |
| 2675 | /// Runs all callbacks scheduled via [`Self::on_next_frame`], returning how many ran. |
| 2676 | /// |
| 2677 | /// Tests have no platform frame loop, so this simulates the delivery of the |
| 2678 | /// next frame. |
| 2679 | #[cfg(any(test, feature = "test-support"))] |
| 2680 | pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize { |
| 2681 | let callbacks = self.next_frame_callbacks.take(); |
| 2682 | let count = callbacks.len(); |
| 2683 | for callback in callbacks { |
| 2684 | callback(self, cx); |
| 2685 | } |
| 2686 | count |
| 2687 | } |
| 2688 | |
| 2689 | /// Spawn the future returned by the given closure on the application thread pool. |
| 2690 | /// The closure is provided a handle to the current window and an `AsyncWindowContext` for |
| 2691 | /// use within your future. |
| 2692 | #[track_caller] |
| 2693 | pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R> |
| 2694 | where |
| 2695 | R: 'static, |
| 2696 | AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static, |
| 2697 | { |
| 2698 | let handle = self.handle; |
| 2699 | cx.spawn(async move |app| { |
| 2700 | let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle); |
| 2701 | f(&mut async_window_cx).await |
| 2702 | }) |
| 2703 | } |
| 2704 | |
| 2705 | /// Spawn the future returned by the given closure on the application thread |
| 2706 | /// pool, with the given priority. The closure is provided a handle to the |
| 2707 | /// current window and an `AsyncWindowContext` for use within your future. |
| 2708 | #[track_caller] |
| 2709 | pub fn spawn_with_priority<AsyncFn, R>( |
| 2710 | &self, |
| 2711 | priority: Priority, |
| 2712 | cx: &App, |
| 2713 | f: AsyncFn, |
| 2714 | ) -> Task<R> |
| 2715 | where |
| 2716 | R: 'static, |
| 2717 | AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static, |
| 2718 | { |
| 2719 | let handle = self.handle; |
| 2720 | cx.spawn_with_priority(priority, async move |app| { |
| 2721 | let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle); |
| 2722 | f(&mut async_window_cx).await |
| 2723 | }) |
| 2724 | } |
| 2725 | |
| 2726 | /// Notify the window that its bounds have changed. |
| 2727 | /// |
| 2728 | /// This updates internal state like `viewport_size` and `scale_factor` from |
| 2729 | /// the platform window, then notifies observers. Normally called automatically |
| 2730 | /// by the platform's resize callback, but exposed publicly for test infrastructure. |
| 2731 | pub fn bounds_changed(&mut self, cx: &mut App) { |
| 2732 | self.scale_factor = self.platform_window.scale_factor(); |
| 2733 | self.viewport_size = self.platform_window.content_size(); |
| 2734 | self.display_id = self.platform_window.display().map(|display| display.id()); |
| 2735 | self.mouse_position = self.platform_window.mouse_position(); |
| 2736 | |
| 2737 | self.refresh(); |
| 2738 | |
| 2739 | self.bounds_observers |
| 2740 | .clone() |
| 2741 | .retain(&(), |callback| callback(self, cx)); |
| 2742 | } |
| 2743 | |
| 2744 | /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays. |
| 2745 | pub fn bounds(&self) -> Bounds<Pixels> { |
| 2746 | self.platform_window.bounds() |
| 2747 | } |
| 2748 | |
| 2749 | /// Renders the current frame's scene to a texture and returns the pixel data as an RGBA image. |
| 2750 | /// This does not present the frame to screen - useful for visual testing where we want |
| 2751 | /// to capture what would be rendered without displaying it or requiring the window to be visible. |
| 2752 | #[cfg(any(test, feature = "test-support"))] |
| 2753 | pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> { |
| 2754 | self.platform_window |
| 2755 | .render_to_image(&self.rendered_frame.scene) |
| 2756 | } |
| 2757 | |
| 2758 | /// Returns the quads in the most recently rendered frame's scene, so tests can assert on |
| 2759 | /// painted output without rasterizing the frame. Quad bounds are in scaled pixels and are |
| 2760 | /// not clipped; each quad carries the content mask it will be clipped to when drawn. Quads |
| 2761 | /// whose bounds don't intersect their content mask are culled at paint time and won't appear. |
| 2762 | #[cfg(any(test, feature = "test-support"))] |
| 2763 | pub fn painted_quads(&self) -> Vec<Quad> { |
| 2764 | self.rendered_frame.scene.quads.clone() |
| 2765 | } |
| 2766 | |
| 2767 | /// Returns the underlines in the most recently rendered frame's scene. |
| 2768 | #[cfg(any(test, feature = "test-support"))] |
| 2769 | pub fn painted_underlines(&self) -> Vec<Underline> { |
| 2770 | self.rendered_frame.scene.underlines.clone() |
| 2771 | } |
| 2772 | |
| 2773 | /// Set the content size of the window. |
| 2774 | pub fn resize(&mut self, size: Size<Pixels>) { |
| 2775 | self.platform_window.resize(size); |
| 2776 | } |
| 2777 | |
| 2778 | /// Returns whether or not the window is currently fullscreen |
| 2779 | pub fn is_fullscreen(&self) -> bool { |
| 2780 | self.platform_window.is_fullscreen() |
| 2781 | } |
| 2782 | |
| 2783 | /// Returns whether the window is currently in simple (borderless) fullscreen, |
| 2784 | /// where it covers the entire screen including the menu bar and notch area. |
| 2785 | /// Always `false` on platforms other than macOS. |
| 2786 | pub fn is_simple_fullscreen(&self) -> bool { |
| 2787 | self.platform_window.is_simple_fullscreen() |
| 2788 | } |
| 2789 | |
| 2790 | pub(crate) fn appearance_changed(&mut self, cx: &mut App) { |
| 2791 | self.appearance = self.platform_window.appearance(); |
| 2792 | |
| 2793 | self.appearance_observers |
| 2794 | .clone() |
| 2795 | .retain(&(), |callback| callback(self, cx)); |
| 2796 | } |
| 2797 | |
| 2798 | pub(crate) fn button_layout_changed(&mut self, cx: &mut App) { |
| 2799 | self.button_layout_observers |
| 2800 | .clone() |
| 2801 | .retain(&(), |callback| callback(self, cx)); |
| 2802 | } |
| 2803 | |
| 2804 | /// Returns the appearance of the current window. |
| 2805 | pub fn appearance(&self) -> WindowAppearance { |
| 2806 | self.appearance |
| 2807 | } |
| 2808 | |
| 2809 | /// Returns the size of the drawable area within the window. |
| 2810 | pub fn viewport_size(&self) -> Size<Pixels> { |
| 2811 | self.viewport_size |
| 2812 | } |
| 2813 | |
| 2814 | /// Returns the platform's visible viewport in window-local logical pixels. |
| 2815 | /// |
| 2816 | /// Unlike `viewport_size`, this can shrink or move when the keyboard opens. |
| 2817 | /// During drawing this is a consistent frame snapshot. Outside drawing it |
| 2818 | /// reflects the latest platform sample, not a synchronous geometry query. |
| 2819 | pub fn visual_viewport_bounds(&self) -> Bounds<Pixels> { |
| 2820 | self.platform_window.visual_viewport_bounds() |
| 2821 | } |
| 2822 | |
| 2823 | /// Returns a conservative rectangle avoiding platform-known obscured content. |
| 2824 | /// |
| 2825 | /// Intersects the visual viewport with the full layout area inset by system |
| 2826 | /// safe areas and keyboard occlusion. Unknown overlays cannot be excluded. |
| 2827 | pub fn fully_visible_bounds(&self) -> Bounds<Pixels> { |
| 2828 | let insets = self.platform_window.insets().effective(); |
| 2829 | let viewport = self.viewport_size(); |
| 2830 | let left = insets.left.max(Pixels::ZERO).min(viewport.width); |
| 2831 | let top = insets.top.max(Pixels::ZERO).min(viewport.height); |
| 2832 | let right = (viewport.width - insets.right.max(Pixels::ZERO)).max(left); |
| 2833 | let bottom = (viewport.height - insets.bottom.max(Pixels::ZERO)).max(top); |
| 2834 | let safe_bounds = Bounds::from_corners(point(left, top), point(right, bottom)); |
| 2835 | let mut visible = safe_bounds.intersect(&self.visual_viewport_bounds()); |
| 2836 | visible.size.width = visible.size.width.max(Pixels::ZERO); |
| 2837 | visible.size.height = visible.size.height.max(Pixels::ZERO); |
| 2838 | visible |
| 2839 | } |
| 2840 | |
| 2841 | /// Requests the virtual keyboard for the currently focused text input. |
| 2842 | /// |
| 2843 | /// Call from a user gesture on platforms that require one. The platform may |
| 2844 | /// decline the request; this does not change focus or the layout viewport. |
| 2845 | pub fn request_virtual_keyboard(&self) { |
| 2846 | self.platform_window.show_soft_keyboard(); |
| 2847 | } |
| 2848 | |
| 2849 | /// Requests dismissal of the virtual keyboard without changing GPUI focus. |
| 2850 | pub fn dismiss_virtual_keyboard(&self) { |
| 2851 | self.platform_window.hide_soft_keyboard(); |
| 2852 | } |
| 2853 | |
| 2854 | /// Returns whether this window is focused by the operating system (receiving key events). |
| 2855 | pub fn is_window_active(&self) -> bool { |
| 2856 | self.active.get() |
| 2857 | } |
| 2858 | |
| 2859 | /// Returns whether this window is considered to be the window |
| 2860 | /// that currently owns the mouse cursor. |
| 2861 | /// On mac, this is equivalent to `is_window_active`. |
| 2862 | pub fn is_window_hovered(&self) -> bool { |
| 2863 | if cfg!(any( |
| 2864 | target_os = "windows", |
| 2865 | target_os = "linux", |
| 2866 | target_os = "freebsd" |
| 2867 | )) { |
| 2868 | self.hovered.get() |
| 2869 | } else { |
| 2870 | self.is_window_active() |
| 2871 | } |
| 2872 | } |
| 2873 | |
| 2874 | /// Toggle zoom on the window. |
| 2875 | pub fn zoom_window(&self) { |
| 2876 | self.platform_window.zoom(); |
| 2877 | } |
| 2878 | |
| 2879 | /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11) |
| 2880 | pub fn show_window_menu(&self, position: Point<Pixels>) { |
| 2881 | self.platform_window.show_window_menu(position) |
| 2882 | } |
| 2883 | |
| 2884 | /// Handle window movement for Linux and macOS. |
| 2885 | /// Tells the compositor to take control of window movement (Wayland and X11) |
| 2886 | /// |
| 2887 | /// Events may not be received during a move operation. |
| 2888 | pub fn start_window_move(&self) { |
| 2889 | self.platform_window.start_window_move() |
| 2890 | } |
| 2891 | |
| 2892 | /// When using client side decorations, set this to the width of the invisible decorations (Wayland and X11) |
| 2893 | pub fn set_client_inset(&mut self, inset: Pixels) { |
| 2894 | self.client_inset = Some(inset); |
| 2895 | self.platform_window.set_client_inset(inset); |
| 2896 | } |
| 2897 | |
| 2898 | /// Returns the client_inset value by [`Self::set_client_inset`]. |
| 2899 | pub fn client_inset(&self) -> Option<Pixels> { |
| 2900 | self.client_inset |
| 2901 | } |
| 2902 | |
| 2903 | /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11) |
| 2904 | pub fn window_decorations(&self) -> Decorations { |
| 2905 | self.platform_window.window_decorations() |
| 2906 | } |
| 2907 | |
| 2908 | /// Returns whether this window is resizable. |
| 2909 | pub fn is_resizable(&self) -> bool { |
| 2910 | self.is_resizable |
| 2911 | } |
| 2912 | |
| 2913 | /// Returns whether this window is minimizable. |
| 2914 | pub fn is_minimizable(&self) -> bool { |
| 2915 | self.is_minimizable |
| 2916 | } |
| 2917 | |
| 2918 | /// Returns the controls supported by the platform. |
| 2919 | pub fn window_controls(&self) -> WindowControls { |
| 2920 | self.platform_window.window_controls() |
| 2921 | } |
| 2922 | |
| 2923 | /// Updates the window's title at the platform level. |
| 2924 | pub fn set_window_title(&mut self, title: &str) { |
| 2925 | self.platform_window.set_title(title); |
| 2926 | self.a11y.set_window_title(title.to_string()); |
| 2927 | } |
| 2928 | |
| 2929 | /// Sets the position of the macOS traffic light buttons. |
| 2930 | #[cfg(target_os = "macos")] |
| 2931 | pub fn set_traffic_light_position(&self, position: Point<Pixels>) { |
| 2932 | self.platform_window.set_traffic_light_position(position); |
| 2933 | } |
| 2934 | |
| 2935 | /// Sets the application identifier. |
| 2936 | pub fn set_app_id(&mut self, app_id: &str) { |
| 2937 | self.platform_window.set_app_id(app_id); |
| 2938 | } |
| 2939 | |
| 2940 | /// Sets the window background appearance. |
| 2941 | pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) { |
| 2942 | self.platform_window |
| 2943 | .set_background_appearance(background_appearance); |
| 2944 | } |
| 2945 | |
| 2946 | /// Mark the window as dirty at the platform level. |
| 2947 | pub fn set_window_edited(&mut self, edited: bool) { |
| 2948 | self.platform_window.set_edited(edited); |
| 2949 | } |
| 2950 | |
| 2951 | /// Set the path of the file this window represents. |
| 2952 | /// On macOS, this sets the window's accessibility document property (AXDocument). |
| 2953 | pub fn set_document_path(&self, path: Option<&std::path::Path>) { |
| 2954 | self.platform_window.set_document_path(path); |
| 2955 | } |
| 2956 | |
| 2957 | /// Determine the display on which the window is visible. |
| 2958 | pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> { |
| 2959 | cx.platform |
| 2960 | .displays() |
| 2961 | .into_iter() |
| 2962 | .find(|display| Some(display.id()) == self.display_id) |
| 2963 | } |
| 2964 | |
| 2965 | /// Show the platform character palette. |
| 2966 | pub fn show_character_palette(&self) { |
| 2967 | self.platform_window.show_character_palette(); |
| 2968 | } |
| 2969 | |
| 2970 | /// The scale factor of the display associated with the window. For example, it could |
| 2971 | /// return 2.0 for a "retina" display, indicating that each logical pixel should actually |
| 2972 | /// be rendered as two pixels on screen. |
| 2973 | pub fn scale_factor(&self) -> f32 { |
| 2974 | self.scale_factor |
| 2975 | } |
| 2976 | |
| 2977 | /// Overrides the display scale factor for tests. |
| 2978 | #[cfg(any(test, feature = "test-support"))] |
| 2979 | pub fn set_scale_factor(&mut self, scale_factor: f32) { |
| 2980 | self.scale_factor = scale_factor; |
| 2981 | self.refresh(); |
| 2982 | } |
| 2983 | |
| 2984 | /// The size of an em for the base font of the application. Adjusting this value allows the |
| 2985 | /// UI to scale, just like zooming a web page. |
| 2986 | pub fn rem_size(&self) -> Pixels { |
| 2987 | self.rem_size_override_stack |
| 2988 | .last() |
| 2989 | .copied() |
| 2990 | .unwrap_or(self.rem_size) |
| 2991 | } |
| 2992 | |
| 2993 | /// Sets the size of an em for the base font of the application. Adjusting this value allows the |
| 2994 | /// UI to scale, just like zooming a web page. |
| 2995 | pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) { |
| 2996 | self.rem_size = rem_size.into(); |
| 2997 | } |
| 2998 | |
| 2999 | /// Acquire a globally unique identifier for the given ElementId. |
| 3000 | /// Only valid for the duration of the provided closure. |
| 3001 | pub fn with_global_id<R>( |
| 3002 | &mut self, |
| 3003 | element_id: ElementId, |
| 3004 | f: impl FnOnce(&GlobalElementId, &mut Self) -> R, |
| 3005 | ) -> R { |
| 3006 | self.with_id(element_id, |this| { |
| 3007 | let global_id = GlobalElementId(Arc::from(&*this.element_id_stack)); |
| 3008 | |
| 3009 | f(&global_id, this) |
| 3010 | }) |
| 3011 | } |
| 3012 | |
| 3013 | /// Calls the provided closure with the element ID pushed on the stack. |
| 3014 | #[inline] |
| 3015 | pub fn with_id<R>( |
| 3016 | &mut self, |
| 3017 | element_id: impl Into<ElementId>, |
| 3018 | f: impl FnOnce(&mut Self) -> R, |
| 3019 | ) -> R { |
| 3020 | self.element_id_stack.push(element_id.into()); |
| 3021 | let result = f(self); |
| 3022 | self.element_id_stack.pop(); |
| 3023 | result |
| 3024 | } |
| 3025 | |
| 3026 | /// Executes the provided function with the specified rem size. |
| 3027 | /// |
| 3028 | /// This method must only be called as part of element drawing. |
| 3029 | // This function is called in a highly recursive manner in editor |
| 3030 | // prepainting, make sure its inlined to reduce the stack burden |
| 3031 | #[inline] |
| 3032 | pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R |
| 3033 | where |
| 3034 | F: FnOnce(&mut Self) -> R, |
| 3035 | { |
| 3036 | self.invalidator.debug_assert_paint_or_prepaint(); |
| 3037 | |
| 3038 | if let Some(rem_size) = rem_size { |
| 3039 | self.rem_size_override_stack.push(rem_size.into()); |
| 3040 | let result = f(self); |
| 3041 | self.rem_size_override_stack.pop(); |
| 3042 | result |
| 3043 | } else { |
| 3044 | f(self) |
| 3045 | } |
| 3046 | } |
| 3047 | |
| 3048 | /// The line height associated with the current text style. |
| 3049 | pub fn line_height(&self) -> Pixels { |
| 3050 | self.text_style().line_height_in_pixels(self.rem_size()) |
| 3051 | } |
| 3052 | |
| 3053 | /// Rounds a logical value to the nearest device pixel. |
| 3054 | #[inline] |
| 3055 | pub fn pixel_snap(&self, value: Pixels) -> Pixels { |
| 3056 | px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor()) |
| 3057 | } |
| 3058 | |
| 3059 | /// f64 variant of [`Self::pixel_snap`]. |
| 3060 | #[inline] |
| 3061 | pub fn pixel_snap_f64(&self, value: f64) -> f64 { |
| 3062 | let scale_factor = f64::from(self.scale_factor()); |
| 3063 | round_half_toward_zero_f64(value * scale_factor) / scale_factor |
| 3064 | } |
| 3065 | |
| 3066 | /// Snaps a bounds' origin and size to the nearest device pixel. |
| 3067 | #[inline] |
| 3068 | pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> { |
| 3069 | bounds.map(|c| self.pixel_snap(c)) |
| 3070 | } |
| 3071 | |
| 3072 | /// Snaps a point's coordinates to the nearest device pixel. |
| 3073 | #[inline] |
| 3074 | pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> { |
| 3075 | position.map(|c| self.pixel_snap(c)) |
| 3076 | } |
| 3077 | |
| 3078 | /// Returns the snapped device-space bounds used to paint an underline. |
| 3079 | pub fn underline_bounds( |
| 3080 | &self, |
| 3081 | origin: Point<Pixels>, |
| 3082 | width: Pixels, |
| 3083 | style: &UnderlineStyle, |
| 3084 | ) -> Bounds<ScaledPixels> { |
| 3085 | let scale_factor = self.scale_factor(); |
| 3086 | let thickness = self.snap_stroke(style.thickness); |
| 3087 | let height = if style.wavy { |
| 3088 | ScaledPixels(thickness.0 * 3.) |
| 3089 | } else { |
| 3090 | thickness |
| 3091 | }; |
| 3092 | Bounds { |
| 3093 | origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))), |
| 3094 | size: size(self.snap_stroke(width), height), |
| 3095 | } |
| 3096 | } |
| 3097 | |
| 3098 | /// Paints an underline excluding absolute device-space horizontal spans. |
| 3099 | pub fn paint_underline_with_exclusions( |
| 3100 | &mut self, |
| 3101 | origin: Point<Pixels>, |
| 3102 | width: Pixels, |
| 3103 | style: &UnderlineStyle, |
| 3104 | exclusions: &[Range<ScaledPixels>], |
| 3105 | ) { |
| 3106 | self.invalidator.debug_assert_paint(); |
| 3107 | let underline = self.underline(origin, width, style); |
| 3108 | if exclusions.is_empty() { |
| 3109 | self.next_frame.scene.insert_primitive(underline); |
| 3110 | return; |
| 3111 | } |
| 3112 | |
| 3113 | let bounds = underline.bounds.intersect(&underline.content_mask.bounds); |
| 3114 | if bounds.is_empty() { |
| 3115 | return; |
| 3116 | } |
| 3117 | |
| 3118 | let mut exclusions = exclusions |
| 3119 | .iter() |
| 3120 | .filter_map(|span| { |
| 3121 | let start = span.start.max(bounds.left()); |
| 3122 | let end = span.end.min(bounds.right()); |
| 3123 | (start < end).then_some(start..end) |
| 3124 | }) |
| 3125 | .collect::<SmallVec<[_; 4]>>(); |
| 3126 | if exclusions.is_empty() { |
| 3127 | self.next_frame.scene.insert_primitive(underline); |
| 3128 | return; |
| 3129 | } |
| 3130 | exclusions.sort_unstable_by_key(|span| span.start); |
| 3131 | |
| 3132 | let mut paint_span = |start, end| { |
| 3133 | self.next_frame.scene.insert_primitive(Underline { |
| 3134 | content_mask: ContentMask { |
| 3135 | bounds: Bounds::from_corners( |
| 3136 | point(start, bounds.top()), |
| 3137 | point(end, bounds.bottom()), |
| 3138 | ), |
| 3139 | }, |
| 3140 | ..underline |
| 3141 | }); |
| 3142 | }; |
| 3143 | let mut start = bounds.left(); |
| 3144 | for exclusion in exclusions { |
| 3145 | if start < exclusion.start { |
| 3146 | paint_span(start, exclusion.start); |
| 3147 | } |
| 3148 | start = start.max(exclusion.end); |
| 3149 | } |
| 3150 | if start < bounds.right() { |
| 3151 | paint_span(start, bounds.right()); |
| 3152 | } |
| 3153 | } |
| 3154 | |
| 3155 | fn underline(&self, origin: Point<Pixels>, width: Pixels, style: &UnderlineStyle) -> Underline { |
| 3156 | Underline { |
| 3157 | order: 0, |
| 3158 | pad: 0, |
| 3159 | bounds: self.underline_bounds(origin, width, style), |
| 3160 | content_mask: self.snapped_content_mask(), |
| 3161 | color: style |
| 3162 | .color |
| 3163 | .unwrap_or_default() |
| 3164 | .opacity(self.element_opacity()), |
| 3165 | thickness: self.snap_stroke(style.thickness), |
| 3166 | wavy: style.wavy.into(), |
| 3167 | } |
| 3168 | } |
| 3169 | |
| 3170 | #[inline] |
| 3171 | fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> { |
| 3172 | let scale_factor = self.scale_factor(); |
| 3173 | let left = round_to_device_pixel(bounds.left().0, scale_factor); |
| 3174 | let top = round_to_device_pixel(bounds.top().0, scale_factor); |
| 3175 | let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left); |
| 3176 | let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top); |
| 3177 | Bounds::from_corners( |
| 3178 | point(ScaledPixels(left), ScaledPixels(top)), |
| 3179 | point(ScaledPixels(right), ScaledPixels(bottom)), |
| 3180 | ) |
| 3181 | } |
| 3182 | |
| 3183 | /// Rounds half-to-zero but clamps any non-zero input up to 1 dp so thin strokes do not disappear. |
| 3184 | #[inline] |
| 3185 | fn snap_stroke(&self, value: Pixels) -> ScaledPixels { |
| 3186 | ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor())) |
| 3187 | } |
| 3188 | |
| 3189 | #[inline] |
| 3190 | fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> { |
| 3191 | edges.map(|e| self.snap_stroke(*e)) |
| 3192 | } |
| 3193 | |
| 3194 | /// Floors the near edge and ceils the far edge, producing a strict superset of the raw region. |
| 3195 | #[inline] |
| 3196 | fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> { |
| 3197 | let scale_factor = self.scale_factor(); |
| 3198 | let left = floor_to_device_pixel(bounds.left().0, scale_factor); |
| 3199 | let top = floor_to_device_pixel(bounds.top().0, scale_factor); |
| 3200 | let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left); |
| 3201 | let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top); |
| 3202 | Bounds::from_corners( |
| 3203 | point(ScaledPixels(left), ScaledPixels(top)), |
| 3204 | point(ScaledPixels(right), ScaledPixels(bottom)), |
| 3205 | ) |
| 3206 | } |
| 3207 | |
| 3208 | #[inline] |
| 3209 | fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> { |
| 3210 | ContentMask { |
| 3211 | bounds: self.cover_bounds(self.content_mask().bounds), |
| 3212 | } |
| 3213 | } |
| 3214 | |
| 3215 | /// Call to prevent the default action of an event. Currently only used to prevent |
| 3216 | /// parent elements from becoming focused on mouse down. |
| 3217 | pub fn prevent_default(&mut self) { |
| 3218 | self.default_prevented = true; |
| 3219 | } |
| 3220 | |
| 3221 | /// Obtain whether default has been prevented for the event currently being dispatched. |
| 3222 | pub fn default_prevented(&self) -> bool { |
| 3223 | self.default_prevented |
| 3224 | } |
| 3225 | |
| 3226 | /// Determine whether the given action is available along the dispatch path to the currently focused element. |
| 3227 | pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool { |
| 3228 | let node_id = |
| 3229 | self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id)); |
| 3230 | self.rendered_frame |
| 3231 | .dispatch_tree |
| 3232 | .is_action_available(action, node_id) |
| 3233 | } |
| 3234 | |
| 3235 | /// Determine whether the given action is available along the dispatch path to the given focus_handle. |
| 3236 | pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool { |
| 3237 | let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id)); |
| 3238 | self.rendered_frame |
| 3239 | .dispatch_tree |
| 3240 | .is_action_available(action, node_id) |
| 3241 | } |
| 3242 | |
| 3243 | /// The position of the mouse relative to the window. |
| 3244 | pub fn mouse_position(&self) -> Point<Pixels> { |
| 3245 | self.mouse_position |
| 3246 | } |
| 3247 | |
| 3248 | /// Captures the pointer for the given hitbox. While captured, all mouse move and mouse up |
| 3249 | /// events will be routed to listeners that check this hitbox's `is_hovered` status, |
| 3250 | /// regardless of actual hit testing. This enables drag operations that continue |
| 3251 | /// even when the pointer moves outside the element's bounds. |
| 3252 | /// |
| 3253 | /// The capture is automatically released on mouse up. |
| 3254 | pub fn capture_pointer(&mut self, hitbox_id: HitboxId) { |
| 3255 | self.captured_hitbox = Some(hitbox_id); |
| 3256 | } |
| 3257 | |
| 3258 | /// Releases any active pointer capture. |
| 3259 | pub fn release_pointer(&mut self) { |
| 3260 | self.captured_hitbox = None; |
| 3261 | } |
| 3262 | |
| 3263 | /// Returns the hitbox that has captured the pointer, if any. |
| 3264 | pub fn captured_hitbox(&self) -> Option<HitboxId> { |
| 3265 | self.captured_hitbox |
| 3266 | } |
| 3267 | |
| 3268 | /// Captures the current long press for the given entity. |
| 3269 | /// |
| 3270 | /// The capture is released when the gesture ends or is cancelled, or when |
| 3271 | /// a replacement touch begins. A listener must also call |
| 3272 | /// [`Self::prevent_default`] on the started event to claim the gesture. |
| 3273 | pub fn capture_long_press<T: 'static>(&mut self, entity: &Entity<T>) { |
| 3274 | self.long_press_capture = Some(entity.entity_id()); |
| 3275 | } |
| 3276 | |
| 3277 | /// Returns whether the given entity has captured the current long press. |
| 3278 | pub fn has_long_press_capture<T: 'static>(&self, entity: &Entity<T>) -> bool { |
| 3279 | self.long_press_capture == Some(entity.entity_id()) |
| 3280 | } |
| 3281 | |
| 3282 | /// The current state of the keyboard's modifiers |
| 3283 | pub fn modifiers(&self) -> Modifiers { |
| 3284 | self.modifiers |
| 3285 | } |
| 3286 | |
| 3287 | /// Returns true if the last input event was keyboard-based (key press, tab navigation, etc.) |
| 3288 | /// This is used for focus-visible styling to show focus indicators only for keyboard navigation. |
| 3289 | pub fn last_input_was_keyboard(&self) -> bool { |
| 3290 | self.last_input_modality == InputModality::Keyboard |
| 3291 | } |
| 3292 | |
| 3293 | pub(crate) fn last_input_was_touch(&self) -> bool { |
| 3294 | self.last_input_modality == InputModality::Touch |
| 3295 | } |
| 3296 | |
| 3297 | /// The current state of the keyboard's capslock |
| 3298 | pub fn capslock(&self) -> Capslock { |
| 3299 | self.capslock |
| 3300 | } |
| 3301 | |
| 3302 | /// Produces a new frame and assigns it to `rendered_frame`. To actually show |
| 3303 | /// the contents of the new [`Scene`], use [`Self::present`]. |
| 3304 | #[profiling::function] |
| 3305 | pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded { |
| 3306 | // Drain every draw in profiler builds so a previous frame's |
| 3307 | // first-invalidation timestamp can't be attributed to this one. |
| 3308 | #[cfg(feature = "profiler")] |
| 3309 | let frame_dirty = self.invalidator.take_frame_dirty(); |
| 3310 | #[cfg(feature = "profiler")] |
| 3311 | self.window_profiler.begin_draw(); |
| 3312 | |
| 3313 | // Set up the per-App arena for element allocation during this draw. |
| 3314 | // This ensures that multiple test Apps have isolated arenas. |
| 3315 | let arena_scope = ElementArenaScope::enter(&cx.element_arena); |
| 3316 | |
| 3317 | if self.platform_window.prepare_frame() { |
| 3318 | self.refresh(); |
| 3319 | } |
| 3320 | self.invalidate_entities(); |
| 3321 | cx.entities.clear_accessed(); |
| 3322 | debug_assert!(self.rendered_entity_stack.is_empty()); |
| 3323 | self.invalidator.set_dirty(false); |
| 3324 | self.requested_autoscroll = None; |
| 3325 | |
| 3326 | // Restore the previously-used input handler. |
| 3327 | // Place it back into a None slot (left by a previous .take()) so that |
| 3328 | // cached paint_range indices in reuse_paint find the handler at the |
| 3329 | // expected position. |
| 3330 | if let Some(input_handler) = self.platform_window.take_input_handler() { |
| 3331 | if let Some(slot) = self |
| 3332 | .rendered_frame |
| 3333 | .input_handlers |
| 3334 | .iter_mut() |
| 3335 | .rev() |
| 3336 | .find(|h| h.is_none()) |
| 3337 | { |
| 3338 | *slot = Some(input_handler); |
| 3339 | } else { |
| 3340 | self.rendered_frame.input_handlers.push(Some(input_handler)); |
| 3341 | } |
| 3342 | } |
| 3343 | if !cx.mode.skip_drawing() { |
| 3344 | self.draw_roots(cx); |
| 3345 | #[cfg(feature = "profiler")] |
| 3346 | { |
| 3347 | let viewport_size = self.viewport_size; |
| 3348 | let scale_factor = self.scale_factor(); |
| 3349 | self.debug_frame_overlay.paint( |
| 3350 | &mut self.next_frame.scene, |
| 3351 | viewport_size, |
| 3352 | scale_factor, |
| 3353 | ); |
| 3354 | } |
| 3355 | } |
| 3356 | self.dirty_views.clear(); |
| 3357 | self.next_frame.window_active = self.active.get(); |
| 3358 | |
| 3359 | // Register requested input handler with the platform window. |
| 3360 | // Use .take() instead of .pop() to preserve Vec length, so that cached |
| 3361 | // paint_range indices remain valid for reuse_paint on the next frame. |
| 3362 | // Search backwards to find the last Some entry, since reuse_paint may |
| 3363 | // have copied None slots from the previous frame. (Fixes #50456) |
| 3364 | let focused_text_input_active = if let Some(mut input_handler) = self |
| 3365 | .next_frame |
| 3366 | .input_handlers |
| 3367 | .iter_mut() |
| 3368 | .rev() |
| 3369 | .find_map(|h| h.take()) |
| 3370 | { |
| 3371 | let accepts_text_input = input_handler.accepts_text_input(self, cx); |
| 3372 | self.platform_window.set_input_handler(input_handler); |
| 3373 | accepts_text_input |
| 3374 | } else { |
| 3375 | false |
| 3376 | }; |
| 3377 | self.apply_text_input_configuration(cx); |
| 3378 | if focused_text_input_active != self.focused_text_input_active { |
| 3379 | self.focused_text_input_active = focused_text_input_active; |
| 3380 | self.platform_window |
| 3381 | .text_input_state_changed(if focused_text_input_active { |
| 3382 | TextInputStateChange::FocusGained |
| 3383 | } else { |
| 3384 | TextInputStateChange::FocusLost |
| 3385 | }); |
| 3386 | } |
| 3387 | |
| 3388 | self.layout_engine.as_mut().unwrap().clear(); |
| 3389 | self.text_system().finish_frame(); |
| 3390 | self.next_frame.finish(&mut self.rendered_frame); |
| 3391 | |
| 3392 | self.invalidator.set_phase(DrawPhase::Focus); |
| 3393 | let previous_focus_path = self.rendered_frame.focus_path(); |
| 3394 | let previous_window_active = self.rendered_frame.window_active; |
| 3395 | mem::swap(&mut self.rendered_frame, &mut self.next_frame); |
| 3396 | self.next_frame.clear(); |
| 3397 | let current_focus_path = self.rendered_frame.focus_path(); |
| 3398 | let current_window_active = self.rendered_frame.window_active; |
| 3399 | let mut focus_before_listeners = self.focus; |
| 3400 | |
| 3401 | if previous_focus_path != current_focus_path |
| 3402 | || previous_window_active != current_window_active |
| 3403 | { |
| 3404 | if !previous_focus_path.is_empty() && current_focus_path.is_empty() { |
| 3405 | self.focus_lost_path = previous_focus_path.clone(); |
| 3406 | self.focus_lost_listeners |
| 3407 | .clone() |
| 3408 | .retain(&(), |listener| listener(self, cx)); |
| 3409 | self.focus_lost_path = SmallVec::new(); |
| 3410 | // The focus-lost fallback (e.g. a workspace refocusing itself) may target |
| 3411 | // an element that isn't part of the element tree, in which case scheduling |
| 3412 | // a redraw below would dispatch focus-lost again, looping forever. Only |
| 3413 | // track focus movement caused by the focus listeners. |
| 3414 | focus_before_listeners = self.focus; |
| 3415 | } |
| 3416 | |
| 3417 | let event = WindowFocusEvent { |
| 3418 | previous_focus_path: if previous_window_active { |
| 3419 | previous_focus_path |
| 3420 | } else { |
| 3421 | Default::default() |
| 3422 | }, |
| 3423 | current_focus_path: if current_window_active { |
| 3424 | current_focus_path |
| 3425 | } else { |
| 3426 | Default::default() |
| 3427 | }, |
| 3428 | }; |
| 3429 | self.focus_listeners |
| 3430 | .clone() |
| 3431 | .retain(&(), |listener| listener(&event, self, cx)); |
| 3432 | } |
| 3433 | |
| 3434 | debug_assert!(self.rendered_entity_stack.is_empty()); |
| 3435 | self.record_entities_accessed(cx); |
| 3436 | self.reset_cursor_style(cx); |
| 3437 | self.refreshing = false; |
| 3438 | self.invalidator.set_phase(DrawPhase::None); |
| 3439 | // Focus listeners may move focus (e.g. a dock forwarding focus to its active |
| 3440 | // panel). `Window::focus` suppresses `refresh` while a draw is in progress, so |
| 3441 | // schedule another frame here to render the new focus state and dispatch the |
| 3442 | // resulting focus events. |
| 3443 | if self.focus != focus_before_listeners { |
| 3444 | self.refresh(); |
| 3445 | } |
| 3446 | self.needs_present.set(true); |
| 3447 | |
| 3448 | #[cfg(feature = "profiler")] |
| 3449 | { |
| 3450 | let draw_duration = self |
| 3451 | .window_profiler |
| 3452 | .end_draw(frame_dirty.dirty_at, frame_dirty.invalidations); |
| 3453 | self.debug_frame_overlay.record_frame(draw_duration); |
| 3454 | } |
| 3455 | |
| 3456 | // Exit the scope to obtain the arena-clear token this draw owes; the |
| 3457 | // scope's teardown itself happens in `ElementArenaScope::drop`. |
| 3458 | arena_scope.exit(&cx.element_arena) |
| 3459 | } |
| 3460 | |
| 3461 | fn record_entities_accessed(&mut self, cx: &mut App) { |
| 3462 | let mut entities_ref = cx.entities.accessed_entities.get_mut(); |
| 3463 | let mut entities = mem::take(entities_ref.deref_mut()); |
| 3464 | let handle = self.handle; |
| 3465 | cx.record_entities_accessed( |
| 3466 | handle, |
| 3467 | // Try moving window invalidator into the Window |
| 3468 | self.invalidator.clone(), |
| 3469 | &entities, |
| 3470 | ); |
| 3471 | let mut entities_ref = cx.entities.accessed_entities.get_mut(); |
| 3472 | mem::swap(&mut entities, entities_ref.deref_mut()); |
| 3473 | } |
| 3474 | |
| 3475 | fn invalidate_entities(&mut self) { |
| 3476 | let mut views = self.invalidator.take_views(); |
| 3477 | for entity in views.drain() { |
| 3478 | self.mark_view_dirty(entity); |
| 3479 | } |
| 3480 | self.invalidator.replace_views(views); |
| 3481 | } |
| 3482 | |
| 3483 | #[profiling::function] |
| 3484 | fn present(&mut self) { |
| 3485 | #[cfg(feature = "profiler")] |
| 3486 | let _foreground_turn = profiler::journal::foreground_turn(); |
| 3487 | #[cfg(feature = "profiler")] |
| 3488 | let present_start = Instant::now(); |
| 3489 | self.platform_window.draw(&self.rendered_frame.scene); |
| 3490 | #[cfg(feature = "profiler")] |
| 3491 | self.window_profiler.record_present( |
| 3492 | present_start, |
| 3493 | Instant::now(), |
| 3494 | self.active.get(), |
| 3495 | !self.next_frame_callbacks.borrow().is_empty(), |
| 3496 | ); |
| 3497 | self.needs_present.set(false); |
| 3498 | profiling::finish_frame!(); |
| 3499 | } |
| 3500 | |
| 3501 | /// Presents the most recently drawn frame if it hasn't been presented yet. |
| 3502 | #[cfg(all(test, feature = "profiler"))] |
| 3503 | pub fn present_if_needed(&mut self) { |
| 3504 | if self.needs_present.get() { |
| 3505 | self.present(); |
| 3506 | } |
| 3507 | } |
| 3508 | |
| 3509 | /// Returns a snapshot of the current input-latency histograms. |
| 3510 | #[cfg(feature = "profiler")] |
| 3511 | pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot { |
| 3512 | self.window_profiler.input_latency_snapshot() |
| 3513 | } |
| 3514 | |
| 3515 | /// Returns a snapshot of the current frame-duration histograms. |
| 3516 | #[cfg(feature = "profiler")] |
| 3517 | pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot { |
| 3518 | self.window_profiler.frame_duration_snapshot() |
| 3519 | } |
| 3520 | |
| 3521 | /// Returns the current mode of the debug frame overlay. |
| 3522 | #[cfg(feature = "profiler")] |
| 3523 | pub fn debug_frame_overlay_mode(&self) -> DebugFrameOverlayMode { |
| 3524 | self.debug_frame_overlay.mode() |
| 3525 | } |
| 3526 | |
| 3527 | /// Sets the mode of the debug frame overlay and schedules a redraw. |
| 3528 | #[cfg(feature = "profiler")] |
| 3529 | pub fn set_debug_frame_overlay_mode(&mut self, mode: DebugFrameOverlayMode) { |
| 3530 | self.debug_frame_overlay.set_mode(mode); |
| 3531 | self.refresh(); |
| 3532 | } |
| 3533 | |
| 3534 | /// Advances the debug frame overlay through its hidden, frame-time-only, |
| 3535 | /// and detailed modes. |
| 3536 | #[cfg(feature = "profiler")] |
| 3537 | pub fn cycle_debug_frame_overlay_mode(&mut self) { |
| 3538 | self.set_debug_frame_overlay_mode(self.debug_frame_overlay.mode().next()); |
| 3539 | } |
| 3540 | |
| 3541 | /// Clears the debug frame overlay's frame-time statistics, except for the |
| 3542 | /// total frame count, and schedules a redraw. |
| 3543 | #[cfg(feature = "profiler")] |
| 3544 | pub fn reset_debug_frame_overlay_stats(&mut self) { |
| 3545 | self.debug_frame_overlay.reset_stats(); |
| 3546 | self.refresh(); |
| 3547 | } |
| 3548 | |
| 3549 | fn draw_roots(&mut self, cx: &mut App) { |
| 3550 | self.invalidator.set_phase(DrawPhase::Prepaint); |
| 3551 | self.tooltip_bounds.take(); |
| 3552 | |
| 3553 | self.a11y.sync_active_flag(); |
| 3554 | if self.a11y.is_active() { |
| 3555 | self.a11y.begin_frame(); |
| 3556 | } |
| 3557 | |
| 3558 | let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size()); |
| 3559 | let root_size = { |
| 3560 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 3561 | { |
| 3562 | if self.inspector.is_some() { |
| 3563 | let mut size = self.viewport_size; |
| 3564 | size.width = (size.width - _inspector_width).max(px(0.0)); |
| 3565 | size |
| 3566 | } else { |
| 3567 | self.viewport_size |
| 3568 | } |
| 3569 | } |
| 3570 | #[cfg(not(any(feature = "inspector", debug_assertions)))] |
| 3571 | { |
| 3572 | self.viewport_size |
| 3573 | } |
| 3574 | }; |
| 3575 | |
| 3576 | // Layout all root elements. Like the root element on the web, which |
| 3577 | // stretches to fill the viewport unless explicitly sized, window roots |
| 3578 | // fill the window when their size is `auto`. |
| 3579 | let scale_factor = self.scale_factor(); |
| 3580 | let mut root_element = self.root.as_ref().unwrap().clone().into_any_element(); |
| 3581 | let root_layout_id = root_element.request_layout(self, cx); |
| 3582 | self.layout_engine |
| 3583 | .as_mut() |
| 3584 | .unwrap() |
| 3585 | .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor); |
| 3586 | root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx); |
| 3587 | |
| 3588 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 3589 | let inspector_element = self.prepaint_inspector(_inspector_width, cx); |
| 3590 | |
| 3591 | self.prepaint_deferred_draws(cx); |
| 3592 | |
| 3593 | let mut prompt_element = None; |
| 3594 | let mut active_drag_element = None; |
| 3595 | let mut tooltip_element = None; |
| 3596 | if let Some(prompt) = self.prompt.take() { |
| 3597 | let mut element = prompt.view.any_view().into_any_element(); |
| 3598 | let prompt_layout_id = element.request_layout(self, cx); |
| 3599 | self.layout_engine |
| 3600 | .as_mut() |
| 3601 | .unwrap() |
| 3602 | .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor); |
| 3603 | element.prepaint_as_root(Point::default(), root_size.into(), self, cx); |
| 3604 | prompt_element = Some(element); |
| 3605 | self.prompt = Some(prompt); |
| 3606 | } else if let Some(active_drag) = cx.active_drag.take() { |
| 3607 | let mut element = active_drag.view.clone().into_any_element(); |
| 3608 | let offset = self.mouse_position() - active_drag.cursor_offset; |
| 3609 | element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx); |
| 3610 | active_drag_element = Some(element); |
| 3611 | cx.active_drag = Some(active_drag); |
| 3612 | } else { |
| 3613 | tooltip_element = self.prepaint_tooltip(cx); |
| 3614 | } |
| 3615 | |
| 3616 | self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position); |
| 3617 | |
| 3618 | // Now actually paint the elements. |
| 3619 | self.invalidator.set_phase(DrawPhase::Paint); |
| 3620 | root_element.paint(self, cx); |
| 3621 | |
| 3622 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 3623 | self.paint_inspector(inspector_element, cx); |
| 3624 | |
| 3625 | self.paint_deferred_draws(cx); |
| 3626 | |
| 3627 | if let Some(mut prompt_element) = prompt_element { |
| 3628 | prompt_element.paint(self, cx); |
| 3629 | } else if let Some(mut drag_element) = active_drag_element { |
| 3630 | drag_element.paint(self, cx); |
| 3631 | } else if let Some(mut tooltip_element) = tooltip_element { |
| 3632 | tooltip_element.paint(self, cx); |
| 3633 | } |
| 3634 | |
| 3635 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 3636 | self.paint_inspector_hitbox(cx); |
| 3637 | |
| 3638 | // a11y may have been activated/deactivated halfway through the frame |
| 3639 | let a11y_active_start_of_frame = self.a11y.is_active(); |
| 3640 | self.a11y.sync_active_flag(); |
| 3641 | let a11y_active_end_of_frame = self.a11y.is_active(); |
| 3642 | |
| 3643 | let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame; |
| 3644 | |
| 3645 | if a11y_active_start_of_frame { |
| 3646 | // Harvest frame metadata for the debug dump while the live window |
| 3647 | // and frame are still in scope. |
| 3648 | let frame_info = crate::window::a11y::debug::FrameDebugInfo { |
| 3649 | viewport_size: self.viewport_size, |
| 3650 | scale_factor: self.scale_factor, |
| 3651 | tab_stop_count: self.next_frame.tab_stops.tab_stop_count(), |
| 3652 | }; |
| 3653 | // clear the builder state regardless |
| 3654 | let tree_update = self.a11y.end_frame(frame_info); |
| 3655 | |
| 3656 | if should_send_a11y_update { |
| 3657 | log::debug!( |
| 3658 | "Sending a11y tree update: {} nodes", |
| 3659 | tree_update.nodes.len() |
| 3660 | ); |
| 3661 | self.platform_window.a11y_tree_update(tree_update); |
| 3662 | } |
| 3663 | } |
| 3664 | } |
| 3665 | |
| 3666 | fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> { |
| 3667 | // Use indexing instead of iteration to avoid borrowing self for the duration of the loop. |
| 3668 | for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() { |
| 3669 | let Some(Some(tooltip_request)) = self |
| 3670 | .next_frame |
| 3671 | .tooltip_requests |
| 3672 | .get(tooltip_request_index) |
| 3673 | .cloned() |
| 3674 | else { |
| 3675 | log::error!("Unexpectedly absent TooltipRequest"); |
| 3676 | continue; |
| 3677 | }; |
| 3678 | let mut element = tooltip_request.tooltip.view.clone().into_any_element(); |
| 3679 | let mouse_position = tooltip_request.tooltip.mouse_position; |
| 3680 | let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx); |
| 3681 | |
| 3682 | let mut tooltip_bounds = |
| 3683 | Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size); |
| 3684 | let window_bounds = Bounds { |
| 3685 | origin: Point::default(), |
| 3686 | size: self.viewport_size(), |
| 3687 | }; |
| 3688 | |
| 3689 | if tooltip_bounds.right() > window_bounds.right() { |
| 3690 | let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.); |
| 3691 | if new_x >= Pixels::ZERO { |
| 3692 | tooltip_bounds.origin.x = new_x; |
| 3693 | } else { |
| 3694 | tooltip_bounds.origin.x = cmp::max( |
| 3695 | Pixels::ZERO, |
| 3696 | tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(), |
| 3697 | ); |
| 3698 | } |
| 3699 | } |
| 3700 | |
| 3701 | if tooltip_bounds.bottom() > window_bounds.bottom() { |
| 3702 | let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.); |
| 3703 | if new_y >= Pixels::ZERO { |
| 3704 | tooltip_bounds.origin.y = new_y; |
| 3705 | } else { |
| 3706 | tooltip_bounds.origin.y = cmp::max( |
| 3707 | Pixels::ZERO, |
| 3708 | tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(), |
| 3709 | ); |
| 3710 | } |
| 3711 | } |
| 3712 | |
| 3713 | // It's possible for an element to have an active tooltip while not being painted (e.g. |
| 3714 | // via the `visible_on_hover` method). Since mouse listeners are not active in this |
| 3715 | // case, instead update the tooltip's visibility here. |
| 3716 | let is_visible = |
| 3717 | (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx); |
| 3718 | if !is_visible { |
| 3719 | continue; |
| 3720 | } |
| 3721 | |
| 3722 | self.with_absolute_element_offset(tooltip_bounds.origin, |window| { |
| 3723 | element.prepaint(window, cx) |
| 3724 | }); |
| 3725 | |
| 3726 | self.tooltip_bounds = Some(TooltipBounds { |
| 3727 | id: tooltip_request.id, |
| 3728 | bounds: tooltip_bounds, |
| 3729 | }); |
| 3730 | return Some(element); |
| 3731 | } |
| 3732 | None |
| 3733 | } |
| 3734 | |
| 3735 | fn prepaint_deferred_draws(&mut self, cx: &mut App) { |
| 3736 | assert_eq!(self.element_id_stack.len(), 0); |
| 3737 | |
| 3738 | // Process deferred draws in multiple rounds to support nesting. |
| 3739 | // Each round processes all current deferred draws, which may push new ones. |
| 3740 | // |
| 3741 | // The draws are processed in place rather than being moved out of |
| 3742 | // `next_frame.deferred_draws`: `prepaint_index` snapshots that vector's |
| 3743 | // length, so any prepaint range recorded during a round (view caches, |
| 3744 | // nested deferred draws) must index the same vector `reuse_prepaint` |
| 3745 | // slices on the next frame. Moving the draws out and re-appending them |
| 3746 | // shifts the indices of nested draws, causing reused subtrees to graft |
| 3747 | // the wrong deferred draws and panic in the dispatch tree. |
| 3748 | let mut round_start = 0; |
| 3749 | let mut depth = 0; |
| 3750 | loop { |
| 3751 | let round_end = self.next_frame.deferred_draws.len(); |
| 3752 | if round_start == round_end { |
| 3753 | break; |
| 3754 | } |
| 3755 | // Limit maximum nesting depth to prevent infinite loops. |
| 3756 | assert!(depth < 10, "Exceeded maximum (10) deferred depth"); |
| 3757 | depth += 1; |
| 3758 | |
| 3759 | // Sort this round by priority. |
| 3760 | let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>(); |
| 3761 | traversal_order.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority); |
| 3762 | |
| 3763 | for deferred_draw_ix in traversal_order { |
| 3764 | let (element, parent_node, current_view, rem_size, absolute_offset, prepaint_range) = { |
| 3765 | let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix]; |
| 3766 | self.element_id_stack |
| 3767 | .clone_from(&deferred_draw.element_id_stack); |
| 3768 | self.text_style_stack |
| 3769 | .clone_from(&deferred_draw.text_style_stack); |
| 3770 | ( |
| 3771 | deferred_draw.element.take(), |
| 3772 | deferred_draw.parent_node, |
| 3773 | deferred_draw.current_view, |
| 3774 | deferred_draw.rem_size, |
| 3775 | deferred_draw.absolute_offset, |
| 3776 | deferred_draw.prepaint_range.clone(), |
| 3777 | ) |
| 3778 | }; |
| 3779 | self.next_frame.dispatch_tree.set_active_node(parent_node); |
| 3780 | |
| 3781 | let prepaint_start = self.prepaint_index(); |
| 3782 | if let Some(mut element) = element { |
| 3783 | self.with_rendered_view(current_view, |window| { |
| 3784 | window.with_rem_size(Some(rem_size), |window| { |
| 3785 | window.with_absolute_element_offset(absolute_offset, |window| { |
| 3786 | element.prepaint(window, cx); |
| 3787 | }); |
| 3788 | }); |
| 3789 | }); |
| 3790 | self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element); |
| 3791 | } else { |
| 3792 | self.reuse_prepaint(prepaint_range); |
| 3793 | } |
| 3794 | let prepaint_end = self.prepaint_index(); |
| 3795 | self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range = |
| 3796 | prepaint_start..prepaint_end; |
| 3797 | } |
| 3798 | |
| 3799 | self.element_id_stack.clear(); |
| 3800 | self.text_style_stack.clear(); |
| 3801 | round_start = round_end; |
| 3802 | } |
| 3803 | } |
| 3804 | |
| 3805 | fn paint_deferred_draws(&mut self, cx: &mut App) { |
| 3806 | assert_eq!(self.element_id_stack.len(), 0); |
| 3807 | |
| 3808 | // Paint all deferred draws in priority order. |
| 3809 | // Since prepaint has already processed nested deferreds, we just paint them all. |
| 3810 | if self.next_frame.deferred_draws.len() == 0 { |
| 3811 | return; |
| 3812 | } |
| 3813 | |
| 3814 | let traversal_order = self.deferred_draw_traversal_order(); |
| 3815 | let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws); |
| 3816 | for deferred_draw_ix in traversal_order { |
| 3817 | let mut deferred_draw = &mut deferred_draws[deferred_draw_ix]; |
| 3818 | self.element_id_stack |
| 3819 | .clone_from(&deferred_draw.element_id_stack); |
| 3820 | self.next_frame |
| 3821 | .dispatch_tree |
| 3822 | .set_active_node(deferred_draw.parent_node); |
| 3823 | |
| 3824 | let paint_start = self.paint_index(); |
| 3825 | let content_mask = deferred_draw.content_mask; |
| 3826 | if let Some(element) = deferred_draw.element.as_mut() { |
| 3827 | self.with_rendered_view(deferred_draw.current_view, |window| { |
| 3828 | window.with_content_mask(content_mask, |window| { |
| 3829 | window.with_rem_size(Some(deferred_draw.rem_size), |window| { |
| 3830 | element.paint(window, cx); |
| 3831 | }); |
| 3832 | }) |
| 3833 | }) |
| 3834 | } else { |
| 3835 | self.reuse_paint(deferred_draw.paint_range.clone()); |
| 3836 | } |
| 3837 | let paint_end = self.paint_index(); |
| 3838 | deferred_draw.paint_range = paint_start..paint_end; |
| 3839 | } |
| 3840 | self.next_frame.deferred_draws = deferred_draws; |
| 3841 | self.element_id_stack.clear(); |
| 3842 | } |
| 3843 | |
| 3844 | fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> { |
| 3845 | let deferred_count = self.next_frame.deferred_draws.len(); |
| 3846 | let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>(); |
| 3847 | sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority); |
| 3848 | sorted_indices |
| 3849 | } |
| 3850 | |
| 3851 | pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex { |
| 3852 | PrepaintStateIndex { |
| 3853 | hitboxes_index: self.next_frame.hitboxes.len(), |
| 3854 | tooltips_index: self.next_frame.tooltip_requests.len(), |
| 3855 | deferred_draws_index: self.next_frame.deferred_draws.len(), |
| 3856 | dispatch_tree_index: self.next_frame.dispatch_tree.len(), |
| 3857 | accessed_element_states_index: self.next_frame.accessed_element_states.len(), |
| 3858 | line_layout_index: self.text_system.layout_index(), |
| 3859 | } |
| 3860 | } |
| 3861 | |
| 3862 | pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) { |
| 3863 | self.next_frame.hitboxes.extend( |
| 3864 | self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index] |
| 3865 | .iter() |
| 3866 | .cloned(), |
| 3867 | ); |
| 3868 | self.next_frame.tooltip_requests.extend( |
| 3869 | self.rendered_frame.tooltip_requests |
| 3870 | [range.start.tooltips_index..range.end.tooltips_index] |
| 3871 | .iter_mut() |
| 3872 | .map(|request| request.take()), |
| 3873 | ); |
| 3874 | self.next_frame.accessed_element_states.extend( |
| 3875 | self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index |
| 3876 | ..range.end.accessed_element_states_index] |
| 3877 | .iter() |
| 3878 | .map(|(id, type_id)| (id.clone(), *type_id)), |
| 3879 | ); |
| 3880 | self.text_system |
| 3881 | .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index); |
| 3882 | |
| 3883 | let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree( |
| 3884 | range.start.dispatch_tree_index..range.end.dispatch_tree_index, |
| 3885 | &mut self.rendered_frame.dispatch_tree, |
| 3886 | self.focus, |
| 3887 | ); |
| 3888 | |
| 3889 | if reused_subtree.contains_focus() { |
| 3890 | self.next_frame.focus = self.focus; |
| 3891 | } |
| 3892 | |
| 3893 | self.next_frame.deferred_draws.extend( |
| 3894 | self.rendered_frame.deferred_draws |
| 3895 | [range.start.deferred_draws_index..range.end.deferred_draws_index] |
| 3896 | .iter() |
| 3897 | .map(|deferred_draw| DeferredDraw { |
| 3898 | current_view: deferred_draw.current_view, |
| 3899 | parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node), |
| 3900 | element_id_stack: deferred_draw.element_id_stack.clone(), |
| 3901 | text_style_stack: deferred_draw.text_style_stack.clone(), |
| 3902 | content_mask: deferred_draw.content_mask, |
| 3903 | rem_size: deferred_draw.rem_size, |
| 3904 | priority: deferred_draw.priority, |
| 3905 | element: None, |
| 3906 | absolute_offset: deferred_draw.absolute_offset, |
| 3907 | prepaint_range: deferred_draw.prepaint_range.clone(), |
| 3908 | paint_range: deferred_draw.paint_range.clone(), |
| 3909 | }), |
| 3910 | ); |
| 3911 | } |
| 3912 | |
| 3913 | pub(crate) fn paint_index(&self) -> PaintIndex { |
| 3914 | PaintIndex { |
| 3915 | scene_index: self.next_frame.scene.len(), |
| 3916 | #[cfg(any(test, feature = "test-support"))] |
| 3917 | debug_bounds_index: self.next_frame.debug_bounds_records.len(), |
| 3918 | mouse_listeners_index: self.next_frame.mouse_listeners.len(), |
| 3919 | input_handlers_index: self.next_frame.input_handlers.len(), |
| 3920 | cursor_styles_index: self.next_frame.cursor_styles.len(), |
| 3921 | accessed_element_states_index: self.next_frame.accessed_element_states.len(), |
| 3922 | tab_handle_index: self.next_frame.tab_stops.paint_index(), |
| 3923 | line_layout_index: self.text_system.layout_index(), |
| 3924 | } |
| 3925 | } |
| 3926 | |
| 3927 | pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) { |
| 3928 | // Cached elements still exist in the frame even when their paint methods don't run. |
| 3929 | #[cfg(any(test, feature = "test-support"))] |
| 3930 | for (selector, bounds) in &self.rendered_frame.debug_bounds_records |
| 3931 | [range.start.debug_bounds_index..range.end.debug_bounds_index] |
| 3932 | { |
| 3933 | self.next_frame |
| 3934 | .record_debug_bounds(selector.clone(), *bounds); |
| 3935 | } |
| 3936 | self.next_frame.cursor_styles.extend( |
| 3937 | self.rendered_frame.cursor_styles |
| 3938 | [range.start.cursor_styles_index..range.end.cursor_styles_index] |
| 3939 | .iter() |
| 3940 | .cloned(), |
| 3941 | ); |
| 3942 | self.next_frame.input_handlers.extend( |
| 3943 | self.rendered_frame.input_handlers |
| 3944 | [range.start.input_handlers_index..range.end.input_handlers_index] |
| 3945 | .iter_mut() |
| 3946 | .map(|handler| handler.take()), |
| 3947 | ); |
| 3948 | self.next_frame.mouse_listeners.extend( |
| 3949 | self.rendered_frame.mouse_listeners |
| 3950 | [range.start.mouse_listeners_index..range.end.mouse_listeners_index] |
| 3951 | .iter_mut() |
| 3952 | .map(|listener| listener.take()), |
| 3953 | ); |
| 3954 | self.next_frame.accessed_element_states.extend( |
| 3955 | self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index |
| 3956 | ..range.end.accessed_element_states_index] |
| 3957 | .iter() |
| 3958 | .map(|(id, type_id)| (id.clone(), *type_id)), |
| 3959 | ); |
| 3960 | self.next_frame.tab_stops.replay( |
| 3961 | &self.rendered_frame.tab_stops.insertion_history |
| 3962 | [range.start.tab_handle_index..range.end.tab_handle_index], |
| 3963 | ); |
| 3964 | |
| 3965 | self.text_system |
| 3966 | .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index); |
| 3967 | self.next_frame.scene.replay( |
| 3968 | range.start.scene_index..range.end.scene_index, |
| 3969 | &self.rendered_frame.scene, |
| 3970 | ); |
| 3971 | } |
| 3972 | |
| 3973 | /// Push a text style onto the stack, and call a function with that style active. |
| 3974 | /// Use [`Window::text_style`] to get the current, combined text style. This method |
| 3975 | /// should only be called as part of element drawing. |
| 3976 | pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R |
| 3977 | where |
| 3978 | F: FnOnce(&mut Self) -> R, |
| 3979 | { |
| 3980 | self.invalidator.debug_assert_paint_or_prepaint(); |
| 3981 | if let Some(style) = style { |
| 3982 | self.text_style_stack.push(style); |
| 3983 | let result = f(self); |
| 3984 | self.text_style_stack.pop(); |
| 3985 | result |
| 3986 | } else { |
| 3987 | f(self) |
| 3988 | } |
| 3989 | } |
| 3990 | |
| 3991 | /// Updates the cursor style at the platform level. This method should only be called |
| 3992 | /// during the paint phase of element drawing. |
| 3993 | pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) { |
| 3994 | self.invalidator.debug_assert_paint(); |
| 3995 | self.next_frame.cursor_styles.push(CursorStyleRequest { |
| 3996 | hitbox_id: Some(hitbox.id), |
| 3997 | style, |
| 3998 | }); |
| 3999 | } |
| 4000 | |
| 4001 | /// Updates the cursor style for the entire window at the platform level. A cursor |
| 4002 | /// style using this method will have precedence over any cursor style set using |
| 4003 | /// `set_cursor_style`. This method should only be called during the paint |
| 4004 | /// phase of element drawing. |
| 4005 | pub fn set_window_cursor_style(&mut self, style: CursorStyle) { |
| 4006 | self.invalidator.debug_assert_paint(); |
| 4007 | self.next_frame.cursor_styles.push(CursorStyleRequest { |
| 4008 | hitbox_id: None, |
| 4009 | style, |
| 4010 | }) |
| 4011 | } |
| 4012 | |
| 4013 | /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called |
| 4014 | /// during the paint phase of element drawing. |
| 4015 | pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId { |
| 4016 | self.invalidator.debug_assert_prepaint(); |
| 4017 | let id = TooltipId(post_inc(&mut self.next_tooltip_id.0)); |
| 4018 | self.next_frame |
| 4019 | .tooltip_requests |
| 4020 | .push(Some(TooltipRequest { id, tooltip })); |
| 4021 | id |
| 4022 | } |
| 4023 | |
| 4024 | /// Invoke the given function with the given content mask after intersecting it |
| 4025 | /// with the current mask. This method should only be called during element drawing. |
| 4026 | // This function is called in a highly recursive manner in editor |
| 4027 | // prepainting, make sure its inlined to reduce the stack burden |
| 4028 | #[inline] |
| 4029 | pub fn with_content_mask<R>( |
| 4030 | &mut self, |
| 4031 | mask: Option<ContentMask<Pixels>>, |
| 4032 | f: impl FnOnce(&mut Self) -> R, |
| 4033 | ) -> R { |
| 4034 | self.invalidator.debug_assert_paint_or_prepaint(); |
| 4035 | if let Some(mask) = mask { |
| 4036 | let mask = mask.intersect(&self.content_mask()); |
| 4037 | self.content_mask_stack.push(mask); |
| 4038 | let result = f(self); |
| 4039 | self.content_mask_stack.pop(); |
| 4040 | result |
| 4041 | } else { |
| 4042 | f(self) |
| 4043 | } |
| 4044 | } |
| 4045 | |
| 4046 | /// Updates the global element offset relative to the current offset. This is used to implement |
| 4047 | /// scrolling. This method should only be called during the prepaint phase of element drawing. |
| 4048 | pub fn with_element_offset<R>( |
| 4049 | &mut self, |
| 4050 | offset: Point<Pixels>, |
| 4051 | f: impl FnOnce(&mut Self) -> R, |
| 4052 | ) -> R { |
| 4053 | self.invalidator.debug_assert_prepaint(); |
| 4054 | |
| 4055 | if offset.is_zero() { |
| 4056 | return f(self); |
| 4057 | }; |
| 4058 | |
| 4059 | let abs_offset = self.element_offset() + offset; |
| 4060 | self.with_absolute_element_offset(abs_offset, f) |
| 4061 | } |
| 4062 | |
| 4063 | /// Updates the global element offset based on the given offset. This is used to implement |
| 4064 | /// drag handles and other manual painting of elements. This method should only be called during |
| 4065 | /// the prepaint phase of element drawing. |
| 4066 | pub fn with_absolute_element_offset<R>( |
| 4067 | &mut self, |
| 4068 | offset: Point<Pixels>, |
| 4069 | f: impl FnOnce(&mut Self) -> R, |
| 4070 | ) -> R { |
| 4071 | self.invalidator.debug_assert_prepaint(); |
| 4072 | self.element_offset_stack.push(offset); |
| 4073 | let result = f(self); |
| 4074 | self.element_offset_stack.pop(); |
| 4075 | result |
| 4076 | } |
| 4077 | |
| 4078 | pub(crate) fn with_element_opacity<R>( |
| 4079 | &mut self, |
| 4080 | opacity: Option<f32>, |
| 4081 | f: impl FnOnce(&mut Self) -> R, |
| 4082 | ) -> R { |
| 4083 | self.invalidator.debug_assert_paint_or_prepaint(); |
| 4084 | |
| 4085 | let Some(opacity) = opacity else { |
| 4086 | return f(self); |
| 4087 | }; |
| 4088 | |
| 4089 | let previous_opacity = self.element_opacity; |
| 4090 | self.element_opacity = previous_opacity * opacity; |
| 4091 | let result = f(self); |
| 4092 | self.element_opacity = previous_opacity; |
| 4093 | result |
| 4094 | } |
| 4095 | |
| 4096 | /// Perform prepaint on child elements in a "retryable" manner, so that any side effects |
| 4097 | /// of prepaints can be discarded before prepainting again. This is used to support autoscroll |
| 4098 | /// where we need to prepaint children to detect the autoscroll bounds, then adjust the |
| 4099 | /// element offset and prepaint again. See [`crate::List`] for an example. This method should only be |
| 4100 | /// called during the prepaint phase of element drawing. |
| 4101 | pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> { |
| 4102 | self.invalidator.debug_assert_prepaint(); |
| 4103 | let index = self.prepaint_index(); |
| 4104 | let result = f(self); |
| 4105 | if result.is_err() { |
| 4106 | self.next_frame.hitboxes.truncate(index.hitboxes_index); |
| 4107 | self.next_frame |
| 4108 | .tooltip_requests |
| 4109 | .truncate(index.tooltips_index); |
| 4110 | self.next_frame |
| 4111 | .deferred_draws |
| 4112 | .truncate(index.deferred_draws_index); |
| 4113 | self.next_frame |
| 4114 | .dispatch_tree |
| 4115 | .truncate(index.dispatch_tree_index); |
| 4116 | self.next_frame |
| 4117 | .accessed_element_states |
| 4118 | .truncate(index.accessed_element_states_index); |
| 4119 | self.text_system.truncate_layouts(index.line_layout_index); |
| 4120 | } |
| 4121 | result |
| 4122 | } |
| 4123 | |
| 4124 | /// When you call this method during [`Element::prepaint`], containing elements will attempt to |
| 4125 | /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call |
| 4126 | /// [`Element::prepaint`] again with a new set of bounds. See [`crate::List`] for an example of an element |
| 4127 | /// that supports this method being called on the elements it contains. This method should only be |
| 4128 | /// called during the prepaint phase of element drawing. |
| 4129 | pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) { |
| 4130 | self.invalidator.debug_assert_prepaint(); |
| 4131 | self.requested_autoscroll = Some(bounds); |
| 4132 | } |
| 4133 | |
| 4134 | /// This method can be called from a containing element such as [`crate::List`] to support the autoscroll behavior |
| 4135 | /// described in [`Self::request_autoscroll`]. |
| 4136 | pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> { |
| 4137 | self.invalidator.debug_assert_prepaint(); |
| 4138 | self.requested_autoscroll.take() |
| 4139 | } |
| 4140 | |
| 4141 | /// Asynchronously load an asset, if the asset hasn't finished loading this will return None. |
| 4142 | /// Your view will be re-drawn once the asset has finished loading. |
| 4143 | /// |
| 4144 | /// Note that the multiple calls to this method will only result in one `Asset::load` call at a |
| 4145 | /// time. |
| 4146 | pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> { |
| 4147 | cx.asset_entry::<A>(source).use_by(self.current_view()) |
| 4148 | } |
| 4149 | |
| 4150 | /// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None. |
| 4151 | /// Your view will not be re-drawn once the asset has finished loading. |
| 4152 | /// |
| 4153 | /// Note that the multiple calls to this method will only result in one `Asset::load` call at a |
| 4154 | /// time. |
| 4155 | pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> { |
| 4156 | cx.fetch_asset::<A>(source) |
| 4157 | } |
| 4158 | /// Obtain the current element offset. This method should only be called during the |
| 4159 | /// prepaint phase of element drawing. |
| 4160 | pub fn element_offset(&self) -> Point<Pixels> { |
| 4161 | self.invalidator.debug_assert_prepaint(); |
| 4162 | self.element_offset_stack |
| 4163 | .last() |
| 4164 | .copied() |
| 4165 | .unwrap_or_default() |
| 4166 | } |
| 4167 | |
| 4168 | /// Obtain the current element opacity. This method should only be called during the |
| 4169 | /// prepaint phase of element drawing. |
| 4170 | #[inline] |
| 4171 | pub(crate) fn element_opacity(&self) -> f32 { |
| 4172 | self.invalidator.debug_assert_paint_or_prepaint(); |
| 4173 | self.element_opacity |
| 4174 | } |
| 4175 | |
| 4176 | /// Obtain the current content mask. This method should only be called during element drawing. |
| 4177 | pub fn content_mask(&self) -> ContentMask<Pixels> { |
| 4178 | self.invalidator.debug_assert_paint_or_prepaint(); |
| 4179 | self.content_mask_stack |
| 4180 | .last() |
| 4181 | .cloned() |
| 4182 | .unwrap_or_else(|| ContentMask { |
| 4183 | bounds: Bounds { |
| 4184 | origin: Point::default(), |
| 4185 | size: self.viewport_size, |
| 4186 | }, |
| 4187 | }) |
| 4188 | } |
| 4189 | |
| 4190 | /// Provide elements in the called function with a new namespace in which their identifiers must be unique. |
| 4191 | /// This can be used within a custom element to distinguish multiple sets of child elements. |
| 4192 | pub fn with_element_namespace<R>( |
| 4193 | &mut self, |
| 4194 | element_id: impl Into<ElementId>, |
| 4195 | f: impl FnOnce(&mut Self) -> R, |
| 4196 | ) -> R { |
| 4197 | self.element_id_stack.push(element_id.into()); |
| 4198 | let result = f(self); |
| 4199 | self.element_id_stack.pop(); |
| 4200 | result |
| 4201 | } |
| 4202 | |
| 4203 | /// Use a piece of state that exists as long this element is being rendered in consecutive frames. |
| 4204 | pub fn use_keyed_state<S: 'static>( |
| 4205 | &mut self, |
| 4206 | key: impl Into<ElementId>, |
| 4207 | cx: &mut App, |
| 4208 | init: impl FnOnce(&mut Self, &mut Context<S>) -> S, |
| 4209 | ) -> Entity<S> { |
| 4210 | let current_view = self.current_view(); |
| 4211 | self.with_global_id(key.into(), |global_id, window| { |
| 4212 | window.with_element_state(global_id, |state: Option<Entity<S>>, window| { |
| 4213 | if let Some(state) = state { |
| 4214 | (state.clone(), state) |
| 4215 | } else { |
| 4216 | let new_state = cx.new(|cx| init(window, cx)); |
| 4217 | Self::observe_keyed_state(&new_state, current_view, cx); |
| 4218 | (new_state.clone(), new_state) |
| 4219 | } |
| 4220 | }) |
| 4221 | }) |
| 4222 | } |
| 4223 | |
| 4224 | /// Use a piece of state that exists as long this element is being rendered in consecutive frames, without needing to specify a key |
| 4225 | /// |
| 4226 | /// NOTE: This method uses the location of the caller to generate an ID for this state. |
| 4227 | /// If this is not sufficient to identify your state (e.g. you're rendering a list item), |
| 4228 | /// you can provide a custom ElementID using the `use_keyed_state` method. |
| 4229 | #[track_caller] |
| 4230 | pub fn use_state<S: 'static>( |
| 4231 | &mut self, |
| 4232 | cx: &mut App, |
| 4233 | init: impl FnOnce(&mut Self, &mut Context<S>) -> S, |
| 4234 | ) -> Entity<S> { |
| 4235 | self.use_keyed_state( |
| 4236 | ElementId::CodeLocation(*core::panic::Location::caller()), |
| 4237 | cx, |
| 4238 | init, |
| 4239 | ) |
| 4240 | } |
| 4241 | |
| 4242 | /// Updates or initializes state for an element with the given id that lives across multiple |
| 4243 | /// frames. If an element with this ID existed in the rendered frame, its state will be passed |
| 4244 | /// to the given closure. The state returned by the closure will be stored so it can be referenced |
| 4245 | /// when drawing the next frame. This method should only be called as part of element drawing. |
| 4246 | #[inline(always)] |
| 4247 | pub fn with_element_state<S, R>( |
| 4248 | &mut self, |
| 4249 | global_id: &GlobalElementId, |
| 4250 | f: impl FnOnce(Option<S>, &mut Self) -> (R, S), |
| 4251 | ) -> R |
| 4252 | where |
| 4253 | S: 'static, |
| 4254 | { |
| 4255 | self.invalidator.debug_assert_paint_or_prepaint(); |
| 4256 | |
| 4257 | let (key, state) = self.take_element_state(global_id, TypeId::of::<S>()); |
| 4258 | |
| 4259 | if let Some(any) = state { |
| 4260 | let ElementStateBox { |
| 4261 | inner, |
| 4262 | #[cfg(debug_assertions)] |
| 4263 | type_name, |
| 4264 | } = any; |
| 4265 | // Using the extra inner option to avoid needing to reallocate a new box. |
| 4266 | let mut state_box = inner |
| 4267 | .downcast::<Option<S>>() |
| 4268 | .map_err(|_| { |
| 4269 | #[cfg(debug_assertions)] |
| 4270 | { |
| 4271 | anyhow::anyhow!( |
| 4272 | "invalid element state type for id, requested {:?}, actual: {:?}", |
| 4273 | std::any::type_name::<S>(), |
| 4274 | type_name |
| 4275 | ) |
| 4276 | } |
| 4277 | |
| 4278 | #[cfg(not(debug_assertions))] |
| 4279 | { |
| 4280 | anyhow::anyhow!( |
| 4281 | "invalid element state type for id, requested {:?}", |
| 4282 | std::any::type_name::<S>(), |
| 4283 | ) |
| 4284 | } |
| 4285 | }) |
| 4286 | .unwrap(); |
| 4287 | |
| 4288 | let state = state_box.take().expect( |
| 4289 | "reentrant call to with_element_state for the same state type and element id", |
| 4290 | ); |
| 4291 | let (result, state) = f(Some(state), self); |
| 4292 | state_box.replace(state); |
| 4293 | self.insert_element_state( |
| 4294 | key, |
| 4295 | ElementStateBox { |
| 4296 | inner: state_box, |
| 4297 | #[cfg(debug_assertions)] |
| 4298 | type_name, |
| 4299 | }, |
| 4300 | ); |
| 4301 | result |
| 4302 | } else { |
| 4303 | let (result, state) = f(None, self); |
| 4304 | self.insert_element_state( |
| 4305 | key, |
| 4306 | ElementStateBox { |
| 4307 | inner: Box::new(Some(state)), |
| 4308 | #[cfg(debug_assertions)] |
| 4309 | type_name: std::any::type_name::<S>(), |
| 4310 | }, |
| 4311 | ); |
| 4312 | result |
| 4313 | } |
| 4314 | } |
| 4315 | |
| 4316 | /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience |
| 4317 | /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state` |
| 4318 | /// when the element is guaranteed to have an id. |
| 4319 | /// |
| 4320 | /// The first option means 'no ID provided' |
| 4321 | /// The second option means 'not yet initialized' |
| 4322 | pub fn with_optional_element_state<S, R>( |
| 4323 | &mut self, |
| 4324 | global_id: Option<&GlobalElementId>, |
| 4325 | f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>), |
| 4326 | ) -> R |
| 4327 | where |
| 4328 | S: 'static, |
| 4329 | { |
| 4330 | self.invalidator.debug_assert_paint_or_prepaint(); |
| 4331 | |
| 4332 | if let Some(global_id) = global_id { |
| 4333 | self.with_element_state(global_id, |state, cx| { |
| 4334 | let (result, state) = f(Some(state), cx); |
| 4335 | let state = |
| 4336 | state.expect("you must return some state when you pass some element id"); |
| 4337 | (result, state) |
| 4338 | }) |
| 4339 | } else { |
| 4340 | let (result, state) = f(None, self); |
| 4341 | debug_assert!( |
| 4342 | state.is_none(), |
| 4343 | "you must not return an element state when passing None for the global id" |
| 4344 | ); |
| 4345 | result |
| 4346 | } |
| 4347 | } |
| 4348 | |
| 4349 | /// Executes the given closure within the context of a tab group. |
| 4350 | #[inline] |
| 4351 | pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R { |
| 4352 | if let Some(index) = index { |
| 4353 | self.next_frame.tab_stops.begin_group(index); |
| 4354 | let result = f(self); |
| 4355 | self.next_frame.tab_stops.end_group(); |
| 4356 | result |
| 4357 | } else { |
| 4358 | f(self) |
| 4359 | } |
| 4360 | } |
| 4361 | |
| 4362 | /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree |
| 4363 | /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements, |
| 4364 | /// with higher values being drawn on top. |
| 4365 | /// |
| 4366 | /// When `content_mask` is provided, the deferred element will be clipped to that region during |
| 4367 | /// both prepaint and paint. When `None`, no additional clipping is applied. |
| 4368 | /// |
| 4369 | /// This method should only be called as part of the prepaint phase of element drawing. |
| 4370 | pub fn defer_draw( |
| 4371 | &mut self, |
| 4372 | element: AnyElement, |
| 4373 | absolute_offset: Point<Pixels>, |
| 4374 | priority: usize, |
| 4375 | content_mask: Option<ContentMask<Pixels>>, |
| 4376 | ) { |
| 4377 | self.invalidator.debug_assert_prepaint(); |
| 4378 | let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap(); |
| 4379 | self.next_frame.deferred_draws.push(DeferredDraw { |
| 4380 | current_view: self.current_view(), |
| 4381 | parent_node, |
| 4382 | element_id_stack: self.element_id_stack.clone(), |
| 4383 | text_style_stack: self.text_style_stack.clone(), |
| 4384 | content_mask, |
| 4385 | rem_size: self.rem_size(), |
| 4386 | priority, |
| 4387 | element: Some(element), |
| 4388 | absolute_offset, |
| 4389 | prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(), |
| 4390 | paint_range: PaintIndex::default()..PaintIndex::default(), |
| 4391 | }); |
| 4392 | } |
| 4393 | |
| 4394 | /// Creates a new painting layer for the specified bounds. A "layer" is a batch |
| 4395 | /// of geometry that are non-overlapping and have the same draw order. This is typically used |
| 4396 | /// for performance reasons. |
| 4397 | /// |
| 4398 | /// This method should only be called as part of the paint phase of element drawing. |
| 4399 | pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R { |
| 4400 | self.invalidator.debug_assert_paint(); |
| 4401 | |
| 4402 | let content_mask = self.content_mask(); |
| 4403 | let clipped_bounds = bounds.intersect(&content_mask.bounds); |
| 4404 | if !clipped_bounds.is_empty() { |
| 4405 | self.next_frame |
| 4406 | .scene |
| 4407 | .push_layer(self.cover_bounds(clipped_bounds)); |
| 4408 | } |
| 4409 | |
| 4410 | let result = f(self); |
| 4411 | |
| 4412 | if !clipped_bounds.is_empty() { |
| 4413 | self.next_frame.scene.pop_layer(); |
| 4414 | } |
| 4415 | |
| 4416 | result |
| 4417 | } |
| 4418 | |
| 4419 | /// Paint the drop (non-inset) shadows from `shadows` into the scene at the current |
| 4420 | /// z-index. Inset shadows are skipped; paint those with [`Self::paint_inset_shadows`] |
| 4421 | /// after the element's background so they layer on top of the fill. |
| 4422 | /// |
| 4423 | /// This method should only be called as part of the paint phase of element drawing. |
| 4424 | pub fn paint_drop_shadows( |
| 4425 | &mut self, |
| 4426 | bounds: Bounds<Pixels>, |
| 4427 | corner_radii: Corners<Pixels>, |
| 4428 | shadows: &[BoxShadow], |
| 4429 | ) { |
| 4430 | self.invalidator.debug_assert_paint(); |
| 4431 | |
| 4432 | let scale_factor = self.scale_factor(); |
| 4433 | let content_mask = self.snapped_content_mask(); |
| 4434 | let opacity = self.element_opacity(); |
| 4435 | let element_bounds = self.cover_bounds(bounds); |
| 4436 | let element_corner_radii = corner_radii.scale(scale_factor); |
| 4437 | for shadow in shadows { |
| 4438 | if shadow.inset { |
| 4439 | continue; |
| 4440 | } |
| 4441 | let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius); |
| 4442 | self.next_frame.scene.insert_primitive(Shadow { |
| 4443 | order: 0, |
| 4444 | blur_radius: shadow.blur_radius.scale(scale_factor), |
| 4445 | bounds: self.cover_bounds(shadow_bounds), |
| 4446 | content_mask, |
| 4447 | corner_radii: corner_radii.scale(scale_factor), |
| 4448 | color: shadow.color.opacity(opacity), |
| 4449 | element_bounds, |
| 4450 | element_corner_radii, |
| 4451 | inset: 0, |
| 4452 | pad: 0, |
| 4453 | }); |
| 4454 | } |
| 4455 | } |
| 4456 | |
| 4457 | /// Paint the inset shadows from `shadows` into the scene at the current z-index. Should |
| 4458 | /// be called after the element's background so the shadow layers on top of the fill. |
| 4459 | /// Drop shadows are skipped; paint those with [`Self::paint_drop_shadows`] before the background. |
| 4460 | pub fn paint_inset_shadows( |
| 4461 | &mut self, |
| 4462 | bounds: Bounds<Pixels>, |
| 4463 | corner_radii: Corners<Pixels>, |
| 4464 | shadows: &[BoxShadow], |
| 4465 | ) { |
| 4466 | self.invalidator.debug_assert_paint(); |
| 4467 | |
| 4468 | let scale_factor = self.scale_factor(); |
| 4469 | let content_mask = self.snapped_content_mask(); |
| 4470 | let opacity = self.element_opacity(); |
| 4471 | let element_bounds = self.cover_bounds(bounds); |
| 4472 | let element_corner_radii = corner_radii.scale(scale_factor); |
| 4473 | for shadow in shadows { |
| 4474 | if !shadow.inset { |
| 4475 | continue; |
| 4476 | } |
| 4477 | let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius); |
| 4478 | // Clamp at zero so a large spread can't produce negative radii, which would |
| 4479 | // break the SDF in the shader. |
| 4480 | let zero = Pixels::ZERO; |
| 4481 | let hole_corner_radii = Corners { |
| 4482 | top_left: (corner_radii.top_left - shadow.spread_radius).max(zero), |
| 4483 | top_right: (corner_radii.top_right - shadow.spread_radius).max(zero), |
| 4484 | bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero), |
| 4485 | bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero), |
| 4486 | }; |
| 4487 | self.next_frame.scene.insert_primitive(Shadow { |
| 4488 | order: 0, |
| 4489 | blur_radius: shadow.blur_radius.scale(scale_factor), |
| 4490 | bounds: self.cover_bounds(hole), |
| 4491 | content_mask, |
| 4492 | corner_radii: hole_corner_radii.scale(scale_factor), |
| 4493 | color: shadow.color.opacity(opacity), |
| 4494 | element_bounds, |
| 4495 | element_corner_radii, |
| 4496 | inset: 1, |
| 4497 | pad: 0, |
| 4498 | }); |
| 4499 | } |
| 4500 | } |
| 4501 | |
| 4502 | fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> { |
| 4503 | let radii = &quad.corner_radii; |
| 4504 | let widths = &quad.border_widths; |
| 4505 | let edge_radii = Edges { |
| 4506 | top: radii.top_left.max(radii.top_right), |
| 4507 | right: radii.top_right.max(radii.bottom_right), |
| 4508 | bottom: radii.bottom_left.max(radii.bottom_right), |
| 4509 | left: radii.top_left.max(radii.bottom_left), |
| 4510 | }; |
| 4511 | |
| 4512 | let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0)); |
| 4513 | let inset_bounds = |top_left_inset, bottom_right_inset| { |
| 4514 | Bounds::from_corners( |
| 4515 | quad.bounds.origin + top_left_inset + antialias_inset, |
| 4516 | quad.bounds.bottom_right() - bottom_right_inset - antialias_inset, |
| 4517 | ) |
| 4518 | }; |
| 4519 | |
| 4520 | // Rounded corners need only be excluded on one axis. Either candidate |
| 4521 | // is empty of border pixels, so use the larger interior. |
| 4522 | let horizontal_band = inset_bounds( |
| 4523 | point(widths.left, widths.top.max(edge_radii.top)), |
| 4524 | point(widths.right, widths.bottom.max(edge_radii.bottom)), |
| 4525 | ); |
| 4526 | let vertical_band = inset_bounds( |
| 4527 | point(widths.left.max(edge_radii.left), widths.top), |
| 4528 | point(widths.right.max(edge_radii.right), widths.bottom), |
| 4529 | ); |
| 4530 | |
| 4531 | let area = |bounds: &Bounds<ScaledPixels>| { |
| 4532 | bounds.size.width.0.max(0.) * bounds.size.height.0.max(0.) |
| 4533 | }; |
| 4534 | if area(&horizontal_band) >= area(&vertical_band) { |
| 4535 | horizontal_band |
| 4536 | } else { |
| 4537 | vertical_band |
| 4538 | } |
| 4539 | } |
| 4540 | |
| 4541 | /// Paint one or more quads into the scene for the next frame at the current stacking context. |
| 4542 | /// Quads are colored rectangular regions with an optional background, border, and corner radius. |
| 4543 | /// see [`fill`], [`outline`], and [`quad`] to construct this type. |
| 4544 | /// |
| 4545 | /// This method should only be called as part of the paint phase of element drawing. |
| 4546 | /// |
| 4547 | /// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners |
| 4548 | /// where the circular arcs meet. This will not display well when combined with dashed borders. |
| 4549 | /// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds. |
| 4550 | pub fn paint_quad(&mut self, quad: PaintQuad) { |
| 4551 | self.invalidator.debug_assert_paint(); |
| 4552 | |
| 4553 | let opacity = self.element_opacity(); |
| 4554 | let snapped_bounds = self.snap_bounds(quad.bounds); |
| 4555 | let snapped_border_widths = self.snap_border_widths(quad.border_widths); |
| 4556 | let quad = Quad { |
| 4557 | order: 0, |
| 4558 | bounds: snapped_bounds, |
| 4559 | content_mask: self.snapped_content_mask(), |
| 4560 | background: quad.background.opacity(opacity), |
| 4561 | border_color: quad.border_color.opacity(opacity), |
| 4562 | corner_radii: quad.corner_radii.scale(self.scale_factor()), |
| 4563 | border_widths: snapped_border_widths, |
| 4564 | border_style: quad.border_style, |
| 4565 | }; |
| 4566 | |
| 4567 | if !quad.background.is_transparent() { |
| 4568 | self.next_frame.scene.insert_primitive(quad); |
| 4569 | return; |
| 4570 | } |
| 4571 | |
| 4572 | // Splitting a border-only quad around its empty interior avoids shading |
| 4573 | // every transparent pixel inside large outlines. |
| 4574 | let outer_bounds = quad.bounds; |
| 4575 | let inner_bounds = Self::largest_border_interior(&quad); |
| 4576 | |
| 4577 | if inner_bounds.is_empty() { |
| 4578 | self.next_frame.scene.insert_primitive(quad); |
| 4579 | return; |
| 4580 | } |
| 4581 | |
| 4582 | let strips = [ |
| 4583 | // Top |
| 4584 | Bounds::from_corners( |
| 4585 | outer_bounds.origin, |
| 4586 | point(outer_bounds.right(), inner_bounds.top()), |
| 4587 | ), |
| 4588 | // Bottom |
| 4589 | Bounds::from_corners( |
| 4590 | point(outer_bounds.left(), inner_bounds.bottom()), |
| 4591 | outer_bounds.bottom_right(), |
| 4592 | ), |
| 4593 | // Left |
| 4594 | Bounds::from_corners( |
| 4595 | point(outer_bounds.left(), inner_bounds.top()), |
| 4596 | inner_bounds.bottom_left(), |
| 4597 | ), |
| 4598 | // Right |
| 4599 | Bounds::from_corners( |
| 4600 | inner_bounds.top_right(), |
| 4601 | point(outer_bounds.right(), inner_bounds.bottom()), |
| 4602 | ), |
| 4603 | ]; |
| 4604 | |
| 4605 | for strip in strips { |
| 4606 | let content_mask_bounds = quad.content_mask.bounds.intersect(&strip); |
| 4607 | if !content_mask_bounds.is_empty() { |
| 4608 | self.next_frame.scene.insert_primitive(Quad { |
| 4609 | content_mask: ContentMask { |
| 4610 | bounds: content_mask_bounds, |
| 4611 | }, |
| 4612 | ..quad |
| 4613 | }); |
| 4614 | } |
| 4615 | } |
| 4616 | } |
| 4617 | |
| 4618 | /// Paint the given `Path` into the scene for the next frame at the current z-index. |
| 4619 | /// |
| 4620 | /// This method should only be called as part of the paint phase of element drawing. |
| 4621 | pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) { |
| 4622 | self.invalidator.debug_assert_paint(); |
| 4623 | |
| 4624 | let scale_factor = self.scale_factor(); |
| 4625 | let content_mask = self.content_mask(); |
| 4626 | let opacity = self.element_opacity(); |
| 4627 | path.content_mask = content_mask; |
| 4628 | let color: Background = color.into(); |
| 4629 | path.color = color.opacity(opacity); |
| 4630 | self.next_frame |
| 4631 | .scene |
| 4632 | .insert_primitive(path.scale(scale_factor)); |
| 4633 | } |
| 4634 | |
| 4635 | /// Paint an underline into the scene for the next frame at the current z-index. |
| 4636 | /// |
| 4637 | /// This method should only be called as part of the paint phase of element drawing. |
| 4638 | pub fn paint_underline( |
| 4639 | &mut self, |
| 4640 | origin: Point<Pixels>, |
| 4641 | width: Pixels, |
| 4642 | style: &UnderlineStyle, |
| 4643 | ) { |
| 4644 | self.invalidator.debug_assert_paint(); |
| 4645 | let underline = self.underline(origin, width, style); |
| 4646 | self.next_frame.scene.insert_primitive(underline); |
| 4647 | } |
| 4648 | |
| 4649 | /// Paint a strikethrough into the scene for the next frame at the current z-index. |
| 4650 | /// |
| 4651 | /// This method should only be called as part of the paint phase of element drawing. |
| 4652 | pub fn paint_strikethrough( |
| 4653 | &mut self, |
| 4654 | origin: Point<Pixels>, |
| 4655 | width: Pixels, |
| 4656 | style: &StrikethroughStyle, |
| 4657 | ) { |
| 4658 | self.invalidator.debug_assert_paint(); |
| 4659 | |
| 4660 | let scale_factor = self.scale_factor(); |
| 4661 | let height = style.thickness; |
| 4662 | let bounds = Bounds { |
| 4663 | origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))), |
| 4664 | size: size(self.snap_stroke(width), self.snap_stroke(height)), |
| 4665 | }; |
| 4666 | let opacity = self.element_opacity(); |
| 4667 | |
| 4668 | self.next_frame.scene.insert_primitive(Underline { |
| 4669 | order: 0, |
| 4670 | pad: 0, |
| 4671 | bounds, |
| 4672 | content_mask: self.snapped_content_mask(), |
| 4673 | thickness: self.snap_stroke(style.thickness), |
| 4674 | color: style.color.unwrap_or_default().opacity(opacity), |
| 4675 | wavy: false.into(), |
| 4676 | }); |
| 4677 | } |
| 4678 | |
| 4679 | /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index. |
| 4680 | /// |
| 4681 | /// The y component of the origin is the baseline of the glyph. |
| 4682 | /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or |
| 4683 | /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem). |
| 4684 | /// This method is only useful if you need to paint a single glyph that has already been shaped. |
| 4685 | /// |
| 4686 | /// This method should only be called as part of the paint phase of element drawing. |
| 4687 | pub fn paint_glyph( |
| 4688 | &mut self, |
| 4689 | origin: Point<Pixels>, |
| 4690 | font_id: FontId, |
| 4691 | glyph_id: GlyphId, |
| 4692 | font_size: Pixels, |
| 4693 | color: Hsla, |
| 4694 | ) -> Result<()> { |
| 4695 | self.invalidator.debug_assert_paint(); |
| 4696 | |
| 4697 | let element_opacity = self.element_opacity(); |
| 4698 | let scale_factor = self.scale_factor(); |
| 4699 | let glyph_origin = origin.scale(scale_factor); |
| 4700 | |
| 4701 | let quantized_origin = Point::new( |
| 4702 | round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32) |
| 4703 | / SUBPIXEL_VARIANTS_X as f32, |
| 4704 | round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32) |
| 4705 | / SUBPIXEL_VARIANTS_Y as f32, |
| 4706 | ); |
| 4707 | let subpixel_variant = Point::new( |
| 4708 | (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8, |
| 4709 | (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8, |
| 4710 | ); |
| 4711 | let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc())); |
| 4712 | let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size); |
| 4713 | let dilation = self.text_system().glyph_dilation_for_color(color); |
| 4714 | let params = RenderGlyphParams { |
| 4715 | font_id, |
| 4716 | glyph_id, |
| 4717 | font_size, |
| 4718 | subpixel_variant, |
| 4719 | scale_factor, |
| 4720 | is_emoji: false, |
| 4721 | subpixel_rendering, |
| 4722 | dilation, |
| 4723 | }; |
| 4724 | |
| 4725 | let raster_bounds = self.text_system().raster_bounds(¶ms)?; |
| 4726 | if !raster_bounds.is_zero() { |
| 4727 | let tile = self |
| 4728 | .sprite_atlas |
| 4729 | .get_or_insert_with(params.clone().into(), &mut || { |
| 4730 | let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?; |
| 4731 | Ok(Some((size, Cow::Owned(bytes)))) |
| 4732 | })? |
| 4733 | .expect("Callback above only errors or returns Some"); |
| 4734 | let bounds = Bounds { |
| 4735 | origin: integer_origin + raster_bounds.origin.map(Into::into), |
| 4736 | size: tile.bounds.size.map(Into::into), |
| 4737 | }; |
| 4738 | let content_mask = self.snapped_content_mask(); |
| 4739 | |
| 4740 | if subpixel_rendering { |
| 4741 | self.next_frame.scene.insert_primitive(SubpixelSprite { |
| 4742 | order: 0, |
| 4743 | pad: 0, |
| 4744 | bounds, |
| 4745 | content_mask, |
| 4746 | color: color.opacity(element_opacity), |
| 4747 | tile, |
| 4748 | transformation: TransformationMatrix::unit(), |
| 4749 | }); |
| 4750 | } else { |
| 4751 | self.next_frame.scene.insert_primitive(MonochromeSprite { |
| 4752 | order: 0, |
| 4753 | pad: 0, |
| 4754 | bounds, |
| 4755 | content_mask, |
| 4756 | color: color.opacity(element_opacity), |
| 4757 | tile, |
| 4758 | transformation: TransformationMatrix::unit(), |
| 4759 | }); |
| 4760 | } |
| 4761 | } |
| 4762 | Ok(()) |
| 4763 | } |
| 4764 | |
| 4765 | fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool { |
| 4766 | if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque { |
| 4767 | return false; |
| 4768 | } |
| 4769 | |
| 4770 | if !self.platform_window.is_subpixel_rendering_supported() { |
| 4771 | return false; |
| 4772 | } |
| 4773 | |
| 4774 | let mode = match self.text_rendering_mode.get() { |
| 4775 | TextRenderingMode::PlatformDefault => self |
| 4776 | .text_system() |
| 4777 | .recommended_rendering_mode(font_id, font_size), |
| 4778 | mode => mode, |
| 4779 | }; |
| 4780 | |
| 4781 | mode == TextRenderingMode::Subpixel |
| 4782 | } |
| 4783 | |
| 4784 | /// Paints an emoji glyph into the scene for the next frame at the current z-index. |
| 4785 | /// |
| 4786 | /// The y component of the origin is the baseline of the glyph. |
| 4787 | /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or |
| 4788 | /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem). |
| 4789 | /// This method is only useful if you need to paint a single emoji that has already been shaped. |
| 4790 | /// |
| 4791 | /// This method should only be called as part of the paint phase of element drawing. |
| 4792 | pub fn paint_emoji( |
| 4793 | &mut self, |
| 4794 | origin: Point<Pixels>, |
| 4795 | font_id: FontId, |
| 4796 | glyph_id: GlyphId, |
| 4797 | font_size: Pixels, |
| 4798 | ) -> Result<()> { |
| 4799 | self.invalidator.debug_assert_paint(); |
| 4800 | |
| 4801 | let scale_factor = self.scale_factor(); |
| 4802 | let glyph_origin = origin.scale(scale_factor); |
| 4803 | let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0))); |
| 4804 | let params = RenderGlyphParams { |
| 4805 | font_id, |
| 4806 | glyph_id, |
| 4807 | font_size, |
| 4808 | subpixel_variant: Default::default(), |
| 4809 | scale_factor, |
| 4810 | is_emoji: true, |
| 4811 | subpixel_rendering: false, |
| 4812 | dilation: 0, |
| 4813 | }; |
| 4814 | |
| 4815 | let raster_bounds = self.text_system().raster_bounds(¶ms)?; |
| 4816 | if !raster_bounds.is_zero() { |
| 4817 | let tile = self |
| 4818 | .sprite_atlas |
| 4819 | .get_or_insert_with(params.clone().into(), &mut || { |
| 4820 | let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?; |
| 4821 | Ok(Some((size, Cow::Owned(bytes)))) |
| 4822 | })? |
| 4823 | .expect("Callback above only errors or returns Some"); |
| 4824 | |
| 4825 | let bounds = Bounds { |
| 4826 | origin: integer_origin + raster_bounds.origin.map(Into::into), |
| 4827 | size: tile.bounds.size.map(Into::into), |
| 4828 | }; |
| 4829 | let content_mask = self.snapped_content_mask(); |
| 4830 | let opacity = self.element_opacity(); |
| 4831 | |
| 4832 | self.next_frame.scene.insert_primitive(PolychromeSprite { |
| 4833 | order: 0, |
| 4834 | pad: 0, |
| 4835 | grayscale: false.into(), |
| 4836 | bounds, |
| 4837 | corner_radii: Default::default(), |
| 4838 | content_mask, |
| 4839 | tile, |
| 4840 | opacity, |
| 4841 | }); |
| 4842 | } |
| 4843 | Ok(()) |
| 4844 | } |
| 4845 | |
| 4846 | /// Paint a monochrome SVG into the scene for the next frame at the current stacking context. |
| 4847 | /// |
| 4848 | /// This method should only be called as part of the paint phase of element drawing. |
| 4849 | pub fn paint_svg( |
| 4850 | &mut self, |
| 4851 | bounds: Bounds<Pixels>, |
| 4852 | path: SharedString, |
| 4853 | mut data: Option<&[u8]>, |
| 4854 | transformation: TransformationMatrix, |
| 4855 | color: Hsla, |
| 4856 | cx: &App, |
| 4857 | ) -> Result<()> { |
| 4858 | self.invalidator.debug_assert_paint(); |
| 4859 | |
| 4860 | let element_opacity = self.element_opacity(); |
| 4861 | let bounds = self.snap_bounds(bounds); |
| 4862 | |
| 4863 | let params = RenderSvgParams { |
| 4864 | path, |
| 4865 | size: bounds.size.map(|pixels| { |
| 4866 | DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32) |
| 4867 | }), |
| 4868 | }; |
| 4869 | |
| 4870 | let Some(tile) = |
| 4871 | self.sprite_atlas |
| 4872 | .get_or_insert_with(params.clone().into(), &mut || { |
| 4873 | let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)? |
| 4874 | else { |
| 4875 | return Ok(None); |
| 4876 | }; |
| 4877 | Ok(Some((size, Cow::Owned(bytes)))) |
| 4878 | })? |
| 4879 | else { |
| 4880 | return Ok(()); |
| 4881 | }; |
| 4882 | let content_mask = self.snapped_content_mask(); |
| 4883 | let svg_bounds = Bounds { |
| 4884 | origin: bounds.center() |
| 4885 | - Point::new( |
| 4886 | ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.), |
| 4887 | ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.), |
| 4888 | ), |
| 4889 | size: tile |
| 4890 | .bounds |
| 4891 | .size |
| 4892 | .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)), |
| 4893 | }; |
| 4894 | let final_bounds = svg_bounds |
| 4895 | .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0))) |
| 4896 | .map_size(|size| size.ceil()); |
| 4897 | |
| 4898 | self.next_frame.scene.insert_primitive(MonochromeSprite { |
| 4899 | order: 0, |
| 4900 | pad: 0, |
| 4901 | bounds: final_bounds, |
| 4902 | content_mask, |
| 4903 | color: color.opacity(element_opacity), |
| 4904 | tile, |
| 4905 | transformation, |
| 4906 | }); |
| 4907 | |
| 4908 | Ok(()) |
| 4909 | } |
| 4910 | |
| 4911 | /// Paint an image into the scene for the next frame at the current z-index. |
| 4912 | /// This method will panic if the frame_index is not valid |
| 4913 | /// |
| 4914 | /// This method should only be called as part of the paint phase of element drawing. |
| 4915 | /// Paint an image into `bounds`, positioning and scaling it according to `image_bounds`. |
| 4916 | /// |
| 4917 | /// The visible region rendered is `bounds.intersect(&image_bounds)`, with `corner_radii` |
| 4918 | /// applied to `bounds`. |
| 4919 | pub fn paint_image( |
| 4920 | &mut self, |
| 4921 | bounds: Bounds<Pixels>, |
| 4922 | image_bounds: Bounds<Pixels>, |
| 4923 | corner_radii: Corners<Pixels>, |
| 4924 | data: Arc<RenderImage>, |
| 4925 | frame_index: usize, |
| 4926 | grayscale: bool, |
| 4927 | ) -> Result<()> { |
| 4928 | self.invalidator.debug_assert_paint(); |
| 4929 | |
| 4930 | let visible_bounds = bounds.intersect(&image_bounds); |
| 4931 | if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO { |
| 4932 | return Ok(()); |
| 4933 | } |
| 4934 | if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO { |
| 4935 | return Ok(()); |
| 4936 | } |
| 4937 | |
| 4938 | let params = RenderImageParams { |
| 4939 | image_id: data.id, |
| 4940 | frame_index, |
| 4941 | }; |
| 4942 | |
| 4943 | let tile = self |
| 4944 | .sprite_atlas |
| 4945 | .get_or_insert_with(params.into(), &mut || { |
| 4946 | Ok(Some(( |
| 4947 | data.size(frame_index), |
| 4948 | Cow::Borrowed( |
| 4949 | data.as_bytes(frame_index) |
| 4950 | .expect("It's the caller's job to pass a valid frame index"), |
| 4951 | ), |
| 4952 | ))) |
| 4953 | })? |
| 4954 | .expect("Callback above only returns Some"); |
| 4955 | |
| 4956 | let visible_bounds_snapped = self.snap_bounds(visible_bounds); |
| 4957 | |
| 4958 | let sub_tile = if visible_bounds == image_bounds { |
| 4959 | tile |
| 4960 | } else { |
| 4961 | let x_offset_ratio = |
| 4962 | (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width; |
| 4963 | let y_offset_ratio = |
| 4964 | (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height; |
| 4965 | let width_ratio = visible_bounds.size.width / image_bounds.size.width; |
| 4966 | let height_ratio = visible_bounds.size.height / image_bounds.size.height; |
| 4967 | |
| 4968 | let tile_origin_x = tile.bounds.origin.x.0; |
| 4969 | let tile_origin_y = tile.bounds.origin.y.0; |
| 4970 | let tile_width = tile.bounds.size.width.0; |
| 4971 | let tile_height = tile.bounds.size.height.0; |
| 4972 | |
| 4973 | let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32; |
| 4974 | let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32; |
| 4975 | let sub_width = (width_ratio * tile_width as f32).round() as i32; |
| 4976 | let sub_height = (height_ratio * tile_height as f32).round() as i32; |
| 4977 | |
| 4978 | let max_x = tile_origin_x + tile_width; |
| 4979 | let max_y = tile_origin_y + tile_height; |
| 4980 | |
| 4981 | let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x); |
| 4982 | let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y); |
| 4983 | let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0); |
| 4984 | let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0); |
| 4985 | |
| 4986 | AtlasTile { |
| 4987 | bounds: Bounds { |
| 4988 | origin: point( |
| 4989 | DevicePixels(clamped_origin_x), |
| 4990 | DevicePixels(clamped_origin_y), |
| 4991 | ), |
| 4992 | size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)), |
| 4993 | }, |
| 4994 | ..tile |
| 4995 | } |
| 4996 | }; |
| 4997 | |
| 4998 | let content_mask = self.snapped_content_mask(); |
| 4999 | let corner_radii = corner_radii |
| 5000 | .clamp_radii_for_quad_size(visible_bounds.size) |
| 5001 | .scale(self.scale_factor()); |
| 5002 | let opacity = self.element_opacity(); |
| 5003 | |
| 5004 | self.next_frame.scene.insert_primitive(PolychromeSprite { |
| 5005 | order: 0, |
| 5006 | pad: 0, |
| 5007 | grayscale: grayscale.into(), |
| 5008 | bounds: visible_bounds_snapped, |
| 5009 | content_mask, |
| 5010 | corner_radii, |
| 5011 | tile: sub_tile, |
| 5012 | opacity, |
| 5013 | }); |
| 5014 | Ok(()) |
| 5015 | } |
| 5016 | |
| 5017 | /// Paint a surface into the scene for the next frame at the current z-index. |
| 5018 | /// |
| 5019 | /// This method should only be called as part of the paint phase of element drawing. |
| 5020 | #[cfg(any(target_os = "macos", target_os = "ios"))] |
| 5021 | pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) { |
| 5022 | use crate::PaintSurface; |
| 5023 | |
| 5024 | self.invalidator.debug_assert_paint(); |
| 5025 | |
| 5026 | let bounds = self.snap_bounds(bounds); |
| 5027 | let content_mask = self.snapped_content_mask(); |
| 5028 | self.next_frame.scene.insert_primitive(PaintSurface { |
| 5029 | order: 0, |
| 5030 | bounds, |
| 5031 | content_mask, |
| 5032 | image_buffer, |
| 5033 | }); |
| 5034 | } |
| 5035 | |
| 5036 | /// Removes an image from the sprite atlas. |
| 5037 | pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> { |
| 5038 | for frame_index in 0..data.frame_count() { |
| 5039 | let params = RenderImageParams { |
| 5040 | image_id: data.id, |
| 5041 | frame_index, |
| 5042 | }; |
| 5043 | |
| 5044 | self.sprite_atlas.remove(¶ms.clone().into()); |
| 5045 | } |
| 5046 | |
| 5047 | Ok(()) |
| 5048 | } |
| 5049 | |
| 5050 | /// Returns whether every frame of an image is present in the sprite atlas. |
| 5051 | #[cfg(any(test, feature = "test-support"))] |
| 5052 | pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool { |
| 5053 | data.frame_count() > 0 |
| 5054 | && (0..data.frame_count()).all(|frame_index| { |
| 5055 | self.sprite_atlas.contains( |
| 5056 | &RenderImageParams { |
| 5057 | image_id: data.id, |
| 5058 | frame_index, |
| 5059 | } |
| 5060 | .into(), |
| 5061 | ) |
| 5062 | }) |
| 5063 | } |
| 5064 | |
| 5065 | /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which |
| 5066 | /// layout is being requested, along with the layout ids of any children. This method is called during |
| 5067 | /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout. |
| 5068 | /// |
| 5069 | /// This method should only be called as part of the request_layout or prepaint phase of element drawing. |
| 5070 | #[must_use] |
| 5071 | pub fn request_layout( |
| 5072 | &mut self, |
| 5073 | style: Style, |
| 5074 | children: impl IntoIterator<Item = LayoutId>, |
| 5075 | cx: &mut App, |
| 5076 | ) -> LayoutId { |
| 5077 | self.invalidator.debug_assert_prepaint(); |
| 5078 | |
| 5079 | cx.layout_id_buffer.clear(); |
| 5080 | cx.layout_id_buffer.extend(children); |
| 5081 | let rem_size = self.rem_size(); |
| 5082 | let scale_factor = self.scale_factor(); |
| 5083 | |
| 5084 | self.layout_engine.as_mut().unwrap().request_layout( |
| 5085 | style, |
| 5086 | rem_size, |
| 5087 | scale_factor, |
| 5088 | &cx.layout_id_buffer, |
| 5089 | ) |
| 5090 | } |
| 5091 | |
| 5092 | /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children, |
| 5093 | /// this variant takes a function that is invoked during layout so you can use arbitrary logic to |
| 5094 | /// determine the element's size. One place this is used internally is when measuring text. |
| 5095 | /// |
| 5096 | /// The given closure is invoked at layout time wi |
| 5097 | … afgekapt |