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