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