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