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