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