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: bounds
2601 .map_origin(|origin| origin.floor())
2602 .map_size(|size| size.ceil()),
2603 content_mask,
2604 color,
2605 tile,
2606 transformation,
2607 });
2608
2609 Ok(())
2610 }
2611
2612 /// Paint an image into the scene for the next frame at the current z-index.
2613 ///
2614 /// This method should only be called as part of the paint phase of element drawing.
2615 pub fn paint_image(
2616 &mut self,
2617 bounds: Bounds<Pixels>,
2618 corner_radii: Corners<Pixels>,
2619 data: Arc<ImageData>,
2620 frame_index: usize,
2621 grayscale: bool,
2622 ) -> Result<()> {
2623 debug_assert_eq!(
2624 self.window.draw_phase,
2625 DrawPhase::Paint,
2626 "this method can only be called during paint"
2627 );
2628
2629 let scale_factor = self.scale_factor();
2630 let bounds = bounds.scale(scale_factor);
2631 let params = RenderImageParams {
2632 image_id: data.id,
2633 frame_index,
2634 };
2635
2636 let tile = self
2637 .window
2638 .sprite_atlas
2639 .get_or_insert_with(¶ms.clone().into(), &mut || {
2640 Ok(Some((
2641 data.size(frame_index),
2642 Cow::Borrowed(data.as_bytes(frame_index)),
2643 )))
2644 })?
2645 .expect("Callback above only returns Some");
2646 let content_mask = self.content_mask().scale(scale_factor);
2647 let corner_radii = corner_radii.scale(scale_factor);
2648
2649 self.window
2650 .next_frame
2651 .scene
2652 .insert_primitive(PolychromeSprite {
2653 order: 0,
2654 grayscale,
2655 bounds,
2656 content_mask,
2657 corner_radii,
2658 tile,
2659 });
2660 Ok(())
2661 }
2662
2663 /// Paint a surface into the scene for the next frame at the current z-index.
2664 ///
2665 /// This method should only be called as part of the paint phase of element drawing.
2666 #[cfg(target_os = "macos")]
2667 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
2668 debug_assert_eq!(
2669 self.window.draw_phase,
2670 DrawPhase::Paint,
2671 "this method can only be called during paint"
2672 );
2673
2674 let scale_factor = self.scale_factor();
2675 let bounds = bounds.scale(scale_factor);
2676 let content_mask = self.content_mask().scale(scale_factor);
2677 self.window
2678 .next_frame
2679 .scene
2680 .insert_primitive(crate::Surface {
2681 order: 0,
2682 bounds,
2683 content_mask,
2684 image_buffer,
2685 });
2686 }
2687
2688 #[must_use]
2689 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
2690 /// layout is being requested, along with the layout ids of any children. This method is called during
2691 /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
2692 ///
2693 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2694 pub fn request_layout(
2695 &mut self,
2696 style: Style,
2697 children: impl IntoIterator<Item = LayoutId>,
2698 ) -> LayoutId {
2699 debug_assert_eq!(
2700 self.window.draw_phase,
2701 DrawPhase::Prepaint,
2702 "this method can only be called during request_layout, or prepaint"
2703 );
2704
2705 self.app.layout_id_buffer.clear();
2706 self.app.layout_id_buffer.extend(children);
2707 let rem_size = self.rem_size();
2708
2709 self.window.layout_engine.as_mut().unwrap().request_layout(
2710 style,
2711 rem_size,
2712 &self.app.layout_id_buffer,
2713 )
2714 }
2715
2716 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
2717 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
2718 /// determine the element's size. One place this is used internally is when measuring text.
2719 ///
2720 /// The given closure is invoked at layout time with the known dimensions and available space and
2721 /// returns a `Size`.
2722 ///
2723 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2724 pub fn request_measured_layout<
2725 F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
2726 + 'static,
2727 >(
2728 &mut self,
2729 style: Style,
2730 measure: F,
2731 ) -> LayoutId {
2732 debug_assert_eq!(
2733 self.window.draw_phase,
2734 DrawPhase::Prepaint,
2735 "this method can only be called during request_layout, or prepaint"
2736 );
2737
2738 let rem_size = self.rem_size();
2739 self.window
2740 .layout_engine
2741 .as_mut()
2742 .unwrap()
2743 .request_measured_layout(style, rem_size, measure)
2744 }
2745
2746 /// Compute the layout for the given id within the given available space.
2747 /// This method is called for its side effect, typically by the framework prior to painting.
2748 /// After calling it, you can request the bounds of the given layout node id or any descendant.
2749 ///
2750 /// This method should only be called as part of the prepaint phase of element drawing.
2751 pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
2752 debug_assert_eq!(
2753 self.window.draw_phase,
2754 DrawPhase::Prepaint,
2755 "this method can only be called during request_layout, or prepaint"
2756 );
2757
2758 let mut layout_engine = self.window.layout_engine.take().unwrap();
2759 layout_engine.compute_layout(layout_id, available_space, self);
2760 self.window.layout_engine = Some(layout_engine);
2761 }
2762
2763 /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
2764 /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
2765 ///
2766 /// This method should only be called as part of element drawing.
2767 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
2768 debug_assert_eq!(
2769 self.window.draw_phase,
2770 DrawPhase::Prepaint,
2771 "this method can only be called during request_layout, prepaint, or paint"
2772 );
2773
2774 let mut bounds = self
2775 .window
2776 .layout_engine
2777 .as_mut()
2778 .unwrap()
2779 .layout_bounds(layout_id)
2780 .map(Into::into);
2781 bounds.origin += self.element_offset();
2782 bounds
2783 }
2784
2785 /// This method should be called during `prepaint`. You can use
2786 /// the returned [Hitbox] during `paint` or in an event handler
2787 /// to determine whether the inserted hitbox was the topmost.
2788 ///
2789 /// This method should only be called as part of the prepaint phase of element drawing.
2790 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, opaque: bool) -> Hitbox {
2791 debug_assert_eq!(
2792 self.window.draw_phase,
2793 DrawPhase::Prepaint,
2794 "this method can only be called during prepaint"
2795 );
2796
2797 let content_mask = self.content_mask();
2798 let window = &mut self.window;
2799 let id = window.next_hitbox_id;
2800 window.next_hitbox_id.0 += 1;
2801 let hitbox = Hitbox {
2802 id,
2803 bounds,
2804 content_mask,
2805 opaque,
2806 };
2807 window.next_frame.hitboxes.push(hitbox.clone());
2808 hitbox
2809 }
2810
2811 /// Sets the key context for the current element. This context will be used to translate
2812 /// keybindings into actions.
2813 ///
2814 /// This method should only be called as part of the paint phase of element drawing.
2815 pub fn set_key_context(&mut self, context: KeyContext) {
2816 debug_assert_eq!(
2817 self.window.draw_phase,
2818 DrawPhase::Paint,
2819 "this method can only be called during paint"
2820 );
2821 self.window
2822 .next_frame
2823 .dispatch_tree
2824 .set_key_context(context);
2825 }
2826
2827 /// Sets the focus handle for the current element. This handle will be used to manage focus state
2828 /// and keyboard event dispatch for the element.
2829 ///
2830 /// This method should only be called as part of the prepaint phase of element drawing.
2831 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle) {
2832 debug_assert_eq!(
2833 self.window.draw_phase,
2834 DrawPhase::Prepaint,
2835 "this method can only be called during prepaint"
2836 );
2837 if focus_handle.is_focused(self) {
2838 self.window.next_frame.focus = Some(focus_handle.id);
2839 }
2840 self.window
2841 .next_frame
2842 .dispatch_tree
2843 .set_focus_id(focus_handle.id);
2844 }
2845
2846 /// Sets the view id for the current element, which will be used to manage view caching.
2847 ///
2848 /// This method should only be called as part of element prepaint. We plan on removing this
2849 /// method eventually when we solve some issues that require us to construct editor elements
2850 /// directly instead of always using editors via views.
2851 pub fn set_view_id(&mut self, view_id: EntityId) {
2852 debug_assert_eq!(
2853 self.window.draw_phase,
2854 DrawPhase::Prepaint,
2855 "this method can only be called during prepaint"
2856 );
2857 self.window.next_frame.dispatch_tree.set_view_id(view_id);
2858 }
2859
2860 /// Get the last view id for the current element
2861 pub fn parent_view_id(&mut self) -> Option<EntityId> {
2862 self.window.next_frame.dispatch_tree.parent_view_id()
2863 }
2864
2865 /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
2866 /// platform to receive textual input with proper integration with concerns such
2867 /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
2868 /// rendered.
2869 ///
2870 /// This method should only be called as part of the paint phase of element drawing.
2871 ///
2872 /// [element_input_handler]: crate::ElementInputHandler
2873 pub fn handle_input(&mut self, focus_handle: &FocusHandle, input_handler: impl InputHandler) {
2874 debug_assert_eq!(
2875 self.window.draw_phase,
2876 DrawPhase::Paint,
2877 "this method can only be called during paint"
2878 );
2879
2880 if focus_handle.is_focused(self) {
2881 let cx = self.to_async();
2882 self.window
2883 .next_frame
2884 .input_handlers
2885 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
2886 }
2887 }
2888
2889 /// Register a mouse event listener on the window for the next frame. The type of event
2890 /// is determined by the first parameter of the given listener. When the next frame is rendered
2891 /// the listener will be cleared.
2892 ///
2893 /// This method should only be called as part of the paint phase of element drawing.
2894 pub fn on_mouse_event<Event: MouseEvent>(
2895 &mut self,
2896 mut handler: impl FnMut(&Event, DispatchPhase, &mut WindowContext) + 'static,
2897 ) {
2898 debug_assert_eq!(
2899 self.window.draw_phase,
2900 DrawPhase::Paint,
2901 "this method can only be called during paint"
2902 );
2903
2904 self.window.next_frame.mouse_listeners.push(Some(Box::new(
2905 move |event: &dyn Any, phase: DispatchPhase, cx: &mut WindowContext<'_>| {
2906 if let Some(event) = event.downcast_ref() {
2907 handler(event, phase, cx)
2908 }
2909 },
2910 )));
2911 }
2912
2913 /// Register a key event listener on the window for the next frame. The type of event
2914 /// is determined by the first parameter of the given listener. When the next frame is rendered
2915 /// the listener will be cleared.
2916 ///
2917 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2918 /// a specific need to register a global listener.
2919 ///
2920 /// This method should only be called as part of the paint phase of element drawing.
2921 pub fn on_key_event<Event: KeyEvent>(
2922 &mut self,
2923 listener: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
2924 ) {
2925 debug_assert_eq!(
2926 self.window.draw_phase,
2927 DrawPhase::Paint,
2928 "this method can only be called during paint"
2929 );
2930
2931 self.window.next_frame.dispatch_tree.on_key_event(Rc::new(
2932 move |event: &dyn Any, phase, cx: &mut WindowContext<'_>| {
2933 if let Some(event) = event.downcast_ref::<Event>() {
2934 listener(event, phase, cx)
2935 }
2936 },
2937 ));
2938 }
2939
2940 /// Register a modifiers changed event listener on the window for the next frame.
2941 ///
2942 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2943 /// a specific need to register a global listener.
2944 ///
2945 /// This method should only be called as part of the paint phase of element drawing.
2946 pub fn on_modifiers_changed(
2947 &mut self,
2948 listener: impl Fn(&ModifiersChangedEvent, &mut WindowContext) + 'static,
2949 ) {
2950 debug_assert_eq!(
2951 self.window.draw_phase,
2952 DrawPhase::Paint,
2953 "this method can only be called during paint"
2954 );
2955
2956 self.window
2957 .next_frame
2958 .dispatch_tree
2959 .on_modifiers_changed(Rc::new(
2960 move |event: &ModifiersChangedEvent, cx: &mut WindowContext<'_>| {
2961 listener(event, cx)
2962 },
2963 ));
2964 }
2965
2966 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2967 /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
2968 /// Returns a subscription and persists until the subscription is dropped.
2969 pub fn on_focus_in(
2970 &mut self,
2971 handle: &FocusHandle,
2972 mut listener: impl FnMut(&mut WindowContext) + 'static,
2973 ) -> Subscription {
2974 let focus_id = handle.id;
2975 let (subscription, activate) =
2976 self.window.new_focus_listener(Box::new(move |event, cx| {
2977 if event.is_focus_in(focus_id) {
2978 listener(cx);
2979 }
2980 true
2981 }));
2982 self.app.defer(move |_| activate());
2983 subscription
2984 }
2985
2986 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2987 /// Returns a subscription and persists until the subscription is dropped.
2988 pub fn on_focus_out(
2989 &mut self,
2990 handle: &FocusHandle,
2991 mut listener: impl FnMut(FocusOutEvent, &mut WindowContext) + 'static,
2992 ) -> Subscription {
2993 let focus_id = handle.id;
2994 let (subscription, activate) =
2995 self.window.new_focus_listener(Box::new(move |event, cx| {
2996 if let Some(blurred_id) = event.previous_focus_path.last().copied() {
2997 if event.is_focus_out(focus_id) {
2998 let event = FocusOutEvent {
2999 blurred: WeakFocusHandle {
3000 id: blurred_id,
3001 handles: Arc::downgrade(&cx.window.focus_handles),
3002 },
3003 };
3004 listener(event, cx)
3005 }
3006 }
3007 true
3008 }));
3009 self.app.defer(move |_| activate());
3010 subscription
3011 }
3012
3013 fn reset_cursor_style(&self) {
3014 // Set the cursor only if we're the active window.
3015 if self.is_window_hovered() {
3016 let style = self
3017 .window
3018 .rendered_frame
3019 .cursor_styles
3020 .iter()
3021 .rev()
3022 .find(|request| request.hitbox_id.is_hovered(self))
3023 .map(|request| request.style)
3024 .unwrap_or(CursorStyle::Arrow);
3025 self.platform.set_cursor_style(style);
3026 }
3027 }
3028
3029 /// Dispatch a given keystroke as though the user had typed it.
3030 /// You can create a keystroke with Keystroke::parse("").
3031 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke) -> bool {
3032 let keystroke = keystroke.with_simulated_ime();
3033 let result = self.dispatch_event(PlatformInput::KeyDown(KeyDownEvent {
3034 keystroke: keystroke.clone(),
3035 is_held: false,
3036 }));
3037 if !result.propagate {
3038 return true;
3039 }
3040
3041 if let Some(input) = keystroke.ime_key {
3042 if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
3043 input_handler.dispatch_input(&input, self);
3044 self.window.platform_window.set_input_handler(input_handler);
3045 return true;
3046 }
3047 }
3048
3049 false
3050 }
3051
3052 /// Represent this action as a key binding string, to display in the UI.
3053 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
3054 self.bindings_for_action(action)
3055 .into_iter()
3056 .next()
3057 .map(|binding| {
3058 binding
3059 .keystrokes()
3060 .iter()
3061 .map(ToString::to_string)
3062 .collect::<Vec<_>>()
3063 .join(" ")
3064 })
3065 .unwrap_or_else(|| action.name().to_string())
3066 }
3067
3068 /// Dispatch a mouse or keyboard event on the window.
3069 #[profiling::function]
3070 pub fn dispatch_event(&mut self, event: PlatformInput) -> DispatchEventResult {
3071 self.window.last_input_timestamp.set(Instant::now());
3072 // Handlers may set this to false by calling `stop_propagation`.
3073 self.app.propagate_event = true;
3074 // Handlers may set this to true by calling `prevent_default`.
3075 self.window.default_prevented = false;
3076
3077 let event = match event {
3078 // Track the mouse position with our own state, since accessing the platform
3079 // API for the mouse position can only occur on the main thread.
3080 PlatformInput::MouseMove(mouse_move) => {
3081 self.window.mouse_position = mouse_move.position;
3082 self.window.modifiers = mouse_move.modifiers;
3083 PlatformInput::MouseMove(mouse_move)
3084 }
3085 PlatformInput::MouseDown(mouse_down) => {
3086 self.window.mouse_position = mouse_down.position;
3087 self.window.modifiers = mouse_down.modifiers;
3088 PlatformInput::MouseDown(mouse_down)
3089 }
3090 PlatformInput::MouseUp(mouse_up) => {
3091 self.window.mouse_position = mouse_up.position;
3092 self.window.modifiers = mouse_up.modifiers;
3093 PlatformInput::MouseUp(mouse_up)
3094 }
3095 PlatformInput::MouseExited(mouse_exited) => {
3096 self.window.modifiers = mouse_exited.modifiers;
3097 PlatformInput::MouseExited(mouse_exited)
3098 }
3099 PlatformInput::ModifiersChanged(modifiers_changed) => {
3100 self.window.modifiers = modifiers_changed.modifiers;
3101 PlatformInput::ModifiersChanged(modifiers_changed)
3102 }
3103 PlatformInput::ScrollWheel(scroll_wheel) => {
3104 self.window.mouse_position = scroll_wheel.position;
3105 self.window.modifiers = scroll_wheel.modifiers;
3106 PlatformInput::ScrollWheel(scroll_wheel)
3107 }
3108 // Translate dragging and dropping of external files from the operating system
3109 // to internal drag and drop events.
3110 PlatformInput::FileDrop(file_drop) => match file_drop {
3111 FileDropEvent::Entered { position, paths } => {
3112 self.window.mouse_position = position;
3113 if self.active_drag.is_none() {
3114 self.active_drag = Some(AnyDrag {
3115 value: Box::new(paths.clone()),
3116 view: self.new_view(|_| paths).into(),
3117 cursor_offset: position,
3118 });
3119 }
3120 PlatformInput::MouseMove(MouseMoveEvent {
3121 position,
3122 pressed_button: Some(MouseButton::Left),
3123 modifiers: Modifiers::default(),
3124 })
3125 }
3126 FileDropEvent::Pending { position } => {
3127 self.window.mouse_position = position;
3128 PlatformInput::MouseMove(MouseMoveEvent {
3129 position,
3130 pressed_button: Some(MouseButton::Left),
3131 modifiers: Modifiers::default(),
3132 })
3133 }
3134 FileDropEvent::Submit { position } => {
3135 self.activate(true);
3136 self.window.mouse_position = position;
3137 PlatformInput::MouseUp(MouseUpEvent {
3138 button: MouseButton::Left,
3139 position,
3140 modifiers: Modifiers::default(),
3141 click_count: 1,
3142 })
3143 }
3144 FileDropEvent::Exited => {
3145 self.active_drag.take();
3146 PlatformInput::FileDrop(FileDropEvent::Exited)
3147 }
3148 },
3149 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
3150 };
3151
3152 if let Some(any_mouse_event) = event.mouse_event() {
3153 self.dispatch_mouse_event(any_mouse_event);
3154 } else if let Some(any_key_event) = event.keyboard_event() {
3155 self.dispatch_key_event(any_key_event);
3156 }
3157
3158 DispatchEventResult {
3159 propagate: self.app.propagate_event,
3160 default_prevented: self.window.default_prevented,
3161 }
3162 }
3163
3164 fn dispatch_mouse_event(&mut self, event: &dyn Any) {
3165 let hit_test = self.window.rendered_frame.hit_test(self.mouse_position());
3166 if hit_test != self.window.mouse_hit_test {
3167 self.window.mouse_hit_test = hit_test;
3168 self.reset_cursor_style();
3169 }
3170
3171 let mut mouse_listeners = mem::take(&mut self.window.rendered_frame.mouse_listeners);
3172
3173 // Capture phase, events bubble from back to front. Handlers for this phase are used for
3174 // special purposes, such as detecting events outside of a given Bounds.
3175 for listener in &mut mouse_listeners {
3176 let listener = listener.as_mut().unwrap();
3177 listener(event, DispatchPhase::Capture, self);
3178 if !self.app.propagate_event {
3179 break;
3180 }
3181 }
3182
3183 // Bubble phase, where most normal handlers do their work.
3184 if self.app.propagate_event {
3185 for listener in mouse_listeners.iter_mut().rev() {
3186 let listener = listener.as_mut().unwrap();
3187 listener(event, DispatchPhase::Bubble, self);
3188 if !self.app.propagate_event {
3189 break;
3190 }
3191 }
3192 }
3193
3194 self.window.rendered_frame.mouse_listeners = mouse_listeners;
3195
3196 if self.has_active_drag() {
3197 if event.is::<MouseMoveEvent>() {
3198 // If this was a mouse move event, redraw the window so that the
3199 // active drag can follow the mouse cursor.
3200 self.refresh();
3201 } else if event.is::<MouseUpEvent>() {
3202 // If this was a mouse up event, cancel the active drag and redraw
3203 // the window.
3204 self.active_drag = None;
3205 self.refresh();
3206 }
3207 }
3208 }
3209
3210 fn dispatch_key_event(&mut self, event: &dyn Any) {
3211 if self.window.dirty.get() {
3212 self.draw();
3213 }
3214
3215 let node_id = self
3216 .window
3217 .focus
3218 .and_then(|focus_id| {
3219 self.window
3220 .rendered_frame
3221 .dispatch_tree
3222 .focusable_node_id(focus_id)
3223 })
3224 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3225
3226 let dispatch_path = self
3227 .window
3228 .rendered_frame
3229 .dispatch_tree
3230 .dispatch_path(node_id);
3231
3232 let mut keystroke: Option<Keystroke> = None;
3233
3234 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
3235 if event.modifiers.number_of_modifiers() == 0
3236 && self.window.pending_modifier.modifiers.number_of_modifiers() == 1
3237 && !self.window.pending_modifier.saw_keystroke
3238 {
3239 if event.modifiers.number_of_modifiers() == 0 {
3240 let key = match self.window.pending_modifier.modifiers {
3241 modifiers if modifiers.shift => Some("shift"),
3242 modifiers if modifiers.control => Some("control"),
3243 modifiers if modifiers.alt => Some("alt"),
3244 modifiers if modifiers.platform => Some("platform"),
3245 modifiers if modifiers.function => Some("function"),
3246 _ => None,
3247 };
3248 if let Some(key) = key {
3249 keystroke = Some(Keystroke {
3250 key: key.to_string(),
3251 ime_key: None,
3252 modifiers: Modifiers::default(),
3253 });
3254 }
3255 }
3256 }
3257 if self.window.pending_modifier.modifiers.number_of_modifiers() == 0
3258 && event.modifiers.number_of_modifiers() == 1
3259 {
3260 self.window.pending_modifier.saw_keystroke = false
3261 }
3262 self.window.pending_modifier.modifiers = event.modifiers
3263 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3264 self.window.pending_modifier.saw_keystroke = true;
3265 keystroke = Some(key_down_event.keystroke.clone());
3266 }
3267
3268 let Some(keystroke) = keystroke else {
3269 self.finish_dispatch_key_event(event, dispatch_path);
3270 return;
3271 };
3272
3273 let mut currently_pending = self.window.pending_input.take().unwrap_or_default();
3274 if currently_pending.focus.is_some() && currently_pending.focus != self.window.focus {
3275 currently_pending = PendingInput::default();
3276 }
3277
3278 let match_result = self.window.rendered_frame.dispatch_tree.dispatch_key(
3279 currently_pending.keystrokes,
3280 keystroke,
3281 &dispatch_path,
3282 );
3283 if !match_result.to_replay.is_empty() {
3284 self.replay_pending_input(match_result.to_replay)
3285 }
3286
3287 if !match_result.pending.is_empty() {
3288 currently_pending.keystrokes = match_result.pending;
3289 currently_pending.focus = self.window.focus;
3290 currently_pending.timer = Some(self.spawn(|mut cx| async move {
3291 cx.background_executor.timer(Duration::from_secs(1)).await;
3292 cx.update(move |cx| {
3293 let Some(currently_pending) = cx
3294 .window
3295 .pending_input
3296 .take()
3297 .filter(|pending| pending.focus == cx.window.focus)
3298 else {
3299 return;
3300 };
3301
3302 let dispatch_path = cx
3303 .window
3304 .rendered_frame
3305 .dispatch_tree
3306 .dispatch_path(node_id);
3307
3308 let to_replay = cx
3309 .window
3310 .rendered_frame
3311 .dispatch_tree
3312 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
3313
3314 cx.replay_pending_input(to_replay)
3315 })
3316 .log_err();
3317 }));
3318 self.window.pending_input = Some(currently_pending);
3319 self.pending_input_changed();
3320 self.propagate_event = false;
3321 return;
3322 }
3323
3324 self.pending_input_changed();
3325 self.propagate_event = true;
3326 for binding in match_result.bindings {
3327 self.dispatch_action_on_node(node_id, binding.action.as_ref());
3328 if !self.propagate_event {
3329 self.dispatch_keystroke_observers(event, Some(binding.action));
3330 return;
3331 }
3332 }
3333
3334 self.finish_dispatch_key_event(event, dispatch_path)
3335 }
3336
3337 fn finish_dispatch_key_event(
3338 &mut self,
3339 event: &dyn Any,
3340 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
3341 ) {
3342 self.dispatch_key_down_up_event(event, &dispatch_path);
3343 if !self.propagate_event {
3344 return;
3345 }
3346
3347 self.dispatch_modifiers_changed_event(event, &dispatch_path);
3348 if !self.propagate_event {
3349 return;
3350 }
3351
3352 self.dispatch_keystroke_observers(event, None);
3353 }
3354
3355 fn pending_input_changed(&mut self) {
3356 self.window
3357 .pending_input_observers
3358 .clone()
3359 .retain(&(), |callback| callback(self));
3360 }
3361
3362 fn dispatch_key_down_up_event(
3363 &mut self,
3364 event: &dyn Any,
3365 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3366 ) {
3367 // Capture phase
3368 for node_id in dispatch_path {
3369 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3370
3371 for key_listener in node.key_listeners.clone() {
3372 key_listener(event, DispatchPhase::Capture, self);
3373 if !self.propagate_event {
3374 return;
3375 }
3376 }
3377 }
3378
3379 // Bubble phase
3380 for node_id in dispatch_path.iter().rev() {
3381 // Handle low level key events
3382 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3383 for key_listener in node.key_listeners.clone() {
3384 key_listener(event, DispatchPhase::Bubble, self);
3385 if !self.propagate_event {
3386 return;
3387 }
3388 }
3389 }
3390 }
3391
3392 fn dispatch_modifiers_changed_event(
3393 &mut self,
3394 event: &dyn Any,
3395 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3396 ) {
3397 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
3398 return;
3399 };
3400 for node_id in dispatch_path.iter().rev() {
3401 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3402 for listener in node.modifiers_changed_listeners.clone() {
3403 listener(event, self);
3404 if !self.propagate_event {
3405 return;
3406 }
3407 }
3408 }
3409 }
3410
3411 /// Determine whether a potential multi-stroke key binding is in progress on this window.
3412 pub fn has_pending_keystrokes(&self) -> bool {
3413 self.window.pending_input.is_some()
3414 }
3415
3416 fn clear_pending_keystrokes(&mut self) {
3417 self.window.pending_input.take();
3418 }
3419
3420 /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
3421 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
3422 self.window
3423 .pending_input
3424 .as_ref()
3425 .map(|pending_input| pending_input.keystrokes.as_slice())
3426 }
3427
3428 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>) {
3429 let node_id = self
3430 .window
3431 .focus
3432 .and_then(|focus_id| {
3433 self.window
3434 .rendered_frame
3435 .dispatch_tree
3436 .focusable_node_id(focus_id)
3437 })
3438 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3439
3440 let dispatch_path = self
3441 .window
3442 .rendered_frame
3443 .dispatch_tree
3444 .dispatch_path(node_id);
3445
3446 'replay: for replay in replays {
3447 let event = KeyDownEvent {
3448 keystroke: replay.keystroke.clone(),
3449 is_held: false,
3450 };
3451
3452 self.propagate_event = true;
3453 for binding in replay.bindings {
3454 self.dispatch_action_on_node(node_id, binding.action.as_ref());
3455 if !self.propagate_event {
3456 self.dispatch_keystroke_observers(&event, Some(binding.action));
3457 continue 'replay;
3458 }
3459 }
3460
3461 self.dispatch_key_down_up_event(&event, &dispatch_path);
3462 if !self.propagate_event {
3463 continue 'replay;
3464 }
3465 if let Some(input) = replay.keystroke.ime_key.as_ref().cloned() {
3466 if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
3467 input_handler.dispatch_input(&input, self);
3468 self.window.platform_window.set_input_handler(input_handler)
3469 }
3470 }
3471 }
3472 }
3473
3474 fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: &dyn Action) {
3475 let dispatch_path = self
3476 .window
3477 .rendered_frame
3478 .dispatch_tree
3479 .dispatch_path(node_id);
3480
3481 // Capture phase for global actions.
3482 self.propagate_event = true;
3483 if let Some(mut global_listeners) = self
3484 .global_action_listeners
3485 .remove(&action.as_any().type_id())
3486 {
3487 for listener in &global_listeners {
3488 listener(action.as_any(), DispatchPhase::Capture, self);
3489 if !self.propagate_event {
3490 break;
3491 }
3492 }
3493
3494 global_listeners.extend(
3495 self.global_action_listeners
3496 .remove(&action.as_any().type_id())
3497 .unwrap_or_default(),
3498 );
3499
3500 self.global_action_listeners
3501 .insert(action.as_any().type_id(), global_listeners);
3502 }
3503
3504 if !self.propagate_event {
3505 return;
3506 }
3507
3508 // Capture phase for window actions.
3509 for node_id in &dispatch_path {
3510 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3511 for DispatchActionListener {
3512 action_type,
3513 listener,
3514 } in node.action_listeners.clone()
3515 {
3516 let any_action = action.as_any();
3517 if action_type == any_action.type_id() {
3518 listener(any_action, DispatchPhase::Capture, self);
3519
3520 if !self.propagate_event {
3521 return;
3522 }
3523 }
3524 }
3525 }
3526
3527 // Bubble phase for window actions.
3528 for node_id in dispatch_path.iter().rev() {
3529 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3530 for DispatchActionListener {
3531 action_type,
3532 listener,
3533 } in node.action_listeners.clone()
3534 {
3535 let any_action = action.as_any();
3536 if action_type == any_action.type_id() {
3537 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3538 listener(any_action, DispatchPhase::Bubble, self);
3539
3540 if !self.propagate_event {
3541 return;
3542 }
3543 }
3544 }
3545 }
3546
3547 // Bubble phase for global actions.
3548 if let Some(mut global_listeners) = self
3549 .global_action_listeners
3550 .remove(&action.as_any().type_id())
3551 {
3552 for listener in global_listeners.iter().rev() {
3553 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3554
3555 listener(action.as_any(), DispatchPhase::Bubble, self);
3556 if !self.propagate_event {
3557 break;
3558 }
3559 }
3560
3561 global_listeners.extend(
3562 self.global_action_listeners
3563 .remove(&action.as_any().type_id())
3564 .unwrap_or_default(),
3565 );
3566
3567 self.global_action_listeners
3568 .insert(action.as_any().type_id(), global_listeners);
3569 }
3570 }
3571
3572 /// Register the given handler to be invoked whenever the global of the given type
3573 /// is updated.
3574 pub fn observe_global<G: Global>(
3575 &mut self,
3576 f: impl Fn(&mut WindowContext<'_>) + 'static,
3577 ) -> Subscription {
3578 let window_handle = self.window.handle;
3579 let (subscription, activate) = self.global_observers.insert(
3580 TypeId::of::<G>(),
3581 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
3582 );
3583 self.app.defer(move |_| activate());
3584 subscription
3585 }
3586
3587 /// Focus the current window and bring it to the foreground at the platform level.
3588 pub fn activate_window(&self) {
3589 self.window.platform_window.activate();
3590 }
3591
3592 /// Minimize the current window at the platform level.
3593 pub fn minimize_window(&self) {
3594 self.window.platform_window.minimize();
3595 }
3596
3597 /// Toggle full screen status on the current window at the platform level.
3598 pub fn toggle_fullscreen(&self) {
3599 self.window.platform_window.toggle_fullscreen();
3600 }
3601
3602 /// Present a platform dialog.
3603 /// The provided message will be presented, along with buttons for each answer.
3604 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
3605 pub fn prompt(
3606 &mut self,
3607 level: PromptLevel,
3608 message: &str,
3609 detail: Option<&str>,
3610 answers: &[&str],
3611 ) -> oneshot::Receiver<usize> {
3612 let prompt_builder = self.app.prompt_builder.take();
3613 let Some(prompt_builder) = prompt_builder else {
3614 unreachable!("Re-entrant window prompting is not supported by GPUI");
3615 };
3616
3617 let receiver = match &prompt_builder {
3618 PromptBuilder::Default => self
3619 .window
3620 .platform_window
3621 .prompt(level, message, detail, answers)
3622 .unwrap_or_else(|| {
3623 self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3624 }),
3625 PromptBuilder::Custom(_) => {
3626 self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3627 }
3628 };
3629
3630 self.app.prompt_builder = Some(prompt_builder);
3631
3632 receiver
3633 }
3634
3635 fn build_custom_prompt(
3636 &mut self,
3637 prompt_builder: &PromptBuilder,
3638 level: PromptLevel,
3639 message: &str,
3640 detail: Option<&str>,
3641 answers: &[&str],
3642 ) -> oneshot::Receiver<usize> {
3643 let (sender, receiver) = oneshot::channel();
3644 let handle = PromptHandle::new(sender);
3645 let handle = (prompt_builder)(level, message, detail, answers, handle, self);
3646 self.window.prompt = Some(handle);
3647 receiver
3648 }
3649
3650 /// Returns all available actions for the focused element.
3651 pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
3652 let node_id = self
3653 .window
3654 .focus
3655 .and_then(|focus_id| {
3656 self.window
3657 .rendered_frame
3658 .dispatch_tree
3659 .focusable_node_id(focus_id)
3660 })
3661 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3662
3663 let mut actions = self
3664 .window
3665 .rendered_frame
3666 .dispatch_tree
3667 .available_actions(node_id);
3668 for action_type in self.global_action_listeners.keys() {
3669 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
3670 let action = self.actions.build_action_type(action_type).ok();
3671 if let Some(action) = action {
3672 actions.insert(ix, action);
3673 }
3674 }
3675 }
3676 actions
3677 }
3678
3679 /// Returns key bindings that invoke the given action on the currently focused element.
3680 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
3681 self.window
3682 .rendered_frame
3683 .dispatch_tree
3684 .bindings_for_action(
3685 action,
3686 &self.window.rendered_frame.dispatch_tree.context_stack,
3687 )
3688 }
3689
3690 /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
3691 pub fn bindings_for_action_in(
3692 &self,
3693 action: &dyn Action,
3694 focus_handle: &FocusHandle,
3695 ) -> Vec<KeyBinding> {
3696 let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
3697
3698 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
3699 return vec![];
3700 };
3701 let context_stack: Vec<_> = dispatch_tree
3702 .dispatch_path(node_id)
3703 .into_iter()
3704 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
3705 .collect();
3706 dispatch_tree.bindings_for_action(action, &context_stack)
3707 }
3708
3709 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
3710 pub fn listener_for<V: Render, E>(
3711 &self,
3712 view: &View<V>,
3713 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
3714 ) -> impl Fn(&E, &mut WindowContext) + 'static {
3715 let view = view.downgrade();
3716 move |e: &E, cx: &mut WindowContext| {
3717 view.update(cx, |view, cx| f(view, e, cx)).ok();
3718 }
3719 }
3720
3721 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
3722 pub fn handler_for<V: Render>(
3723 &self,
3724 view: &View<V>,
3725 f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
3726 ) -> impl Fn(&mut WindowContext) {
3727 let view = view.downgrade();
3728 move |cx: &mut WindowContext| {
3729 view.update(cx, |view, cx| f(view, cx)).ok();
3730 }
3731 }
3732
3733 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
3734 /// If the callback returns false, the window won't be closed.
3735 pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
3736 let mut this = self.to_async();
3737 self.window
3738 .platform_window
3739 .on_should_close(Box::new(move || this.update(|cx| f(cx)).unwrap_or(true)))
3740 }
3741
3742 /// Register an action listener on the window for the next frame. The type of action
3743 /// is determined by the first parameter of the given listener. When the next frame is rendered
3744 /// the listener will be cleared.
3745 ///
3746 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
3747 /// a specific need to register a global listener.
3748 pub fn on_action(
3749 &mut self,
3750 action_type: TypeId,
3751 listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
3752 ) {
3753 self.window
3754 .next_frame
3755 .dispatch_tree
3756 .on_action(action_type, Rc::new(listener));
3757 }
3758
3759 /// Read information about the GPU backing this window.
3760 /// Currently returns None on Mac and Windows.
3761 pub fn gpu_specs(&self) -> Option<GPUSpecs> {
3762 self.window.platform_window.gpu_specs()
3763 }
3764}
3765
3766#[cfg(target_os = "windows")]
3767impl WindowContext<'_> {
3768 /// Returns the raw HWND handle for the window.
3769 pub fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND {
3770 self.window.platform_window.get_raw_handle()
3771 }
3772}
3773
3774impl Context for WindowContext<'_> {
3775 type Result<T> = T;
3776
3777 fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
3778 where
3779 T: 'static,
3780 {
3781 let slot = self.app.entities.reserve();
3782 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
3783 self.entities.insert(slot, model)
3784 }
3785
3786 fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
3787 self.app.reserve_model()
3788 }
3789
3790 fn insert_model<T: 'static>(
3791 &mut self,
3792 reservation: crate::Reservation<T>,
3793 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
3794 ) -> Self::Result<Model<T>> {
3795 self.app.insert_model(reservation, build_model)
3796 }
3797
3798 fn update_model<T: 'static, R>(
3799 &mut self,
3800 model: &Model<T>,
3801 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
3802 ) -> R {
3803 let mut entity = self.entities.lease(model);
3804 let result = update(
3805 &mut *entity,
3806 &mut ModelContext::new(&mut *self.app, model.downgrade()),
3807 );
3808 self.entities.end_lease(entity);
3809 result
3810 }
3811
3812 fn read_model<T, R>(
3813 &self,
3814 handle: &Model<T>,
3815 read: impl FnOnce(&T, &AppContext) -> R,
3816 ) -> Self::Result<R>
3817 where
3818 T: 'static,
3819 {
3820 let entity = self.entities.read(handle);
3821 read(entity, &*self.app)
3822 }
3823
3824 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
3825 where
3826 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
3827 {
3828 if window == self.window.handle {
3829 let root_view = self.window.root_view.clone().unwrap();
3830 Ok(update(root_view, self))
3831 } else {
3832 window.update(self.app, update)
3833 }
3834 }
3835
3836 fn read_window<T, R>(
3837 &self,
3838 window: &WindowHandle<T>,
3839 read: impl FnOnce(View<T>, &AppContext) -> R,
3840 ) -> Result<R>
3841 where
3842 T: 'static,
3843 {
3844 if window.any_handle == self.window.handle {
3845 let root_view = self
3846 .window
3847 .root_view
3848 .clone()
3849 .unwrap()
3850 .downcast::<T>()
3851 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3852 Ok(read(root_view, self))
3853 } else {
3854 self.app.read_window(window, read)
3855 }
3856 }
3857}
3858
3859impl VisualContext for WindowContext<'_> {
3860 fn new_view<V>(
3861 &mut self,
3862 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3863 ) -> Self::Result<View<V>>
3864 where
3865 V: 'static + Render,
3866 {
3867 let slot = self.app.entities.reserve();
3868 let view = View {
3869 model: slot.clone(),
3870 };
3871 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
3872 let entity = build_view_state(&mut cx);
3873 cx.entities.insert(slot, entity);
3874
3875 // Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
3876 fn notify_observers(cx: &mut WindowContext, tid: TypeId, view: AnyView) {
3877 cx.new_view_observers.clone().retain(&tid, |observer| {
3878 let any_view = view.clone();
3879 (observer)(any_view, cx);
3880 true
3881 });
3882 }
3883 notify_observers(self, TypeId::of::<V>(), AnyView::from(view.clone()));
3884
3885 view
3886 }
3887
3888 /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
3889 fn update_view<T: 'static, R>(
3890 &mut self,
3891 view: &View<T>,
3892 update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
3893 ) -> Self::Result<R> {
3894 let mut lease = self.app.entities.lease(&view.model);
3895 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
3896 let result = update(&mut *lease, &mut cx);
3897 cx.app.entities.end_lease(lease);
3898 result
3899 }
3900
3901 fn replace_root_view<V>(
3902 &mut self,
3903 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3904 ) -> Self::Result<View<V>>
3905 where
3906 V: 'static + Render,
3907 {
3908 let view = self.new_view(build_view);
3909 self.window.root_view = Some(view.clone().into());
3910 self.refresh();
3911 view
3912 }
3913
3914 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
3915 self.update_view(view, |view, cx| {
3916 view.focus_handle(cx).clone().focus(cx);
3917 })
3918 }
3919
3920 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
3921 where
3922 V: ManagedView,
3923 {
3924 self.update_view(view, |_, cx| cx.emit(DismissEvent))
3925 }
3926}
3927
3928impl<'a> std::ops::Deref for WindowContext<'a> {
3929 type Target = AppContext;
3930
3931 fn deref(&self) -> &Self::Target {
3932 self.app
3933 }
3934}
3935
3936impl<'a> std::ops::DerefMut for WindowContext<'a> {
3937 fn deref_mut(&mut self) -> &mut Self::Target {
3938 self.app
3939 }
3940}
3941
3942impl<'a> Borrow<AppContext> for WindowContext<'a> {
3943 fn borrow(&self) -> &AppContext {
3944 self.app
3945 }
3946}
3947
3948impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
3949 fn borrow_mut(&mut self) -> &mut AppContext {
3950 self.app
3951 }
3952}
3953
3954/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
3955pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
3956 #[doc(hidden)]
3957 fn app_mut(&mut self) -> &mut AppContext {
3958 self.borrow_mut()
3959 }
3960
3961 #[doc(hidden)]
3962 fn app(&self) -> &AppContext {
3963 self.borrow()
3964 }
3965
3966 #[doc(hidden)]
3967 fn window(&self) -> &Window {
3968 self.borrow()
3969 }
3970
3971 #[doc(hidden)]
3972 fn window_mut(&mut self) -> &mut Window {
3973 self.borrow_mut()
3974 }
3975}
3976
3977impl Borrow<Window> for WindowContext<'_> {
3978 fn borrow(&self) -> &Window {
3979 self.window
3980 }
3981}
3982
3983impl BorrowMut<Window> for WindowContext<'_> {
3984 fn borrow_mut(&mut self) -> &mut Window {
3985 self.window
3986 }
3987}
3988
3989impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
3990
3991/// Provides access to application state that is specialized for a particular [`View`].
3992/// Allows you to interact with focus, emit events, etc.
3993/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
3994/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
3995pub struct ViewContext<'a, V> {
3996 window_cx: WindowContext<'a>,
3997 view: &'a View<V>,
3998}
3999
4000impl<V> Borrow<AppContext> for ViewContext<'_, V> {
4001 fn borrow(&self) -> &AppContext {
4002 &*self.window_cx.app
4003 }
4004}
4005
4006impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
4007 fn borrow_mut(&mut self) -> &mut AppContext {
4008 &mut *self.window_cx.app
4009 }
4010}
4011
4012impl<V> Borrow<Window> for ViewContext<'_, V> {
4013 fn borrow(&self) -> &Window {
4014 &*self.window_cx.window
4015 }
4016}
4017
4018impl<V> BorrowMut<Window> for ViewContext<'_, V> {
4019 fn borrow_mut(&mut self) -> &mut Window {
4020 &mut *self.window_cx.window
4021 }
4022}
4023
4024impl<'a, V: 'static> ViewContext<'a, V> {
4025 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
4026 Self {
4027 window_cx: WindowContext::new(app, window),
4028 view,
4029 }
4030 }
4031
4032 /// Get the entity_id of this view.
4033 pub fn entity_id(&self) -> EntityId {
4034 self.view.entity_id()
4035 }
4036
4037 /// Get the view pointer underlying this context.
4038 pub fn view(&self) -> &View<V> {
4039 self.view
4040 }
4041
4042 /// Get the model underlying this view.
4043 pub fn model(&self) -> &Model<V> {
4044 &self.view.model
4045 }
4046
4047 /// Access the underlying window context.
4048 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
4049 &mut self.window_cx
4050 }
4051
4052 /// Sets a given callback to be run on the next frame.
4053 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
4054 where
4055 V: 'static,
4056 {
4057 let view = self.view().clone();
4058 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
4059 }
4060
4061 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
4062 /// that are currently on the stack to be returned to the app.
4063 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
4064 let view = self.view().downgrade();
4065 self.window_cx.defer(move |cx| {
4066 view.update(cx, f).ok();
4067 });
4068 }
4069
4070 /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
4071 pub fn observe<V2, E>(
4072 &mut self,
4073 entity: &E,
4074 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
4075 ) -> Subscription
4076 where
4077 V2: 'static,
4078 V: 'static,
4079 E: Entity<V2>,
4080 {
4081 let view = self.view().downgrade();
4082 let entity_id = entity.entity_id();
4083 let entity = entity.downgrade();
4084 let window_handle = self.window.handle;
4085 self.app.new_observer(
4086 entity_id,
4087 Box::new(move |cx| {
4088 window_handle
4089 .update(cx, |_, cx| {
4090 if let Some(handle) = E::upgrade_from(&entity) {
4091 view.update(cx, |this, cx| on_notify(this, handle, cx))
4092 .is_ok()
4093 } else {
4094 false
4095 }
4096 })
4097 .unwrap_or(false)
4098 }),
4099 )
4100 }
4101
4102 /// Subscribe to events emitted by another model or view.
4103 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
4104 /// 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.
4105 pub fn subscribe<V2, E, Evt>(
4106 &mut self,
4107 entity: &E,
4108 mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
4109 ) -> Subscription
4110 where
4111 V2: EventEmitter<Evt>,
4112 E: Entity<V2>,
4113 Evt: 'static,
4114 {
4115 let view = self.view().downgrade();
4116 let entity_id = entity.entity_id();
4117 let handle = entity.downgrade();
4118 let window_handle = self.window.handle;
4119 self.app.new_subscription(
4120 entity_id,
4121 (
4122 TypeId::of::<Evt>(),
4123 Box::new(move |event, cx| {
4124 window_handle
4125 .update(cx, |_, cx| {
4126 if let Some(handle) = E::upgrade_from(&handle) {
4127 let event = event.downcast_ref().expect("invalid event type");
4128 view.update(cx, |this, cx| on_event(this, handle, event, cx))
4129 .is_ok()
4130 } else {
4131 false
4132 }
4133 })
4134 .unwrap_or(false)
4135 }),
4136 ),
4137 )
4138 }
4139
4140 /// Register a callback to be invoked when the view is released.
4141 ///
4142 /// The callback receives a handle to the view's window. This handle may be
4143 /// invalid, if the window was closed before the view was released.
4144 pub fn on_release(
4145 &mut self,
4146 on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
4147 ) -> Subscription {
4148 let window_handle = self.window.handle;
4149 let (subscription, activate) = self.app.release_listeners.insert(
4150 self.view.model.entity_id,
4151 Box::new(move |this, cx| {
4152 let this = this.downcast_mut().expect("invalid entity type");
4153 on_release(this, window_handle, cx)
4154 }),
4155 );
4156 activate();
4157 subscription
4158 }
4159
4160 /// Register a callback to be invoked when the given Model or View is released.
4161 pub fn observe_release<V2, E>(
4162 &mut self,
4163 entity: &E,
4164 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
4165 ) -> Subscription
4166 where
4167 V: 'static,
4168 V2: 'static,
4169 E: Entity<V2>,
4170 {
4171 let view = self.view().downgrade();
4172 let entity_id = entity.entity_id();
4173 let window_handle = self.window.handle;
4174 let (subscription, activate) = self.app.release_listeners.insert(
4175 entity_id,
4176 Box::new(move |entity, cx| {
4177 let entity = entity.downcast_mut().expect("invalid entity type");
4178 let _ = window_handle.update(cx, |_, cx| {
4179 view.update(cx, |this, cx| on_release(this, entity, cx))
4180 });
4181 }),
4182 );
4183 activate();
4184 subscription
4185 }
4186
4187 /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
4188 /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
4189 pub fn notify(&mut self) {
4190 self.window_cx.notify(self.view.entity_id());
4191 }
4192
4193 /// Register a callback to be invoked when the window is resized.
4194 pub fn observe_window_bounds(
4195 &mut self,
4196 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4197 ) -> Subscription {
4198 let view = self.view.downgrade();
4199 let (subscription, activate) = self.window.bounds_observers.insert(
4200 (),
4201 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4202 );
4203 activate();
4204 subscription
4205 }
4206
4207 /// Register a callback to be invoked when the window is activated or deactivated.
4208 pub fn observe_window_activation(
4209 &mut self,
4210 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4211 ) -> Subscription {
4212 let view = self.view.downgrade();
4213 let (subscription, activate) = self.window.activation_observers.insert(
4214 (),
4215 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4216 );
4217 activate();
4218 subscription
4219 }
4220
4221 /// Registers a callback to be invoked when the window appearance changes.
4222 pub fn observe_window_appearance(
4223 &mut self,
4224 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4225 ) -> Subscription {
4226 let view = self.view.downgrade();
4227 let (subscription, activate) = self.window.appearance_observers.insert(
4228 (),
4229 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4230 );
4231 activate();
4232 subscription
4233 }
4234
4235 /// Register a callback to be invoked when the window's pending input changes.
4236 pub fn observe_pending_input(
4237 &mut self,
4238 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4239 ) -> Subscription {
4240 let view = self.view.downgrade();
4241 let (subscription, activate) = self.window.pending_input_observers.insert(
4242 (),
4243 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4244 );
4245 activate();
4246 subscription
4247 }
4248
4249 /// Register a listener to be called when the given focus handle receives focus.
4250 /// Returns a subscription and persists until the subscription is dropped.
4251 pub fn on_focus(
4252 &mut self,
4253 handle: &FocusHandle,
4254 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4255 ) -> Subscription {
4256 let view = self.view.downgrade();
4257 let focus_id = handle.id;
4258 let (subscription, activate) =
4259 self.window.new_focus_listener(Box::new(move |event, cx| {
4260 view.update(cx, |view, cx| {
4261 if event.previous_focus_path.last() != Some(&focus_id)
4262 && event.current_focus_path.last() == Some(&focus_id)
4263 {
4264 listener(view, cx)
4265 }
4266 })
4267 .is_ok()
4268 }));
4269 self.app.defer(|_| activate());
4270 subscription
4271 }
4272
4273 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
4274 /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
4275 /// Returns a subscription and persists until the subscription is dropped.
4276 pub fn on_focus_in(
4277 &mut self,
4278 handle: &FocusHandle,
4279 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4280 ) -> Subscription {
4281 let view = self.view.downgrade();
4282 let focus_id = handle.id;
4283 let (subscription, activate) =
4284 self.window.new_focus_listener(Box::new(move |event, cx| {
4285 view.update(cx, |view, cx| {
4286 if event.is_focus_in(focus_id) {
4287 listener(view, cx)
4288 }
4289 })
4290 .is_ok()
4291 }));
4292 self.app.defer(move |_| activate());
4293 subscription
4294 }
4295
4296 /// Register a listener to be called when the given focus handle loses focus.
4297 /// Returns a subscription and persists until the subscription is dropped.
4298 pub fn on_blur(
4299 &mut self,
4300 handle: &FocusHandle,
4301 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4302 ) -> Subscription {
4303 let view = self.view.downgrade();
4304 let focus_id = handle.id;
4305 let (subscription, activate) =
4306 self.window.new_focus_listener(Box::new(move |event, cx| {
4307 view.update(cx, |view, cx| {
4308 if event.previous_focus_path.last() == Some(&focus_id)
4309 && event.current_focus_path.last() != Some(&focus_id)
4310 {
4311 listener(view, cx)
4312 }
4313 })
4314 .is_ok()
4315 }));
4316 self.app.defer(move |_| activate());
4317 subscription
4318 }
4319
4320 /// Register a listener to be called when nothing in the window has focus.
4321 /// This typically happens when the node that was focused is removed from the tree,
4322 /// and this callback lets you chose a default place to restore the users focus.
4323 /// Returns a subscription and persists until the subscription is dropped.
4324 pub fn on_focus_lost(
4325 &mut self,
4326 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4327 ) -> Subscription {
4328 let view = self.view.downgrade();
4329 let (subscription, activate) = self.window.focus_lost_listeners.insert(
4330 (),
4331 Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
4332 );
4333 activate();
4334 subscription
4335 }
4336
4337 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
4338 /// Returns a subscription and persists until the subscription is dropped.
4339 pub fn on_focus_out(
4340 &mut self,
4341 handle: &FocusHandle,
4342 mut listener: impl FnMut(&mut V, FocusOutEvent, &mut ViewContext<V>) + 'static,
4343 ) -> Subscription {
4344 let view = self.view.downgrade();
4345 let focus_id = handle.id;
4346 let (subscription, activate) =
4347 self.window.new_focus_listener(Box::new(move |event, cx| {
4348 view.update(cx, |view, cx| {
4349 if let Some(blurred_id) = event.previous_focus_path.last().copied() {
4350 if event.is_focus_out(focus_id) {
4351 let event = FocusOutEvent {
4352 blurred: WeakFocusHandle {
4353 id: blurred_id,
4354 handles: Arc::downgrade(&cx.window.focus_handles),
4355 },
4356 };
4357 listener(view, event, cx)
4358 }
4359 }
4360 })
4361 .is_ok()
4362 }));
4363 self.app.defer(move |_| activate());
4364 subscription
4365 }
4366
4367 /// Schedule a future to be run asynchronously.
4368 /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
4369 /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
4370 /// The returned future will be polled on the main thread.
4371 pub fn spawn<Fut, R>(
4372 &mut self,
4373 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
4374 ) -> Task<R>
4375 where
4376 R: 'static,
4377 Fut: Future<Output = R> + 'static,
4378 {
4379 let view = self.view().downgrade();
4380 self.window_cx.spawn(|cx| f(view, cx))
4381 }
4382
4383 /// Register a callback to be invoked when the given global state changes.
4384 pub fn observe_global<G: Global>(
4385 &mut self,
4386 mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
4387 ) -> Subscription {
4388 let window_handle = self.window.handle;
4389 let view = self.view().downgrade();
4390 let (subscription, activate) = self.global_observers.insert(
4391 TypeId::of::<G>(),
4392 Box::new(move |cx| {
4393 window_handle
4394 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
4395 .unwrap_or(false)
4396 }),
4397 );
4398 self.app.defer(move |_| activate());
4399 subscription
4400 }
4401
4402 /// Register a callback to be invoked when the given Action type is dispatched to the window.
4403 pub fn on_action(
4404 &mut self,
4405 action_type: TypeId,
4406 listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
4407 ) {
4408 let handle = self.view().clone();
4409 self.window_cx
4410 .on_action(action_type, move |action, phase, cx| {
4411 handle.update(cx, |view, cx| {
4412 listener(view, action, phase, cx);
4413 })
4414 });
4415 }
4416
4417 /// Emit an event to be handled by any other views that have subscribed via [ViewContext::subscribe].
4418 pub fn emit<Evt>(&mut self, event: Evt)
4419 where
4420 Evt: 'static,
4421 V: EventEmitter<Evt>,
4422 {
4423 let emitter = self.view.model.entity_id;
4424 self.app.push_effect(Effect::Emit {
4425 emitter,
4426 event_type: TypeId::of::<Evt>(),
4427 event: Box::new(event),
4428 });
4429 }
4430
4431 /// Move focus to the current view, assuming it implements [`FocusableView`].
4432 pub fn focus_self(&mut self)
4433 where
4434 V: FocusableView,
4435 {
4436 self.defer(|view, cx| view.focus_handle(cx).focus(cx))
4437 }
4438
4439 /// Convenience method for accessing view state in an event callback.
4440 ///
4441 /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
4442 /// but it's often useful to be able to access view state in these
4443 /// callbacks. This method provides a convenient way to do so.
4444 pub fn listener<E: ?Sized>(
4445 &self,
4446 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
4447 ) -> impl Fn(&E, &mut WindowContext) + 'static {
4448 let view = self.view().downgrade();
4449 move |e: &E, cx: &mut WindowContext| {
4450 view.update(cx, |view, cx| f(view, e, cx)).ok();
4451 }
4452 }
4453}
4454
4455impl<V> Context for ViewContext<'_, V> {
4456 type Result<U> = U;
4457
4458 fn new_model<T: 'static>(
4459 &mut self,
4460 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4461 ) -> Model<T> {
4462 self.window_cx.new_model(build_model)
4463 }
4464
4465 fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
4466 self.window_cx.reserve_model()
4467 }
4468
4469 fn insert_model<T: 'static>(
4470 &mut self,
4471 reservation: crate::Reservation<T>,
4472 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4473 ) -> Self::Result<Model<T>> {
4474 self.window_cx.insert_model(reservation, build_model)
4475 }
4476
4477 fn update_model<T: 'static, R>(
4478 &mut self,
4479 model: &Model<T>,
4480 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
4481 ) -> R {
4482 self.window_cx.update_model(model, update)
4483 }
4484
4485 fn read_model<T, R>(
4486 &self,
4487 handle: &Model<T>,
4488 read: impl FnOnce(&T, &AppContext) -> R,
4489 ) -> Self::Result<R>
4490 where
4491 T: 'static,
4492 {
4493 self.window_cx.read_model(handle, read)
4494 }
4495
4496 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
4497 where
4498 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
4499 {
4500 self.window_cx.update_window(window, update)
4501 }
4502
4503 fn read_window<T, R>(
4504 &self,
4505 window: &WindowHandle<T>,
4506 read: impl FnOnce(View<T>, &AppContext) -> R,
4507 ) -> Result<R>
4508 where
4509 T: 'static,
4510 {
4511 self.window_cx.read_window(window, read)
4512 }
4513}
4514
4515impl<V: 'static> VisualContext for ViewContext<'_, V> {
4516 fn new_view<W: Render + 'static>(
4517 &mut self,
4518 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4519 ) -> Self::Result<View<W>> {
4520 self.window_cx.new_view(build_view_state)
4521 }
4522
4523 fn update_view<V2: 'static, R>(
4524 &mut self,
4525 view: &View<V2>,
4526 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
4527 ) -> Self::Result<R> {
4528 self.window_cx.update_view(view, update)
4529 }
4530
4531 fn replace_root_view<W>(
4532 &mut self,
4533 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4534 ) -> Self::Result<View<W>>
4535 where
4536 W: 'static + Render,
4537 {
4538 self.window_cx.replace_root_view(build_view)
4539 }
4540
4541 fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
4542 self.window_cx.focus_view(view)
4543 }
4544
4545 fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
4546 self.window_cx.dismiss_view(view)
4547 }
4548}
4549
4550impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
4551 type Target = WindowContext<'a>;
4552
4553 fn deref(&self) -> &Self::Target {
4554 &self.window_cx
4555 }
4556}
4557
4558impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
4559 fn deref_mut(&mut self) -> &mut Self::Target {
4560 &mut self.window_cx
4561 }
4562}
4563
4564// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
4565slotmap::new_key_type! {
4566 /// A unique identifier for a window.
4567 pub struct WindowId;
4568}
4569
4570impl WindowId {
4571 /// Converts this window ID to a `u64`.
4572 pub fn as_u64(&self) -> u64 {
4573 self.0.as_ffi()
4574 }
4575}
4576
4577impl From<u64> for WindowId {
4578 fn from(value: u64) -> Self {
4579 WindowId(slotmap::KeyData::from_ffi(value))
4580 }
4581}
4582
4583/// A handle to a window with a specific root view type.
4584/// Note that this does not keep the window alive on its own.
4585#[derive(Deref, DerefMut)]
4586pub struct WindowHandle<V> {
4587 #[deref]
4588 #[deref_mut]
4589 pub(crate) any_handle: AnyWindowHandle,
4590 state_type: PhantomData<V>,
4591}
4592
4593impl<V: 'static + Render> WindowHandle<V> {
4594 /// Creates a new handle from a window ID.
4595 /// This does not check if the root type of the window is `V`.
4596 pub fn new(id: WindowId) -> Self {
4597 WindowHandle {
4598 any_handle: AnyWindowHandle {
4599 id,
4600 state_type: TypeId::of::<V>(),
4601 },
4602 state_type: PhantomData,
4603 }
4604 }
4605
4606 /// Get the root view out of this window.
4607 ///
4608 /// This will fail if the window is closed or if the root view's type does not match `V`.
4609 pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
4610 where
4611 C: Context,
4612 {
4613 Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
4614 root_view
4615 .downcast::<V>()
4616 .map_err(|_| anyhow!("the type of the window's root view has changed"))
4617 }))
4618 }
4619
4620 /// Updates the root view of this window.
4621 ///
4622 /// This will fail if the window has been closed or if the root view's type does not match
4623 pub fn update<C, R>(
4624 &self,
4625 cx: &mut C,
4626 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
4627 ) -> Result<R>
4628 where
4629 C: Context,
4630 {
4631 cx.update_window(self.any_handle, |root_view, cx| {
4632 let view = root_view
4633 .downcast::<V>()
4634 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4635 Ok(cx.update_view(&view, update))
4636 })?
4637 }
4638
4639 /// Read the root view out of this window.
4640 ///
4641 /// This will fail if the window is closed or if the root view's type does not match `V`.
4642 pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
4643 let x = cx
4644 .windows
4645 .get(self.id)
4646 .and_then(|window| {
4647 window
4648 .as_ref()
4649 .and_then(|window| window.root_view.clone())
4650 .map(|root_view| root_view.downcast::<V>())
4651 })
4652 .ok_or_else(|| anyhow!("window not found"))?
4653 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4654
4655 Ok(x.read(cx))
4656 }
4657
4658 /// Read the root view out of this window, with a callback
4659 ///
4660 /// This will fail if the window is closed or if the root view's type does not match `V`.
4661 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
4662 where
4663 C: Context,
4664 {
4665 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
4666 }
4667
4668 /// Read the root view pointer off of this window.
4669 ///
4670 /// This will fail if the window is closed or if the root view's type does not match `V`.
4671 pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
4672 where
4673 C: Context,
4674 {
4675 cx.read_window(self, |root_view, _cx| root_view.clone())
4676 }
4677
4678 /// Check if this window is 'active'.
4679 ///
4680 /// Will return `None` if the window is closed or currently
4681 /// borrowed.
4682 pub fn is_active(&self, cx: &mut AppContext) -> Option<bool> {
4683 cx.update_window(self.any_handle, |_, cx| cx.is_window_active())
4684 .ok()
4685 }
4686}
4687
4688impl<V> Copy for WindowHandle<V> {}
4689
4690impl<V> Clone for WindowHandle<V> {
4691 fn clone(&self) -> Self {
4692 *self
4693 }
4694}
4695
4696impl<V> PartialEq for WindowHandle<V> {
4697 fn eq(&self, other: &Self) -> bool {
4698 self.any_handle == other.any_handle
4699 }
4700}
4701
4702impl<V> Eq for WindowHandle<V> {}
4703
4704impl<V> Hash for WindowHandle<V> {
4705 fn hash<H: Hasher>(&self, state: &mut H) {
4706 self.any_handle.hash(state);
4707 }
4708}
4709
4710impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
4711 fn from(val: WindowHandle<V>) -> Self {
4712 val.any_handle
4713 }
4714}
4715
4716unsafe impl<V> Send for WindowHandle<V> {}
4717unsafe impl<V> Sync for WindowHandle<V> {}
4718
4719/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
4720#[derive(Copy, Clone, PartialEq, Eq, Hash)]
4721pub struct AnyWindowHandle {
4722 pub(crate) id: WindowId,
4723 state_type: TypeId,
4724}
4725
4726impl AnyWindowHandle {
4727 /// Get the ID of this window.
4728 pub fn window_id(&self) -> WindowId {
4729 self.id
4730 }
4731
4732 /// Attempt to convert this handle to a window handle with a specific root view type.
4733 /// If the types do not match, this will return `None`.
4734 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
4735 if TypeId::of::<T>() == self.state_type {
4736 Some(WindowHandle {
4737 any_handle: *self,
4738 state_type: PhantomData,
4739 })
4740 } else {
4741 None
4742 }
4743 }
4744
4745 /// Updates the state of the root view of this window.
4746 ///
4747 /// This will fail if the window has been closed.
4748 pub fn update<C, R>(
4749 self,
4750 cx: &mut C,
4751 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
4752 ) -> Result<R>
4753 where
4754 C: Context,
4755 {
4756 cx.update_window(self, update)
4757 }
4758
4759 /// Read the state of the root view of this window.
4760 ///
4761 /// This will fail if the window has been closed.
4762 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
4763 where
4764 C: Context,
4765 T: 'static,
4766 {
4767 let view = self
4768 .downcast::<T>()
4769 .context("the type of the window's root view has changed")?;
4770
4771 cx.read_window(&view, read)
4772 }
4773}
4774
4775/// An identifier for an [`Element`](crate::Element).
4776///
4777/// Can be constructed with a string, a number, or both, as well
4778/// as other internal representations.
4779#[derive(Clone, Debug, Eq, PartialEq, Hash)]
4780pub enum ElementId {
4781 /// The ID of a View element
4782 View(EntityId),
4783 /// An integer ID.
4784 Integer(usize),
4785 /// A string based ID.
4786 Name(SharedString),
4787 /// A UUID.
4788 Uuid(Uuid),
4789 /// An ID that's equated with a focus handle.
4790 FocusHandle(FocusId),
4791 /// A combination of a name and an integer.
4792 NamedInteger(SharedString, usize),
4793}
4794
4795impl Display for ElementId {
4796 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4797 match self {
4798 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
4799 ElementId::Integer(ix) => write!(f, "{}", ix)?,
4800 ElementId::Name(name) => write!(f, "{}", name)?,
4801 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
4802 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
4803 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
4804 }
4805
4806 Ok(())
4807 }
4808}
4809
4810impl TryInto<SharedString> for ElementId {
4811 type Error = anyhow::Error;
4812
4813 fn try_into(self) -> anyhow::Result<SharedString> {
4814 if let ElementId::Name(name) = self {
4815 Ok(name)
4816 } else {
4817 Err(anyhow!("element id is not string"))
4818 }
4819 }
4820}
4821
4822impl From<usize> for ElementId {
4823 fn from(id: usize) -> Self {
4824 ElementId::Integer(id)
4825 }
4826}
4827
4828impl From<i32> for ElementId {
4829 fn from(id: i32) -> Self {
4830 Self::Integer(id as usize)
4831 }
4832}
4833
4834impl From<SharedString> for ElementId {
4835 fn from(name: SharedString) -> Self {
4836 ElementId::Name(name)
4837 }
4838}
4839
4840impl From<&'static str> for ElementId {
4841 fn from(name: &'static str) -> Self {
4842 ElementId::Name(name.into())
4843 }
4844}
4845
4846impl<'a> From<&'a FocusHandle> for ElementId {
4847 fn from(handle: &'a FocusHandle) -> Self {
4848 ElementId::FocusHandle(handle.id)
4849 }
4850}
4851
4852impl From<(&'static str, EntityId)> for ElementId {
4853 fn from((name, id): (&'static str, EntityId)) -> Self {
4854 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
4855 }
4856}
4857
4858impl From<(&'static str, usize)> for ElementId {
4859 fn from((name, id): (&'static str, usize)) -> Self {
4860 ElementId::NamedInteger(name.into(), id)
4861 }
4862}
4863
4864impl From<(&'static str, u64)> for ElementId {
4865 fn from((name, id): (&'static str, u64)) -> Self {
4866 ElementId::NamedInteger(name.into(), id as usize)
4867 }
4868}
4869
4870impl From<Uuid> for ElementId {
4871 fn from(value: Uuid) -> Self {
4872 Self::Uuid(value)
4873 }
4874}
4875
4876impl From<(&'static str, u32)> for ElementId {
4877 fn from((name, id): (&'static str, u32)) -> Self {
4878 ElementId::NamedInteger(name.into(), id as usize)
4879 }
4880}
4881
4882/// A rectangle to be rendered in the window at the given position and size.
4883/// Passed as an argument [`WindowContext::paint_quad`].
4884#[derive(Clone)]
4885pub struct PaintQuad {
4886 /// The bounds of the quad within the window.
4887 pub bounds: Bounds<Pixels>,
4888 /// The radii of the quad's corners.
4889 pub corner_radii: Corners<Pixels>,
4890 /// The background color of the quad.
4891 pub background: Hsla,
4892 /// The widths of the quad's borders.
4893 pub border_widths: Edges<Pixels>,
4894 /// The color of the quad's borders.
4895 pub border_color: Hsla,
4896}
4897
4898impl PaintQuad {
4899 /// Sets the corner radii of the quad.
4900 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
4901 PaintQuad {
4902 corner_radii: corner_radii.into(),
4903 ..self
4904 }
4905 }
4906
4907 /// Sets the border widths of the quad.
4908 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
4909 PaintQuad {
4910 border_widths: border_widths.into(),
4911 ..self
4912 }
4913 }
4914
4915 /// Sets the border color of the quad.
4916 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
4917 PaintQuad {
4918 border_color: border_color.into(),
4919 ..self
4920 }
4921 }
4922
4923 /// Sets the background color of the quad.
4924 pub fn background(self, background: impl Into<Hsla>) -> Self {
4925 PaintQuad {
4926 background: background.into(),
4927 ..self
4928 }
4929 }
4930}
4931
4932/// Creates a quad with the given parameters.
4933pub fn quad(
4934 bounds: Bounds<Pixels>,
4935 corner_radii: impl Into<Corners<Pixels>>,
4936 background: impl Into<Hsla>,
4937 border_widths: impl Into<Edges<Pixels>>,
4938 border_color: impl Into<Hsla>,
4939) -> PaintQuad {
4940 PaintQuad {
4941 bounds,
4942 corner_radii: corner_radii.into(),
4943 background: background.into(),
4944 border_widths: border_widths.into(),
4945 border_color: border_color.into(),
4946 }
4947}
4948
4949/// Creates a filled quad with the given bounds and background color.
4950pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
4951 PaintQuad {
4952 bounds: bounds.into(),
4953 corner_radii: (0.).into(),
4954 background: background.into(),
4955 border_widths: (0.).into(),
4956 border_color: transparent_black(),
4957 }
4958}
4959
4960/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
4961pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
4962 PaintQuad {
4963 bounds: bounds.into(),
4964 corner_radii: (0.).into(),
4965 background: transparent_black(),
4966 border_widths: (1.).into(),
4967 border_color: border_color.into(),
4968 }
4969}