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