1use crate::{
2 px, size, transparent_black, Action, AnyDrag, AnyTooltip, AnyView, AppContext, Arena,
3 AsyncWindowContext, AvailableSpace, Bounds, BoxShadow, Context, Corners, CursorStyle,
4 DevicePixels, DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect,
5 Entity, EntityId, EventEmitter, FileDropEvent, Flatten, FontId, GlobalElementId, GlyphId, Hsla,
6 ImageData, InputHandler, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent,
7 KeymatchResult, KeystrokeEvent, LayoutId, Model, ModelContext, Modifiers, MonochromeSprite,
8 MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas,
9 PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point, PolychromeSprite,
10 PromptLevel, Quad, Render, RenderGlyphParams, RenderImageParams, RenderSvgParams, ScaledPixels,
11 Scene, Shadow, SharedString, Size, Style, SubscriberSet, Subscription, Surface,
12 TaffyLayoutEngine, Task, Underline, UnderlineStyle, View, VisualContext, WeakView,
13 WindowBounds, WindowOptions, SUBPIXEL_VARIANTS,
14};
15use anyhow::{anyhow, Context as _, Result};
16use collections::{FxHashMap, FxHashSet};
17use derive_more::{Deref, DerefMut};
18use futures::{
19 channel::{mpsc, oneshot},
20 StreamExt,
21};
22use media::core_video::CVImageBuffer;
23use parking_lot::RwLock;
24use slotmap::SlotMap;
25use smallvec::SmallVec;
26use std::{
27 any::{Any, TypeId},
28 borrow::{Borrow, BorrowMut, Cow},
29 cell::RefCell,
30 collections::hash_map::Entry,
31 fmt::{Debug, Display},
32 future::Future,
33 hash::{Hash, Hasher},
34 marker::PhantomData,
35 mem,
36 rc::Rc,
37 sync::{
38 atomic::{AtomicUsize, Ordering::SeqCst},
39 Arc,
40 },
41 time::Duration,
42};
43use util::{post_inc, ResultExt};
44
45const ACTIVE_DRAG_Z_INDEX: u8 = 1;
46
47/// A global stacking order, which is created by stacking successive z-index values.
48/// Each z-index will always be interpreted in the context of its parent z-index.
49#[derive(Deref, DerefMut, Clone, Ord, PartialOrd, PartialEq, Eq, Default)]
50pub struct StackingOrder {
51 #[deref]
52 #[deref_mut]
53 context_stack: SmallVec<[u8; 64]>,
54 id: u32,
55}
56
57impl std::fmt::Debug for StackingOrder {
58 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59 let mut stacks = self.context_stack.iter().peekable();
60 write!(f, "[({}): ", self.id)?;
61 while let Some(z_index) = stacks.next() {
62 write!(f, "{z_index}")?;
63 if stacks.peek().is_some() {
64 write!(f, "->")?;
65 }
66 }
67 write!(f, "]")?;
68 Ok(())
69 }
70}
71
72/// Represents the two different phases when dispatching events.
73#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
74pub enum DispatchPhase {
75 /// After the capture phase comes the bubble phase, in which mouse event listeners are
76 /// invoked front to back and keyboard event listeners are invoked from the focused element
77 /// to the root of the element tree. This is the phase you'll most commonly want to use when
78 /// registering event listeners.
79 #[default]
80 Bubble,
81 /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
82 /// listeners are invoked from the root of the tree downward toward the focused element. This phase
83 /// is used for special purposes such as clearing the "pressed" state for click events. If
84 /// you stop event propagation during this phase, you need to know what you're doing. Handlers
85 /// outside of the immediate region may rely on detecting non-local events during this phase.
86 Capture,
87}
88
89impl DispatchPhase {
90 /// Returns true if this represents the "bubble" phase.
91 pub fn bubble(self) -> bool {
92 self == DispatchPhase::Bubble
93 }
94
95 /// Returns true if this represents the "capture" phase.
96 pub fn capture(self) -> bool {
97 self == DispatchPhase::Capture
98 }
99}
100
101type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
102type AnyMouseListener = Box<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
103type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
104
105struct FocusEvent {
106 previous_focus_path: SmallVec<[FocusId; 8]>,
107 current_focus_path: SmallVec<[FocusId; 8]>,
108}
109
110slotmap::new_key_type! {
111 /// A globally unique identifier for a focusable element.
112 pub struct FocusId;
113}
114
115thread_local! {
116 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(4 * 1024 * 1024));
117}
118
119impl FocusId {
120 /// Obtains whether the element associated with this handle is currently focused.
121 pub fn is_focused(&self, cx: &WindowContext) -> bool {
122 cx.window.focus == Some(*self)
123 }
124
125 /// Obtains whether the element associated with this handle contains the focused
126 /// element or is itself focused.
127 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
128 cx.focused()
129 .map_or(false, |focused| self.contains(focused.id, cx))
130 }
131
132 /// Obtains whether the element associated with this handle is contained within the
133 /// focused element or is itself focused.
134 pub fn within_focused(&self, cx: &WindowContext) -> bool {
135 let focused = cx.focused();
136 focused.map_or(false, |focused| focused.id.contains(*self, cx))
137 }
138
139 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
140 pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
141 cx.window
142 .rendered_frame
143 .dispatch_tree
144 .focus_contains(*self, other)
145 }
146}
147
148/// A handle which can be used to track and manipulate the focused element in a window.
149pub struct FocusHandle {
150 pub(crate) id: FocusId,
151 handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
152}
153
154impl std::fmt::Debug for FocusHandle {
155 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
157 }
158}
159
160impl FocusHandle {
161 pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
162 let id = handles.write().insert(AtomicUsize::new(1));
163 Self {
164 id,
165 handles: handles.clone(),
166 }
167 }
168
169 pub(crate) fn for_id(
170 id: FocusId,
171 handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
172 ) -> Option<Self> {
173 let lock = handles.read();
174 let ref_count = lock.get(id)?;
175 if ref_count.load(SeqCst) == 0 {
176 None
177 } else {
178 ref_count.fetch_add(1, SeqCst);
179 Some(Self {
180 id,
181 handles: handles.clone(),
182 })
183 }
184 }
185
186 /// Moves the focus to the element associated with this handle.
187 pub fn focus(&self, cx: &mut WindowContext) {
188 cx.focus(self)
189 }
190
191 /// Obtains whether the element associated with this handle is currently focused.
192 pub fn is_focused(&self, cx: &WindowContext) -> bool {
193 self.id.is_focused(cx)
194 }
195
196 /// Obtains whether the element associated with this handle contains the focused
197 /// element or is itself focused.
198 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
199 self.id.contains_focused(cx)
200 }
201
202 /// Obtains whether the element associated with this handle is contained within the
203 /// focused element or is itself focused.
204 pub fn within_focused(&self, cx: &WindowContext) -> bool {
205 self.id.within_focused(cx)
206 }
207
208 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
209 pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
210 self.id.contains(other.id, cx)
211 }
212}
213
214impl Clone for FocusHandle {
215 fn clone(&self) -> Self {
216 Self::for_id(self.id, &self.handles).unwrap()
217 }
218}
219
220impl PartialEq for FocusHandle {
221 fn eq(&self, other: &Self) -> bool {
222 self.id == other.id
223 }
224}
225
226impl Eq for FocusHandle {}
227
228impl Drop for FocusHandle {
229 fn drop(&mut self) {
230 self.handles
231 .read()
232 .get(self.id)
233 .unwrap()
234 .fetch_sub(1, SeqCst);
235 }
236}
237
238/// FocusableView allows users of your view to easily
239/// focus it (using cx.focus_view(view))
240pub trait FocusableView: 'static + Render {
241 /// Returns the focus handle associated with this view.
242 fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
243}
244
245/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
246/// where the lifecycle of the view is handled by another view.
247pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
248
249impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
250
251/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
252pub struct DismissEvent;
253
254// Holds the state for a specific window.
255#[doc(hidden)]
256pub struct Window {
257 pub(crate) handle: AnyWindowHandle,
258 pub(crate) removed: bool,
259 pub(crate) platform_window: Box<dyn PlatformWindow>,
260 display_id: DisplayId,
261 sprite_atlas: Arc<dyn PlatformAtlas>,
262 rem_size: Pixels,
263 viewport_size: Size<Pixels>,
264 layout_engine: Option<TaffyLayoutEngine>,
265 pub(crate) root_view: Option<AnyView>,
266 pub(crate) element_id_stack: GlobalElementId,
267 pub(crate) rendered_frame: Frame,
268 pub(crate) next_frame: Frame,
269 pub(crate) dirty_views: FxHashSet<EntityId>,
270 pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
271 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
272 focus_lost_listeners: SubscriberSet<(), AnyObserver>,
273 default_prevented: bool,
274 mouse_position: Point<Pixels>,
275 modifiers: Modifiers,
276 scale_factor: f32,
277 bounds: WindowBounds,
278 bounds_observers: SubscriberSet<(), AnyObserver>,
279 active: bool,
280 pub(crate) dirty: bool,
281 pub(crate) refreshing: bool,
282 pub(crate) drawing: bool,
283 activation_observers: SubscriberSet<(), AnyObserver>,
284 pub(crate) focus: Option<FocusId>,
285 focus_enabled: bool,
286 pending_input: Option<PendingInput>,
287
288 #[cfg(any(test, feature = "test-support"))]
289 pub(crate) focus_invalidated: bool,
290}
291
292#[derive(Default)]
293struct PendingInput {
294 text: String,
295 actions: SmallVec<[Box<dyn Action>; 1]>,
296 focus: Option<FocusId>,
297 timer: Option<Task<()>>,
298}
299
300pub(crate) struct ElementStateBox {
301 inner: Box<dyn Any>,
302 parent_view_id: EntityId,
303 #[cfg(debug_assertions)]
304 type_name: &'static str,
305}
306
307struct RequestedInputHandler {
308 view_id: EntityId,
309 handler: Option<PlatformInputHandler>,
310}
311
312struct TooltipRequest {
313 view_id: EntityId,
314 tooltip: AnyTooltip,
315}
316
317pub(crate) struct Frame {
318 focus: Option<FocusId>,
319 window_active: bool,
320 pub(crate) element_states: FxHashMap<GlobalElementId, ElementStateBox>,
321 mouse_listeners: FxHashMap<TypeId, Vec<(StackingOrder, EntityId, AnyMouseListener)>>,
322 pub(crate) dispatch_tree: DispatchTree,
323 pub(crate) scene: Scene,
324 pub(crate) depth_map: Vec<(StackingOrder, EntityId, Bounds<Pixels>)>,
325 pub(crate) z_index_stack: StackingOrder,
326 pub(crate) next_stacking_order_id: u32,
327 next_root_z_index: u8,
328 content_mask_stack: Vec<ContentMask<Pixels>>,
329 element_offset_stack: Vec<Point<Pixels>>,
330 requested_input_handler: Option<RequestedInputHandler>,
331 tooltip_request: Option<TooltipRequest>,
332 cursor_styles: FxHashMap<EntityId, CursorStyle>,
333 requested_cursor_style: Option<CursorStyle>,
334 pub(crate) view_stack: Vec<EntityId>,
335 pub(crate) reused_views: FxHashSet<EntityId>,
336
337 #[cfg(any(test, feature = "test-support"))]
338 pub(crate) debug_bounds: collections::FxHashMap<String, Bounds<Pixels>>,
339}
340
341impl Frame {
342 fn new(dispatch_tree: DispatchTree) -> Self {
343 Frame {
344 focus: None,
345 window_active: false,
346 element_states: FxHashMap::default(),
347 mouse_listeners: FxHashMap::default(),
348 dispatch_tree,
349 scene: Scene::default(),
350 depth_map: Vec::new(),
351 z_index_stack: StackingOrder::default(),
352 next_stacking_order_id: 0,
353 next_root_z_index: 0,
354 content_mask_stack: Vec::new(),
355 element_offset_stack: Vec::new(),
356 requested_input_handler: None,
357 tooltip_request: None,
358 cursor_styles: FxHashMap::default(),
359 requested_cursor_style: None,
360 view_stack: Vec::new(),
361 reused_views: FxHashSet::default(),
362
363 #[cfg(any(test, feature = "test-support"))]
364 debug_bounds: FxHashMap::default(),
365 }
366 }
367
368 fn clear(&mut self) {
369 self.element_states.clear();
370 self.mouse_listeners.values_mut().for_each(Vec::clear);
371 self.dispatch_tree.clear();
372 self.depth_map.clear();
373 self.next_stacking_order_id = 0;
374 self.next_root_z_index = 0;
375 self.reused_views.clear();
376 self.scene.clear();
377 self.requested_input_handler.take();
378 self.tooltip_request.take();
379 self.cursor_styles.clear();
380 self.requested_cursor_style.take();
381 debug_assert_eq!(self.view_stack.len(), 0);
382 }
383
384 fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
385 self.focus
386 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
387 .unwrap_or_default()
388 }
389
390 fn finish(&mut self, prev_frame: &mut Self) {
391 // Reuse mouse listeners that didn't change since the last frame.
392 for (type_id, listeners) in &mut prev_frame.mouse_listeners {
393 let next_listeners = self.mouse_listeners.entry(*type_id).or_default();
394 for (order, view_id, listener) in listeners.drain(..) {
395 if self.reused_views.contains(&view_id) {
396 next_listeners.push((order, view_id, listener));
397 }
398 }
399 }
400
401 // Reuse entries in the depth map that didn't change since the last frame.
402 for (order, view_id, bounds) in prev_frame.depth_map.drain(..) {
403 if self.reused_views.contains(&view_id) {
404 match self
405 .depth_map
406 .binary_search_by(|(level, _, _)| order.cmp(level))
407 {
408 Ok(i) | Err(i) => self.depth_map.insert(i, (order, view_id, bounds)),
409 }
410 }
411 }
412
413 // Retain element states for views that didn't change since the last frame.
414 for (element_id, state) in prev_frame.element_states.drain() {
415 if self.reused_views.contains(&state.parent_view_id) {
416 self.element_states.entry(element_id).or_insert(state);
417 }
418 }
419
420 // Reuse geometry that didn't change since the last frame.
421 self.scene
422 .reuse_views(&self.reused_views, &mut prev_frame.scene);
423 self.scene.finish();
424 }
425}
426
427impl Window {
428 pub(crate) fn new(
429 handle: AnyWindowHandle,
430 options: WindowOptions,
431 cx: &mut AppContext,
432 ) -> Self {
433 let platform_window = cx.platform.open_window(handle, options);
434 let display_id = platform_window.display().id();
435 let sprite_atlas = platform_window.sprite_atlas();
436 let mouse_position = platform_window.mouse_position();
437 let modifiers = platform_window.modifiers();
438 let content_size = platform_window.content_size();
439 let scale_factor = platform_window.scale_factor();
440 let bounds = platform_window.bounds();
441
442 platform_window.on_request_frame(Box::new({
443 let mut cx = cx.to_async();
444 move || {
445 handle.update(&mut cx, |_, cx| cx.draw()).log_err();
446 }
447 }));
448 platform_window.on_resize(Box::new({
449 let mut cx = cx.to_async();
450 move |_, _| {
451 handle
452 .update(&mut cx, |_, cx| cx.window_bounds_changed())
453 .log_err();
454 }
455 }));
456 platform_window.on_moved(Box::new({
457 let mut cx = cx.to_async();
458 move || {
459 handle
460 .update(&mut cx, |_, cx| cx.window_bounds_changed())
461 .log_err();
462 }
463 }));
464 platform_window.on_active_status_change(Box::new({
465 let mut cx = cx.to_async();
466 move |active| {
467 handle
468 .update(&mut cx, |_, cx| {
469 cx.window.active = active;
470 cx.window
471 .activation_observers
472 .clone()
473 .retain(&(), |callback| callback(cx));
474 })
475 .log_err();
476 }
477 }));
478
479 platform_window.on_input({
480 let mut cx = cx.to_async();
481 Box::new(move |event| {
482 handle
483 .update(&mut cx, |_, cx| cx.dispatch_event(event))
484 .log_err()
485 .unwrap_or(false)
486 })
487 });
488
489 Window {
490 handle,
491 removed: false,
492 platform_window,
493 display_id,
494 sprite_atlas,
495 rem_size: px(16.),
496 viewport_size: content_size,
497 layout_engine: Some(TaffyLayoutEngine::new()),
498 root_view: None,
499 element_id_stack: GlobalElementId::default(),
500 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
501 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
502 dirty_views: FxHashSet::default(),
503 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
504 focus_listeners: SubscriberSet::new(),
505 focus_lost_listeners: SubscriberSet::new(),
506 default_prevented: true,
507 mouse_position,
508 modifiers,
509 scale_factor,
510 bounds,
511 bounds_observers: SubscriberSet::new(),
512 active: false,
513 dirty: false,
514 refreshing: false,
515 drawing: false,
516 activation_observers: SubscriberSet::new(),
517 focus: None,
518 focus_enabled: true,
519 pending_input: None,
520
521 #[cfg(any(test, feature = "test-support"))]
522 focus_invalidated: false,
523 }
524 }
525}
526
527/// Indicates which region of the window is visible. Content falling outside of this mask will not be
528/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
529/// to leave room to support more complex shapes in the future.
530#[derive(Clone, Debug, Default, PartialEq, Eq)]
531#[repr(C)]
532pub struct ContentMask<P: Clone + Default + Debug> {
533 /// The bounds
534 pub bounds: Bounds<P>,
535}
536
537impl ContentMask<Pixels> {
538 /// Scale the content mask's pixel units by the given scaling factor.
539 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
540 ContentMask {
541 bounds: self.bounds.scale(factor),
542 }
543 }
544
545 /// Intersect the content mask with the given content mask.
546 pub fn intersect(&self, other: &Self) -> Self {
547 let bounds = self.bounds.intersect(&other.bounds);
548 ContentMask { bounds }
549 }
550}
551
552/// Provides access to application state in the context of a single window. Derefs
553/// to an [`AppContext`], so you can also pass a [`WindowContext`] to any method that takes
554/// an [`AppContext`] and call any [`AppContext`] methods.
555pub struct WindowContext<'a> {
556 pub(crate) app: &'a mut AppContext,
557 pub(crate) window: &'a mut Window,
558}
559
560impl<'a> WindowContext<'a> {
561 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
562 Self { app, window }
563 }
564
565 /// Obtain a handle to the window that belongs to this context.
566 pub fn window_handle(&self) -> AnyWindowHandle {
567 self.window.handle
568 }
569
570 /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
571 pub fn refresh(&mut self) {
572 if !self.window.drawing {
573 self.window.refreshing = true;
574 self.window.dirty = true;
575 }
576 }
577
578 /// Close this window.
579 pub fn remove_window(&mut self) {
580 self.window.removed = true;
581 }
582
583 /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
584 /// for elements rendered within this window.
585 pub fn focus_handle(&mut self) -> FocusHandle {
586 FocusHandle::new(&self.window.focus_handles)
587 }
588
589 /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
590 pub fn focused(&self) -> Option<FocusHandle> {
591 self.window
592 .focus
593 .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
594 }
595
596 /// Move focus to the element associated with the given [`FocusHandle`].
597 pub fn focus(&mut self, handle: &FocusHandle) {
598 if !self.window.focus_enabled || self.window.focus == Some(handle.id) {
599 return;
600 }
601
602 self.window.focus = Some(handle.id);
603 self.window
604 .rendered_frame
605 .dispatch_tree
606 .clear_pending_keystrokes();
607
608 #[cfg(any(test, feature = "test-support"))]
609 {
610 self.window.focus_invalidated = true;
611 }
612
613 self.refresh();
614 }
615
616 /// Remove focus from all elements within this context's window.
617 pub fn blur(&mut self) {
618 if !self.window.focus_enabled {
619 return;
620 }
621
622 self.window.focus = None;
623 self.refresh();
624 }
625
626 /// Blur the window and don't allow anything in it to be focused again.
627 pub fn disable_focus(&mut self) {
628 self.blur();
629 self.window.focus_enabled = false;
630 }
631
632 /// Dispatch the given action on the currently focused element.
633 pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
634 let focus_handle = self.focused();
635
636 self.defer(move |cx| {
637 let node_id = focus_handle
638 .and_then(|handle| {
639 cx.window
640 .rendered_frame
641 .dispatch_tree
642 .focusable_node_id(handle.id)
643 })
644 .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
645
646 cx.propagate_event = true;
647 cx.dispatch_action_on_node(node_id, action);
648 })
649 }
650
651 pub(crate) fn dispatch_keystroke_observers(
652 &mut self,
653 event: &dyn Any,
654 action: Option<Box<dyn Action>>,
655 ) {
656 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
657 return;
658 };
659
660 self.keystroke_observers
661 .clone()
662 .retain(&(), move |callback| {
663 (callback)(
664 &KeystrokeEvent {
665 keystroke: key_down_event.keystroke.clone(),
666 action: action.as_ref().map(|action| action.boxed_clone()),
667 },
668 self,
669 );
670 true
671 });
672 }
673
674 pub(crate) fn clear_pending_keystrokes(&mut self) {
675 self.window
676 .rendered_frame
677 .dispatch_tree
678 .clear_pending_keystrokes();
679 self.window
680 .next_frame
681 .dispatch_tree
682 .clear_pending_keystrokes();
683 }
684
685 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
686 /// that are currently on the stack to be returned to the app.
687 pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
688 let handle = self.window.handle;
689 self.app.defer(move |cx| {
690 handle.update(cx, |_, cx| f(cx)).ok();
691 });
692 }
693
694 /// Subscribe to events emitted by a model or view.
695 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
696 /// 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.
697 pub fn subscribe<Emitter, E, Evt>(
698 &mut self,
699 entity: &E,
700 mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
701 ) -> Subscription
702 where
703 Emitter: EventEmitter<Evt>,
704 E: Entity<Emitter>,
705 Evt: 'static,
706 {
707 let entity_id = entity.entity_id();
708 let entity = entity.downgrade();
709 let window_handle = self.window.handle;
710 let (subscription, activate) = self.app.event_listeners.insert(
711 entity_id,
712 (
713 TypeId::of::<Evt>(),
714 Box::new(move |event, cx| {
715 window_handle
716 .update(cx, |_, cx| {
717 if let Some(handle) = E::upgrade_from(&entity) {
718 let event = event.downcast_ref().expect("invalid event type");
719 on_event(handle, event, cx);
720 true
721 } else {
722 false
723 }
724 })
725 .unwrap_or(false)
726 }),
727 ),
728 );
729 self.app.defer(move |_| activate());
730 subscription
731 }
732
733 /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
734 /// await points in async code.
735 pub fn to_async(&self) -> AsyncWindowContext {
736 AsyncWindowContext::new(self.app.to_async(), self.window.handle)
737 }
738
739 /// Schedule the given closure to be run directly after the current frame is rendered.
740 pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
741 let handle = self.window.handle;
742 let display_id = self.window.display_id;
743
744 let mut frame_consumers = std::mem::take(&mut self.app.frame_consumers);
745 if let Entry::Vacant(e) = frame_consumers.entry(display_id) {
746 let (tx, mut rx) = mpsc::unbounded::<()>();
747 self.platform.set_display_link_output_callback(
748 display_id,
749 Box::new(move || _ = tx.unbounded_send(())),
750 );
751
752 let consumer_task = self.app.spawn(|cx| async move {
753 while rx.next().await.is_some() {
754 cx.update(|cx| {
755 for callback in cx
756 .next_frame_callbacks
757 .get_mut(&display_id)
758 .unwrap()
759 .drain(..)
760 .collect::<SmallVec<[_; 32]>>()
761 {
762 callback(cx);
763 }
764 })
765 .ok();
766
767 // Flush effects, then stop the display link if no new next_frame_callbacks have been added.
768
769 cx.update(|cx| {
770 if cx.next_frame_callbacks.is_empty() {
771 cx.platform.stop_display_link(display_id);
772 }
773 })
774 .ok();
775 }
776 });
777 e.insert(consumer_task);
778 }
779 debug_assert!(self.app.frame_consumers.is_empty());
780 self.app.frame_consumers = frame_consumers;
781
782 if self.next_frame_callbacks.is_empty() {
783 self.platform.start_display_link(display_id);
784 }
785
786 self.next_frame_callbacks
787 .entry(display_id)
788 .or_default()
789 .push(Box::new(move |cx: &mut AppContext| {
790 cx.update_window(handle, |_root_view, cx| callback(cx)).ok();
791 }));
792 }
793
794 /// Spawn the future returned by the given closure on the application thread pool.
795 /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
796 /// use within your future.
797 pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
798 where
799 R: 'static,
800 Fut: Future<Output = R> + 'static,
801 {
802 self.app
803 .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
804 }
805
806 /// Updates the global of the given type. The given closure is given simultaneous mutable
807 /// access both to the global and the context.
808 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
809 where
810 G: 'static,
811 {
812 let mut global = self.app.lease_global::<G>();
813 let result = f(&mut global, self);
814 self.app.end_global_lease(global);
815 result
816 }
817
818 #[must_use]
819 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
820 /// layout is being requested, along with the layout ids of any children. This method is called during
821 /// calls to the `Element::layout` trait method and enables any element to participate in layout.
822 pub fn request_layout(
823 &mut self,
824 style: &Style,
825 children: impl IntoIterator<Item = LayoutId>,
826 ) -> LayoutId {
827 self.app.layout_id_buffer.clear();
828 self.app.layout_id_buffer.extend(children);
829 let rem_size = self.rem_size();
830
831 self.window.layout_engine.as_mut().unwrap().request_layout(
832 style,
833 rem_size,
834 &self.app.layout_id_buffer,
835 )
836 }
837
838 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
839 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
840 /// determine the element's size. One place this is used internally is when measuring text.
841 ///
842 /// The given closure is invoked at layout time with the known dimensions and available space and
843 /// returns a `Size`.
844 pub fn request_measured_layout<
845 F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
846 + 'static,
847 >(
848 &mut self,
849 style: Style,
850 measure: F,
851 ) -> LayoutId {
852 let rem_size = self.rem_size();
853 self.window
854 .layout_engine
855 .as_mut()
856 .unwrap()
857 .request_measured_layout(style, rem_size, measure)
858 }
859
860 pub(crate) fn layout_style(&self, layout_id: LayoutId) -> Option<&Style> {
861 self.window
862 .layout_engine
863 .as_ref()
864 .unwrap()
865 .requested_style(layout_id)
866 }
867
868 /// Compute the layout for the given id within the given available space.
869 /// This method is called for its side effect, typically by the framework prior to painting.
870 /// After calling it, you can request the bounds of the given layout node id or any descendant.
871 pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
872 let mut layout_engine = self.window.layout_engine.take().unwrap();
873 layout_engine.compute_layout(layout_id, available_space, self);
874 self.window.layout_engine = Some(layout_engine);
875 }
876
877 /// Obtain the bounds computed for the given LayoutId relative to the window. This method should not
878 /// be invoked until the paint phase begins, and will usually be invoked by GPUI itself automatically
879 /// in order to pass your element its `Bounds` automatically.
880 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
881 let mut bounds = self
882 .window
883 .layout_engine
884 .as_mut()
885 .unwrap()
886 .layout_bounds(layout_id)
887 .map(Into::into);
888 bounds.origin += self.element_offset();
889 bounds
890 }
891
892 fn window_bounds_changed(&mut self) {
893 self.window.scale_factor = self.window.platform_window.scale_factor();
894 self.window.viewport_size = self.window.platform_window.content_size();
895 self.window.bounds = self.window.platform_window.bounds();
896 self.window.display_id = self.window.platform_window.display().id();
897 self.refresh();
898
899 self.window
900 .bounds_observers
901 .clone()
902 .retain(&(), |callback| callback(self));
903 }
904
905 /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
906 pub fn window_bounds(&self) -> WindowBounds {
907 self.window.bounds
908 }
909
910 /// Returns the size of the drawable area within the window.
911 pub fn viewport_size(&self) -> Size<Pixels> {
912 self.window.viewport_size
913 }
914
915 /// Returns whether this window is focused by the operating system (receiving key events).
916 pub fn is_window_active(&self) -> bool {
917 self.window.active
918 }
919
920 /// Toggle zoom on the window.
921 pub fn zoom_window(&self) {
922 self.window.platform_window.zoom();
923 }
924
925 /// Updates the window's title at the platform level.
926 pub fn set_window_title(&mut self, title: &str) {
927 self.window.platform_window.set_title(title);
928 }
929
930 /// Mark the window as dirty at the platform level.
931 pub fn set_window_edited(&mut self, edited: bool) {
932 self.window.platform_window.set_edited(edited);
933 }
934
935 /// Determine the display on which the window is visible.
936 pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
937 self.platform
938 .displays()
939 .into_iter()
940 .find(|display| display.id() == self.window.display_id)
941 }
942
943 /// Show the platform character palette.
944 pub fn show_character_palette(&self) {
945 self.window.platform_window.show_character_palette();
946 }
947
948 /// The scale factor of the display associated with the window. For example, it could
949 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
950 /// be rendered as two pixels on screen.
951 pub fn scale_factor(&self) -> f32 {
952 self.window.scale_factor
953 }
954
955 /// The size of an em for the base font of the application. Adjusting this value allows the
956 /// UI to scale, just like zooming a web page.
957 pub fn rem_size(&self) -> Pixels {
958 self.window.rem_size
959 }
960
961 /// Sets the size of an em for the base font of the application. Adjusting this value allows the
962 /// UI to scale, just like zooming a web page.
963 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
964 self.window.rem_size = rem_size.into();
965 }
966
967 /// The line height associated with the current text style.
968 pub fn line_height(&self) -> Pixels {
969 let rem_size = self.rem_size();
970 let text_style = self.text_style();
971 text_style
972 .line_height
973 .to_pixels(text_style.font_size, rem_size)
974 }
975
976 /// Call to prevent the default action of an event. Currently only used to prevent
977 /// parent elements from becoming focused on mouse down.
978 pub fn prevent_default(&mut self) {
979 self.window.default_prevented = true;
980 }
981
982 /// Obtain whether default has been prevented for the event currently being dispatched.
983 pub fn default_prevented(&self) -> bool {
984 self.window.default_prevented
985 }
986
987 /// Register a mouse event listener on the window for the next frame. The type of event
988 /// is determined by the first parameter of the given listener. When the next frame is rendered
989 /// the listener will be cleared.
990 pub fn on_mouse_event<Event: MouseEvent>(
991 &mut self,
992 mut handler: impl FnMut(&Event, DispatchPhase, &mut WindowContext) + 'static,
993 ) {
994 let view_id = self.parent_view_id();
995 let order = self.window.next_frame.z_index_stack.clone();
996 self.window
997 .next_frame
998 .mouse_listeners
999 .entry(TypeId::of::<Event>())
1000 .or_default()
1001 .push((
1002 order,
1003 view_id,
1004 Box::new(
1005 move |event: &dyn Any, phase: DispatchPhase, cx: &mut WindowContext<'_>| {
1006 handler(event.downcast_ref().unwrap(), phase, cx)
1007 },
1008 ),
1009 ))
1010 }
1011
1012 /// Register a key event listener on the window for the next frame. The type of event
1013 /// is determined by the first parameter of the given listener. When the next frame is rendered
1014 /// the listener will be cleared.
1015 ///
1016 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
1017 /// a specific need to register a global listener.
1018 pub fn on_key_event<Event: KeyEvent>(
1019 &mut self,
1020 listener: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
1021 ) {
1022 self.window.next_frame.dispatch_tree.on_key_event(Rc::new(
1023 move |event: &dyn Any, phase, cx: &mut WindowContext<'_>| {
1024 if let Some(event) = event.downcast_ref::<Event>() {
1025 listener(event, phase, cx)
1026 }
1027 },
1028 ));
1029 }
1030
1031 /// Register an action listener on the window for the next frame. The type of action
1032 /// is determined by the first parameter of the given listener. When the next frame is rendered
1033 /// the listener will be cleared.
1034 ///
1035 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
1036 /// a specific need to register a global listener.
1037 pub fn on_action(
1038 &mut self,
1039 action_type: TypeId,
1040 listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
1041 ) {
1042 self.window
1043 .next_frame
1044 .dispatch_tree
1045 .on_action(action_type, Rc::new(listener));
1046 }
1047
1048 /// Determine whether the given action is available along the dispatch path to the currently focused element.
1049 pub fn is_action_available(&self, action: &dyn Action) -> bool {
1050 let target = self
1051 .focused()
1052 .and_then(|focused_handle| {
1053 self.window
1054 .rendered_frame
1055 .dispatch_tree
1056 .focusable_node_id(focused_handle.id)
1057 })
1058 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1059 self.window
1060 .rendered_frame
1061 .dispatch_tree
1062 .is_action_available(action, target)
1063 }
1064
1065 /// The position of the mouse relative to the window.
1066 pub fn mouse_position(&self) -> Point<Pixels> {
1067 self.window.mouse_position
1068 }
1069
1070 /// The current state of the keyboard's modifiers
1071 pub fn modifiers(&self) -> Modifiers {
1072 self.window.modifiers
1073 }
1074
1075 /// Updates the cursor style at the platform level.
1076 pub fn set_cursor_style(&mut self, style: CursorStyle) {
1077 let view_id = self.parent_view_id();
1078 self.window.next_frame.cursor_styles.insert(view_id, style);
1079 self.window.next_frame.requested_cursor_style = Some(style);
1080 }
1081
1082 /// Sets a tooltip to be rendered for the upcoming frame
1083 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) {
1084 let view_id = self.parent_view_id();
1085 self.window.next_frame.tooltip_request = Some(TooltipRequest { view_id, tooltip });
1086 }
1087
1088 /// Called during painting to track which z-index is on top at each pixel position
1089 pub fn add_opaque_layer(&mut self, bounds: Bounds<Pixels>) {
1090 let stacking_order = self.window.next_frame.z_index_stack.clone();
1091 let view_id = self.parent_view_id();
1092 let depth_map = &mut self.window.next_frame.depth_map;
1093 match depth_map.binary_search_by(|(level, _, _)| stacking_order.cmp(level)) {
1094 Ok(i) | Err(i) => depth_map.insert(i, (stacking_order, view_id, bounds)),
1095 }
1096 }
1097
1098 /// Returns true if there is no opaque layer containing the given point
1099 /// on top of the given level. Layers whose level is an extension of the
1100 /// level are not considered to be on top of the level.
1101 pub fn was_top_layer(&self, point: &Point<Pixels>, level: &StackingOrder) -> bool {
1102 for (opaque_level, _, bounds) in self.window.rendered_frame.depth_map.iter() {
1103 if level >= opaque_level {
1104 break;
1105 }
1106
1107 if bounds.contains(point) && !opaque_level.starts_with(level) {
1108 return false;
1109 }
1110 }
1111 true
1112 }
1113
1114 pub(crate) fn was_top_layer_under_active_drag(
1115 &self,
1116 point: &Point<Pixels>,
1117 level: &StackingOrder,
1118 ) -> bool {
1119 for (opaque_level, _, bounds) in self.window.rendered_frame.depth_map.iter() {
1120 if level >= opaque_level {
1121 break;
1122 }
1123 if opaque_level.starts_with(&[ACTIVE_DRAG_Z_INDEX]) {
1124 continue;
1125 }
1126
1127 if bounds.contains(point) && !opaque_level.starts_with(level) {
1128 return false;
1129 }
1130 }
1131 true
1132 }
1133
1134 /// Called during painting to get the current stacking order.
1135 pub fn stacking_order(&self) -> &StackingOrder {
1136 &self.window.next_frame.z_index_stack
1137 }
1138
1139 /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
1140 pub fn paint_shadows(
1141 &mut self,
1142 bounds: Bounds<Pixels>,
1143 corner_radii: Corners<Pixels>,
1144 shadows: &[BoxShadow],
1145 ) {
1146 let scale_factor = self.scale_factor();
1147 let content_mask = self.content_mask();
1148 let view_id = self.parent_view_id();
1149 let window = &mut *self.window;
1150 for shadow in shadows {
1151 let mut shadow_bounds = bounds;
1152 shadow_bounds.origin += shadow.offset;
1153 shadow_bounds.dilate(shadow.spread_radius);
1154 window.next_frame.scene.insert(
1155 &window.next_frame.z_index_stack,
1156 Shadow {
1157 view_id: view_id.into(),
1158 layer_id: 0,
1159 order: 0,
1160 bounds: shadow_bounds.scale(scale_factor),
1161 content_mask: content_mask.scale(scale_factor),
1162 corner_radii: corner_radii.scale(scale_factor),
1163 color: shadow.color,
1164 blur_radius: shadow.blur_radius.scale(scale_factor),
1165 },
1166 );
1167 }
1168 }
1169
1170 /// Paint one or more quads into the scene for the next frame at the current stacking context.
1171 /// Quads are colored rectangular regions with an optional background, border, and corner radius.
1172 /// see [`fill`], [`outline`], and [`quad`] to construct this type.
1173 pub fn paint_quad(&mut self, quad: PaintQuad) {
1174 let scale_factor = self.scale_factor();
1175 let content_mask = self.content_mask();
1176 let view_id = self.parent_view_id();
1177
1178 let window = &mut *self.window;
1179 window.next_frame.scene.insert(
1180 &window.next_frame.z_index_stack,
1181 Quad {
1182 view_id: view_id.into(),
1183 layer_id: 0,
1184 order: 0,
1185 bounds: quad.bounds.scale(scale_factor),
1186 content_mask: content_mask.scale(scale_factor),
1187 background: quad.background,
1188 border_color: quad.border_color,
1189 corner_radii: quad.corner_radii.scale(scale_factor),
1190 border_widths: quad.border_widths.scale(scale_factor),
1191 },
1192 );
1193 }
1194
1195 /// Paint the given `Path` into the scene for the next frame at the current z-index.
1196 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
1197 let scale_factor = self.scale_factor();
1198 let content_mask = self.content_mask();
1199 let view_id = self.parent_view_id();
1200
1201 path.content_mask = content_mask;
1202 path.color = color.into();
1203 path.view_id = view_id.into();
1204 let window = &mut *self.window;
1205 window
1206 .next_frame
1207 .scene
1208 .insert(&window.next_frame.z_index_stack, path.scale(scale_factor));
1209 }
1210
1211 /// Paint an underline into the scene for the next frame at the current z-index.
1212 pub fn paint_underline(
1213 &mut self,
1214 origin: Point<Pixels>,
1215 width: Pixels,
1216 style: &UnderlineStyle,
1217 ) {
1218 let scale_factor = self.scale_factor();
1219 let height = if style.wavy {
1220 style.thickness * 3.
1221 } else {
1222 style.thickness
1223 };
1224 let bounds = Bounds {
1225 origin,
1226 size: size(width, height),
1227 };
1228 let content_mask = self.content_mask();
1229 let view_id = self.parent_view_id();
1230
1231 let window = &mut *self.window;
1232 window.next_frame.scene.insert(
1233 &window.next_frame.z_index_stack,
1234 Underline {
1235 view_id: view_id.into(),
1236 layer_id: 0,
1237 order: 0,
1238 bounds: bounds.scale(scale_factor),
1239 content_mask: content_mask.scale(scale_factor),
1240 thickness: style.thickness.scale(scale_factor),
1241 color: style.color.unwrap_or_default(),
1242 wavy: style.wavy,
1243 },
1244 );
1245 }
1246
1247 /// Paint a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
1248 /// The y component of the origin is the baseline of the glyph.
1249 pub fn paint_glyph(
1250 &mut self,
1251 origin: Point<Pixels>,
1252 font_id: FontId,
1253 glyph_id: GlyphId,
1254 font_size: Pixels,
1255 color: Hsla,
1256 ) -> Result<()> {
1257 let scale_factor = self.scale_factor();
1258 let glyph_origin = origin.scale(scale_factor);
1259 let subpixel_variant = Point {
1260 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1261 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1262 };
1263 let params = RenderGlyphParams {
1264 font_id,
1265 glyph_id,
1266 font_size,
1267 subpixel_variant,
1268 scale_factor,
1269 is_emoji: false,
1270 };
1271
1272 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
1273 if !raster_bounds.is_zero() {
1274 let tile =
1275 self.window
1276 .sprite_atlas
1277 .get_or_insert_with(¶ms.clone().into(), &mut || {
1278 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
1279 Ok((size, Cow::Owned(bytes)))
1280 })?;
1281 let bounds = Bounds {
1282 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1283 size: tile.bounds.size.map(Into::into),
1284 };
1285 let content_mask = self.content_mask().scale(scale_factor);
1286 let view_id = self.parent_view_id();
1287 let window = &mut *self.window;
1288 window.next_frame.scene.insert(
1289 &window.next_frame.z_index_stack,
1290 MonochromeSprite {
1291 view_id: view_id.into(),
1292 layer_id: 0,
1293 order: 0,
1294 bounds,
1295 content_mask,
1296 color,
1297 tile,
1298 },
1299 );
1300 }
1301 Ok(())
1302 }
1303
1304 /// Paint an emoji glyph into the scene for the next frame at the current z-index.
1305 /// The y component of the origin is the baseline of the glyph.
1306 pub fn paint_emoji(
1307 &mut self,
1308 origin: Point<Pixels>,
1309 font_id: FontId,
1310 glyph_id: GlyphId,
1311 font_size: Pixels,
1312 ) -> Result<()> {
1313 let scale_factor = self.scale_factor();
1314 let glyph_origin = origin.scale(scale_factor);
1315 let params = RenderGlyphParams {
1316 font_id,
1317 glyph_id,
1318 font_size,
1319 // We don't render emojis with subpixel variants.
1320 subpixel_variant: Default::default(),
1321 scale_factor,
1322 is_emoji: true,
1323 };
1324
1325 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
1326 if !raster_bounds.is_zero() {
1327 let tile =
1328 self.window
1329 .sprite_atlas
1330 .get_or_insert_with(¶ms.clone().into(), &mut || {
1331 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
1332 Ok((size, Cow::Owned(bytes)))
1333 })?;
1334 let bounds = Bounds {
1335 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1336 size: tile.bounds.size.map(Into::into),
1337 };
1338 let content_mask = self.content_mask().scale(scale_factor);
1339 let view_id = self.parent_view_id();
1340 let window = &mut *self.window;
1341
1342 window.next_frame.scene.insert(
1343 &window.next_frame.z_index_stack,
1344 PolychromeSprite {
1345 view_id: view_id.into(),
1346 layer_id: 0,
1347 order: 0,
1348 bounds,
1349 corner_radii: Default::default(),
1350 content_mask,
1351 tile,
1352 grayscale: false,
1353 },
1354 );
1355 }
1356 Ok(())
1357 }
1358
1359 /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
1360 pub fn paint_svg(
1361 &mut self,
1362 bounds: Bounds<Pixels>,
1363 path: SharedString,
1364 color: Hsla,
1365 ) -> Result<()> {
1366 let scale_factor = self.scale_factor();
1367 let bounds = bounds.scale(scale_factor);
1368 // Render the SVG at twice the size to get a higher quality result.
1369 let params = RenderSvgParams {
1370 path,
1371 size: bounds
1372 .size
1373 .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
1374 };
1375
1376 let tile =
1377 self.window
1378 .sprite_atlas
1379 .get_or_insert_with(¶ms.clone().into(), &mut || {
1380 let bytes = self.svg_renderer.render(¶ms)?;
1381 Ok((params.size, Cow::Owned(bytes)))
1382 })?;
1383 let content_mask = self.content_mask().scale(scale_factor);
1384 let view_id = self.parent_view_id();
1385
1386 let window = &mut *self.window;
1387 window.next_frame.scene.insert(
1388 &window.next_frame.z_index_stack,
1389 MonochromeSprite {
1390 view_id: view_id.into(),
1391 layer_id: 0,
1392 order: 0,
1393 bounds,
1394 content_mask,
1395 color,
1396 tile,
1397 },
1398 );
1399
1400 Ok(())
1401 }
1402
1403 /// Paint an image into the scene for the next frame at the current z-index.
1404 pub fn paint_image(
1405 &mut self,
1406 bounds: Bounds<Pixels>,
1407 corner_radii: Corners<Pixels>,
1408 data: Arc<ImageData>,
1409 grayscale: bool,
1410 ) -> Result<()> {
1411 let scale_factor = self.scale_factor();
1412 let bounds = bounds.scale(scale_factor);
1413 let params = RenderImageParams { image_id: data.id };
1414
1415 let tile = self
1416 .window
1417 .sprite_atlas
1418 .get_or_insert_with(¶ms.clone().into(), &mut || {
1419 Ok((data.size(), Cow::Borrowed(data.as_bytes())))
1420 })?;
1421 let content_mask = self.content_mask().scale(scale_factor);
1422 let corner_radii = corner_radii.scale(scale_factor);
1423 let view_id = self.parent_view_id();
1424
1425 let window = &mut *self.window;
1426 window.next_frame.scene.insert(
1427 &window.next_frame.z_index_stack,
1428 PolychromeSprite {
1429 view_id: view_id.into(),
1430 layer_id: 0,
1431 order: 0,
1432 bounds,
1433 content_mask,
1434 corner_radii,
1435 tile,
1436 grayscale,
1437 },
1438 );
1439 Ok(())
1440 }
1441
1442 /// Paint a surface into the scene for the next frame at the current z-index.
1443 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
1444 let scale_factor = self.scale_factor();
1445 let bounds = bounds.scale(scale_factor);
1446 let content_mask = self.content_mask().scale(scale_factor);
1447 let view_id = self.parent_view_id();
1448 let window = &mut *self.window;
1449 window.next_frame.scene.insert(
1450 &window.next_frame.z_index_stack,
1451 Surface {
1452 view_id: view_id.into(),
1453 layer_id: 0,
1454 order: 0,
1455 bounds,
1456 content_mask,
1457 image_buffer,
1458 },
1459 );
1460 }
1461
1462 pub(crate) fn reuse_view(&mut self) {
1463 let view_id = self.parent_view_id();
1464 let grafted_view_ids = self
1465 .window
1466 .next_frame
1467 .dispatch_tree
1468 .reuse_view(view_id, &mut self.window.rendered_frame.dispatch_tree);
1469 for view_id in grafted_view_ids {
1470 assert!(self.window.next_frame.reused_views.insert(view_id));
1471
1472 // Reuse the previous input handler requested during painting of the reused view.
1473 if self
1474 .window
1475 .rendered_frame
1476 .requested_input_handler
1477 .as_ref()
1478 .map_or(false, |requested| requested.view_id == view_id)
1479 {
1480 self.window.next_frame.requested_input_handler =
1481 self.window.rendered_frame.requested_input_handler.take();
1482 }
1483
1484 // Reuse the tooltip previously requested during painting of the reused view.
1485 if self
1486 .window
1487 .rendered_frame
1488 .tooltip_request
1489 .as_ref()
1490 .map_or(false, |requested| requested.view_id == view_id)
1491 {
1492 self.window.next_frame.tooltip_request =
1493 self.window.rendered_frame.tooltip_request.take();
1494 }
1495
1496 // Reuse the cursor styles previously requested during painting of the reused view.
1497 if let Some(style) = self.window.rendered_frame.cursor_styles.remove(&view_id) {
1498 self.window.next_frame.cursor_styles.insert(view_id, style);
1499 self.window.next_frame.requested_cursor_style = Some(style);
1500 }
1501 }
1502 }
1503
1504 /// Draw pixels to the display for this window based on the contents of its scene.
1505 pub(crate) fn draw(&mut self) {
1506 self.window.dirty = false;
1507 self.window.drawing = true;
1508
1509 #[cfg(any(test, feature = "test-support"))]
1510 {
1511 self.window.focus_invalidated = false;
1512 }
1513
1514 if let Some(requested_handler) = self.window.rendered_frame.requested_input_handler.as_mut()
1515 {
1516 requested_handler.handler = self.window.platform_window.take_input_handler();
1517 }
1518
1519 let root_view = self.window.root_view.take().unwrap();
1520
1521 self.with_z_index(0, |cx| {
1522 cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| {
1523 for (action_type, action_listeners) in &cx.app.global_action_listeners {
1524 for action_listener in action_listeners.iter().cloned() {
1525 cx.window.next_frame.dispatch_tree.on_action(
1526 *action_type,
1527 Rc::new(move |action: &dyn Any, phase, cx: &mut WindowContext<'_>| {
1528 action_listener(action, phase, cx)
1529 }),
1530 )
1531 }
1532 }
1533
1534 let available_space = cx.window.viewport_size.map(Into::into);
1535 root_view.draw(Point::default(), available_space, cx);
1536 })
1537 });
1538
1539 if let Some(active_drag) = self.app.active_drag.take() {
1540 self.with_z_index(ACTIVE_DRAG_Z_INDEX, |cx| {
1541 let offset = cx.mouse_position() - active_drag.cursor_offset;
1542 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1543 active_drag.view.draw(offset, available_space, cx);
1544 });
1545 self.active_drag = Some(active_drag);
1546 } else if let Some(tooltip_request) = self.window.next_frame.tooltip_request.take() {
1547 self.with_z_index(1, |cx| {
1548 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1549 tooltip_request.tooltip.view.draw(
1550 tooltip_request.tooltip.cursor_offset,
1551 available_space,
1552 cx,
1553 );
1554 });
1555 self.window.next_frame.tooltip_request = Some(tooltip_request);
1556 }
1557 self.window.dirty_views.clear();
1558
1559 self.window
1560 .next_frame
1561 .dispatch_tree
1562 .preserve_pending_keystrokes(
1563 &mut self.window.rendered_frame.dispatch_tree,
1564 self.window.focus,
1565 );
1566 self.window.next_frame.focus = self.window.focus;
1567 self.window.next_frame.window_active = self.window.active;
1568 self.window.root_view = Some(root_view);
1569
1570 // Set the cursor only if we're the active window.
1571 let cursor_style = self
1572 .window
1573 .next_frame
1574 .requested_cursor_style
1575 .take()
1576 .unwrap_or(CursorStyle::Arrow);
1577 if self.is_window_active() {
1578 self.platform.set_cursor_style(cursor_style);
1579 }
1580
1581 // Register requested input handler with the platform window.
1582 if let Some(requested_input) = self.window.next_frame.requested_input_handler.as_mut() {
1583 if let Some(handler) = requested_input.handler.take() {
1584 self.window.platform_window.set_input_handler(handler);
1585 }
1586 }
1587
1588 self.window.layout_engine.as_mut().unwrap().clear();
1589 self.text_system()
1590 .finish_frame(&self.window.next_frame.reused_views);
1591 self.window
1592 .next_frame
1593 .finish(&mut self.window.rendered_frame);
1594 ELEMENT_ARENA.with_borrow_mut(|element_arena| element_arena.clear());
1595
1596 let previous_focus_path = self.window.rendered_frame.focus_path();
1597 let previous_window_active = self.window.rendered_frame.window_active;
1598 mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1599 self.window.next_frame.clear();
1600 let current_focus_path = self.window.rendered_frame.focus_path();
1601 let current_window_active = self.window.rendered_frame.window_active;
1602
1603 if previous_focus_path != current_focus_path
1604 || previous_window_active != current_window_active
1605 {
1606 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1607 self.window
1608 .focus_lost_listeners
1609 .clone()
1610 .retain(&(), |listener| listener(self));
1611 }
1612
1613 let event = FocusEvent {
1614 previous_focus_path: if previous_window_active {
1615 previous_focus_path
1616 } else {
1617 Default::default()
1618 },
1619 current_focus_path: if current_window_active {
1620 current_focus_path
1621 } else {
1622 Default::default()
1623 },
1624 };
1625 self.window
1626 .focus_listeners
1627 .clone()
1628 .retain(&(), |listener| listener(&event, self));
1629 }
1630
1631 self.window
1632 .platform_window
1633 .draw(&self.window.rendered_frame.scene);
1634 self.window.refreshing = false;
1635 self.window.drawing = false;
1636 }
1637
1638 /// Dispatch a mouse or keyboard event on the window.
1639 pub fn dispatch_event(&mut self, event: PlatformInput) -> bool {
1640 // Handlers may set this to false by calling `stop_propagation`.
1641 self.app.propagate_event = true;
1642 // Handlers may set this to true by calling `prevent_default`.
1643 self.window.default_prevented = false;
1644
1645 let event = match event {
1646 // Track the mouse position with our own state, since accessing the platform
1647 // API for the mouse position can only occur on the main thread.
1648 PlatformInput::MouseMove(mouse_move) => {
1649 self.window.mouse_position = mouse_move.position;
1650 self.window.modifiers = mouse_move.modifiers;
1651 PlatformInput::MouseMove(mouse_move)
1652 }
1653 PlatformInput::MouseDown(mouse_down) => {
1654 self.window.mouse_position = mouse_down.position;
1655 self.window.modifiers = mouse_down.modifiers;
1656 PlatformInput::MouseDown(mouse_down)
1657 }
1658 PlatformInput::MouseUp(mouse_up) => {
1659 self.window.mouse_position = mouse_up.position;
1660 self.window.modifiers = mouse_up.modifiers;
1661 PlatformInput::MouseUp(mouse_up)
1662 }
1663 PlatformInput::MouseExited(mouse_exited) => {
1664 self.window.modifiers = mouse_exited.modifiers;
1665 PlatformInput::MouseExited(mouse_exited)
1666 }
1667 PlatformInput::ModifiersChanged(modifiers_changed) => {
1668 self.window.modifiers = modifiers_changed.modifiers;
1669 PlatformInput::ModifiersChanged(modifiers_changed)
1670 }
1671 PlatformInput::ScrollWheel(scroll_wheel) => {
1672 self.window.mouse_position = scroll_wheel.position;
1673 self.window.modifiers = scroll_wheel.modifiers;
1674 PlatformInput::ScrollWheel(scroll_wheel)
1675 }
1676 // Translate dragging and dropping of external files from the operating system
1677 // to internal drag and drop events.
1678 PlatformInput::FileDrop(file_drop) => match file_drop {
1679 FileDropEvent::Entered { position, paths } => {
1680 self.window.mouse_position = position;
1681 if self.active_drag.is_none() {
1682 self.active_drag = Some(AnyDrag {
1683 value: Box::new(paths.clone()),
1684 view: self.new_view(|_| paths).into(),
1685 cursor_offset: position,
1686 });
1687 }
1688 PlatformInput::MouseMove(MouseMoveEvent {
1689 position,
1690 pressed_button: Some(MouseButton::Left),
1691 modifiers: Modifiers::default(),
1692 })
1693 }
1694 FileDropEvent::Pending { position } => {
1695 self.window.mouse_position = position;
1696 PlatformInput::MouseMove(MouseMoveEvent {
1697 position,
1698 pressed_button: Some(MouseButton::Left),
1699 modifiers: Modifiers::default(),
1700 })
1701 }
1702 FileDropEvent::Submit { position } => {
1703 self.activate(true);
1704 self.window.mouse_position = position;
1705 PlatformInput::MouseUp(MouseUpEvent {
1706 button: MouseButton::Left,
1707 position,
1708 modifiers: Modifiers::default(),
1709 click_count: 1,
1710 })
1711 }
1712 FileDropEvent::Exited => PlatformInput::MouseUp(MouseUpEvent {
1713 button: MouseButton::Left,
1714 position: Point::default(),
1715 modifiers: Modifiers::default(),
1716 click_count: 1,
1717 }),
1718 },
1719 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
1720 };
1721
1722 if let Some(any_mouse_event) = event.mouse_event() {
1723 self.dispatch_mouse_event(any_mouse_event);
1724 } else if let Some(any_key_event) = event.keyboard_event() {
1725 self.dispatch_key_event(any_key_event);
1726 }
1727
1728 !self.app.propagate_event
1729 }
1730
1731 fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1732 if let Some(mut handlers) = self
1733 .window
1734 .rendered_frame
1735 .mouse_listeners
1736 .remove(&event.type_id())
1737 {
1738 // Because handlers may add other handlers, we sort every time.
1739 handlers.sort_by(|(a, _, _), (b, _, _)| a.cmp(b));
1740
1741 // Capture phase, events bubble from back to front. Handlers for this phase are used for
1742 // special purposes, such as detecting events outside of a given Bounds.
1743 for (_, _, handler) in &mut handlers {
1744 handler(event, DispatchPhase::Capture, self);
1745 if !self.app.propagate_event {
1746 break;
1747 }
1748 }
1749
1750 // Bubble phase, where most normal handlers do their work.
1751 if self.app.propagate_event {
1752 for (_, _, handler) in handlers.iter_mut().rev() {
1753 handler(event, DispatchPhase::Bubble, self);
1754 if !self.app.propagate_event {
1755 break;
1756 }
1757 }
1758 }
1759
1760 self.window
1761 .rendered_frame
1762 .mouse_listeners
1763 .insert(event.type_id(), handlers);
1764 }
1765
1766 if self.app.propagate_event && self.has_active_drag() {
1767 if event.is::<MouseMoveEvent>() {
1768 // If this was a mouse move event, redraw the window so that the
1769 // active drag can follow the mouse cursor.
1770 self.refresh();
1771 } else if event.is::<MouseUpEvent>() {
1772 // If this was a mouse up event, cancel the active drag and redraw
1773 // the window.
1774 self.active_drag = None;
1775 self.refresh();
1776 }
1777 }
1778 }
1779
1780 fn dispatch_key_event(&mut self, event: &dyn Any) {
1781 let node_id = self
1782 .window
1783 .focus
1784 .and_then(|focus_id| {
1785 self.window
1786 .rendered_frame
1787 .dispatch_tree
1788 .focusable_node_id(focus_id)
1789 })
1790 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1791
1792 let dispatch_path = self
1793 .window
1794 .rendered_frame
1795 .dispatch_tree
1796 .dispatch_path(node_id);
1797
1798 if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1799 let KeymatchResult { actions, pending } = self
1800 .window
1801 .rendered_frame
1802 .dispatch_tree
1803 .dispatch_key(&key_down_event.keystroke, &dispatch_path);
1804
1805 if pending {
1806 let mut currently_pending = self.window.pending_input.take().unwrap_or_default();
1807 if currently_pending.focus.is_some() && currently_pending.focus != self.window.focus
1808 {
1809 currently_pending = PendingInput::default();
1810 }
1811 currently_pending.focus = self.window.focus;
1812 if let Some(new_text) = &key_down_event.keystroke.ime_key.as_ref() {
1813 currently_pending.text += new_text
1814 }
1815 for action in actions {
1816 currently_pending.actions.push(action);
1817 }
1818
1819 currently_pending.timer = Some(self.spawn(|mut cx| async move {
1820 cx.background_executor.timer(Duration::from_secs(1)).await;
1821 cx.update(move |cx| {
1822 cx.clear_pending_keystrokes();
1823 let Some(currently_pending) = cx.window.pending_input.take() else {
1824 return;
1825 };
1826 cx.replay_pending_input(currently_pending)
1827 })
1828 .log_err();
1829 }));
1830 self.window.pending_input = Some(currently_pending);
1831
1832 self.propagate_event = false;
1833 return;
1834 } else if let Some(currently_pending) = self.window.pending_input.take() {
1835 if actions.is_empty() {
1836 self.replay_pending_input(currently_pending)
1837 }
1838 }
1839
1840 if !actions.is_empty() {
1841 self.clear_pending_keystrokes();
1842 }
1843
1844 self.propagate_event = true;
1845 for action in actions {
1846 self.dispatch_action_on_node(node_id, action.boxed_clone());
1847 if !self.propagate_event {
1848 self.dispatch_keystroke_observers(event, Some(action));
1849 return;
1850 }
1851 }
1852 }
1853
1854 // Capture phase
1855 for node_id in &dispatch_path {
1856 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1857
1858 for key_listener in node.key_listeners.clone() {
1859 key_listener(event, DispatchPhase::Capture, self);
1860 if !self.propagate_event {
1861 return;
1862 }
1863 }
1864 }
1865
1866 // Bubble phase
1867 for node_id in dispatch_path.iter().rev() {
1868 // Handle low level key events
1869 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1870 for key_listener in node.key_listeners.clone() {
1871 key_listener(event, DispatchPhase::Bubble, self);
1872 if !self.propagate_event {
1873 return;
1874 }
1875 }
1876 }
1877
1878 self.dispatch_keystroke_observers(event, None);
1879 }
1880
1881 /// Determine whether a potential multi-stroke key binding is in progress on this window.
1882 pub fn has_pending_keystrokes(&self) -> bool {
1883 self.window
1884 .rendered_frame
1885 .dispatch_tree
1886 .has_pending_keystrokes()
1887 }
1888
1889 fn replay_pending_input(&mut self, currently_pending: PendingInput) {
1890 let node_id = self
1891 .window
1892 .focus
1893 .and_then(|focus_id| {
1894 self.window
1895 .rendered_frame
1896 .dispatch_tree
1897 .focusable_node_id(focus_id)
1898 })
1899 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1900
1901 if self.window.focus != currently_pending.focus {
1902 return;
1903 }
1904
1905 self.propagate_event = true;
1906 for action in currently_pending.actions {
1907 self.dispatch_action_on_node(node_id, action);
1908 if !self.propagate_event {
1909 return;
1910 }
1911 }
1912
1913 if !currently_pending.text.is_empty() {
1914 if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
1915 input_handler.flush_pending_input(¤tly_pending.text, self);
1916 self.window.platform_window.set_input_handler(input_handler)
1917 }
1918 }
1919 }
1920
1921 fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1922 let dispatch_path = self
1923 .window
1924 .rendered_frame
1925 .dispatch_tree
1926 .dispatch_path(node_id);
1927
1928 // Capture phase
1929 for node_id in &dispatch_path {
1930 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1931 for DispatchActionListener {
1932 action_type,
1933 listener,
1934 } in node.action_listeners.clone()
1935 {
1936 let any_action = action.as_any();
1937 if action_type == any_action.type_id() {
1938 listener(any_action, DispatchPhase::Capture, self);
1939 if !self.propagate_event {
1940 return;
1941 }
1942 }
1943 }
1944 }
1945 // Bubble phase
1946 for node_id in dispatch_path.iter().rev() {
1947 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1948 for DispatchActionListener {
1949 action_type,
1950 listener,
1951 } in node.action_listeners.clone()
1952 {
1953 let any_action = action.as_any();
1954 if action_type == any_action.type_id() {
1955 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1956 listener(any_action, DispatchPhase::Bubble, self);
1957 if !self.propagate_event {
1958 return;
1959 }
1960 }
1961 }
1962 }
1963 }
1964
1965 /// Register the given handler to be invoked whenever the global of the given type
1966 /// is updated.
1967 pub fn observe_global<G: 'static>(
1968 &mut self,
1969 f: impl Fn(&mut WindowContext<'_>) + 'static,
1970 ) -> Subscription {
1971 let window_handle = self.window.handle;
1972 let (subscription, activate) = self.global_observers.insert(
1973 TypeId::of::<G>(),
1974 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1975 );
1976 self.app.defer(move |_| activate());
1977 subscription
1978 }
1979
1980 /// Focus the current window and bring it to the foreground at the platform level.
1981 pub fn activate_window(&self) {
1982 self.window.platform_window.activate();
1983 }
1984
1985 /// Minimize the current window at the platform level.
1986 pub fn minimize_window(&self) {
1987 self.window.platform_window.minimize();
1988 }
1989
1990 /// Toggle full screen status on the current window at the platform level.
1991 pub fn toggle_full_screen(&self) {
1992 self.window.platform_window.toggle_full_screen();
1993 }
1994
1995 /// Present a platform dialog.
1996 /// The provided message will be presented, along with buttons for each answer.
1997 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
1998 pub fn prompt(
1999 &self,
2000 level: PromptLevel,
2001 message: &str,
2002 answers: &[&str],
2003 ) -> oneshot::Receiver<usize> {
2004 self.window.platform_window.prompt(level, message, answers)
2005 }
2006
2007 /// Returns all available actions for the focused element.
2008 pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
2009 let node_id = self
2010 .window
2011 .focus
2012 .and_then(|focus_id| {
2013 self.window
2014 .rendered_frame
2015 .dispatch_tree
2016 .focusable_node_id(focus_id)
2017 })
2018 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
2019
2020 self.window
2021 .rendered_frame
2022 .dispatch_tree
2023 .available_actions(node_id)
2024 }
2025
2026 /// Returns key bindings that invoke the given action on the currently focused element.
2027 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
2028 self.window
2029 .rendered_frame
2030 .dispatch_tree
2031 .bindings_for_action(
2032 action,
2033 &self.window.rendered_frame.dispatch_tree.context_stack,
2034 )
2035 }
2036
2037 /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
2038 pub fn bindings_for_action_in(
2039 &self,
2040 action: &dyn Action,
2041 focus_handle: &FocusHandle,
2042 ) -> Vec<KeyBinding> {
2043 let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
2044
2045 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
2046 return vec![];
2047 };
2048 let context_stack = dispatch_tree
2049 .dispatch_path(node_id)
2050 .into_iter()
2051 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
2052 .collect();
2053 dispatch_tree.bindings_for_action(action, &context_stack)
2054 }
2055
2056 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
2057 pub fn listener_for<V: Render, E>(
2058 &self,
2059 view: &View<V>,
2060 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2061 ) -> impl Fn(&E, &mut WindowContext) + 'static {
2062 let view = view.downgrade();
2063 move |e: &E, cx: &mut WindowContext| {
2064 view.update(cx, |view, cx| f(view, e, cx)).ok();
2065 }
2066 }
2067
2068 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
2069 pub fn handler_for<V: Render>(
2070 &self,
2071 view: &View<V>,
2072 f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
2073 ) -> impl Fn(&mut WindowContext) {
2074 let view = view.downgrade();
2075 move |cx: &mut WindowContext| {
2076 view.update(cx, |view, cx| f(view, cx)).ok();
2077 }
2078 }
2079
2080 /// Invoke the given function with the given focus handle present on the key dispatch stack.
2081 /// If you want an element to participate in key dispatch, use this method to push its key context and focus handle into the stack during paint.
2082 pub fn with_key_dispatch<R>(
2083 &mut self,
2084 context: Option<KeyContext>,
2085 focus_handle: Option<FocusHandle>,
2086 f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
2087 ) -> R {
2088 let window = &mut self.window;
2089 let focus_id = focus_handle.as_ref().map(|handle| handle.id);
2090 window
2091 .next_frame
2092 .dispatch_tree
2093 .push_node(context.clone(), focus_id, None);
2094
2095 let result = f(focus_handle, self);
2096
2097 self.window.next_frame.dispatch_tree.pop_node();
2098
2099 result
2100 }
2101
2102 /// Invoke the given function with the given view id present on the view stack.
2103 /// This is a fairly low-level method used to layout views.
2104 pub fn with_view_id<R>(&mut self, view_id: EntityId, f: impl FnOnce(&mut Self) -> R) -> R {
2105 let text_system = self.text_system().clone();
2106 text_system.with_view(view_id, || {
2107 if self.window.next_frame.view_stack.last() == Some(&view_id) {
2108 return f(self);
2109 } else {
2110 self.window.next_frame.view_stack.push(view_id);
2111 let result = f(self);
2112 self.window.next_frame.view_stack.pop();
2113 result
2114 }
2115 })
2116 }
2117
2118 /// Invoke the given function with the given view id present on the view stack.
2119 /// This is a fairly low-level method used to paint views.
2120 pub fn paint_view<R>(&mut self, view_id: EntityId, f: impl FnOnce(&mut Self) -> R) -> R {
2121 let text_system = self.text_system().clone();
2122 text_system.with_view(view_id, || {
2123 if self.window.next_frame.view_stack.last() == Some(&view_id) {
2124 return f(self);
2125 } else {
2126 self.window.next_frame.view_stack.push(view_id);
2127 self.window
2128 .next_frame
2129 .dispatch_tree
2130 .push_node(None, None, Some(view_id));
2131 let result = f(self);
2132 self.window.next_frame.dispatch_tree.pop_node();
2133 self.window.next_frame.view_stack.pop();
2134 result
2135 }
2136 })
2137 }
2138
2139 /// Updates or initializes state for an element with the given id that lives across multiple
2140 /// frames. If an element with this ID existed in the rendered frame, its state will be passed
2141 /// to the given closure. The state returned by the closure will be stored so it can be referenced
2142 /// when drawing the next frame.
2143 pub(crate) fn with_element_state<S, R>(
2144 &mut self,
2145 id: ElementId,
2146 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2147 ) -> R
2148 where
2149 S: 'static,
2150 {
2151 self.with_element_id(Some(id), |cx| {
2152 let global_id = cx.window().element_id_stack.clone();
2153
2154 if let Some(any) = cx
2155 .window_mut()
2156 .next_frame
2157 .element_states
2158 .remove(&global_id)
2159 .or_else(|| {
2160 cx.window_mut()
2161 .rendered_frame
2162 .element_states
2163 .remove(&global_id)
2164 })
2165 {
2166 let ElementStateBox {
2167 inner,
2168 parent_view_id,
2169 #[cfg(debug_assertions)]
2170 type_name
2171 } = any;
2172 // Using the extra inner option to avoid needing to reallocate a new box.
2173 let mut state_box = inner
2174 .downcast::<Option<S>>()
2175 .map_err(|_| {
2176 #[cfg(debug_assertions)]
2177 {
2178 anyhow!(
2179 "invalid element state type for id, requested_type {:?}, actual type: {:?}",
2180 std::any::type_name::<S>(),
2181 type_name
2182 )
2183 }
2184
2185 #[cfg(not(debug_assertions))]
2186 {
2187 anyhow!(
2188 "invalid element state type for id, requested_type {:?}",
2189 std::any::type_name::<S>(),
2190 )
2191 }
2192 })
2193 .unwrap();
2194
2195 // Actual: Option<AnyElement> <- View
2196 // Requested: () <- AnyElement
2197 let state = state_box
2198 .take()
2199 .expect("element state is already on the stack");
2200 let (result, state) = f(Some(state), cx);
2201 state_box.replace(state);
2202 cx.window_mut()
2203 .next_frame
2204 .element_states
2205 .insert(global_id, ElementStateBox {
2206 inner: state_box,
2207 parent_view_id,
2208 #[cfg(debug_assertions)]
2209 type_name
2210 });
2211 result
2212 } else {
2213 let (result, state) = f(None, cx);
2214 let parent_view_id = cx.parent_view_id();
2215 cx.window_mut()
2216 .next_frame
2217 .element_states
2218 .insert(global_id,
2219 ElementStateBox {
2220 inner: Box::new(Some(state)),
2221 parent_view_id,
2222 #[cfg(debug_assertions)]
2223 type_name: std::any::type_name::<S>()
2224 }
2225
2226 );
2227 result
2228 }
2229 })
2230 }
2231
2232 fn parent_view_id(&self) -> EntityId {
2233 *self
2234 .window
2235 .next_frame
2236 .view_stack
2237 .last()
2238 .expect("a view should always be on the stack while drawing")
2239 }
2240
2241 /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
2242 /// platform to receive textual input with proper integration with concerns such
2243 /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
2244 /// rendered.
2245 ///
2246 /// [element_input_handler]: crate::ElementInputHandler
2247 pub fn handle_input(&mut self, focus_handle: &FocusHandle, input_handler: impl InputHandler) {
2248 if focus_handle.is_focused(self) {
2249 let view_id = self.parent_view_id();
2250 self.window.next_frame.requested_input_handler = Some(RequestedInputHandler {
2251 view_id,
2252 handler: Some(PlatformInputHandler::new(
2253 self.to_async(),
2254 Box::new(input_handler),
2255 )),
2256 })
2257 }
2258 }
2259
2260 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
2261 /// If the callback returns false, the window won't be closed.
2262 pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
2263 let mut this = self.to_async();
2264 self.window
2265 .platform_window
2266 .on_should_close(Box::new(move || {
2267 this.update(|cx| {
2268 // Ensure that the window is removed from the app if it's been closed
2269 // by always pre-empting the system close event.
2270 if f(cx) {
2271 cx.remove_window();
2272 }
2273 false
2274 })
2275 .unwrap_or(true)
2276 }))
2277 }
2278}
2279
2280impl Context for WindowContext<'_> {
2281 type Result<T> = T;
2282
2283 fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
2284 where
2285 T: 'static,
2286 {
2287 let slot = self.app.entities.reserve();
2288 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
2289 self.entities.insert(slot, model)
2290 }
2291
2292 fn update_model<T: 'static, R>(
2293 &mut self,
2294 model: &Model<T>,
2295 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2296 ) -> R {
2297 let mut entity = self.entities.lease(model);
2298 let result = update(
2299 &mut *entity,
2300 &mut ModelContext::new(&mut *self.app, model.downgrade()),
2301 );
2302 self.entities.end_lease(entity);
2303 result
2304 }
2305
2306 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2307 where
2308 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2309 {
2310 if window == self.window.handle {
2311 let root_view = self.window.root_view.clone().unwrap();
2312 Ok(update(root_view, self))
2313 } else {
2314 window.update(self.app, update)
2315 }
2316 }
2317
2318 fn read_model<T, R>(
2319 &self,
2320 handle: &Model<T>,
2321 read: impl FnOnce(&T, &AppContext) -> R,
2322 ) -> Self::Result<R>
2323 where
2324 T: 'static,
2325 {
2326 let entity = self.entities.read(handle);
2327 read(entity, &*self.app)
2328 }
2329
2330 fn read_window<T, R>(
2331 &self,
2332 window: &WindowHandle<T>,
2333 read: impl FnOnce(View<T>, &AppContext) -> R,
2334 ) -> Result<R>
2335 where
2336 T: 'static,
2337 {
2338 if window.any_handle == self.window.handle {
2339 let root_view = self
2340 .window
2341 .root_view
2342 .clone()
2343 .unwrap()
2344 .downcast::<T>()
2345 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2346 Ok(read(root_view, self))
2347 } else {
2348 self.app.read_window(window, read)
2349 }
2350 }
2351}
2352
2353impl VisualContext for WindowContext<'_> {
2354 fn new_view<V>(
2355 &mut self,
2356 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
2357 ) -> Self::Result<View<V>>
2358 where
2359 V: 'static + Render,
2360 {
2361 let slot = self.app.entities.reserve();
2362 let view = View {
2363 model: slot.clone(),
2364 };
2365 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
2366 let entity = build_view_state(&mut cx);
2367 cx.entities.insert(slot, entity);
2368
2369 cx.new_view_observers
2370 .clone()
2371 .retain(&TypeId::of::<V>(), |observer| {
2372 let any_view = AnyView::from(view.clone());
2373 (observer)(any_view, self);
2374 true
2375 });
2376
2377 view
2378 }
2379
2380 /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
2381 fn update_view<T: 'static, R>(
2382 &mut self,
2383 view: &View<T>,
2384 update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
2385 ) -> Self::Result<R> {
2386 let mut lease = self.app.entities.lease(&view.model);
2387 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
2388 let result = update(&mut *lease, &mut cx);
2389 cx.app.entities.end_lease(lease);
2390 result
2391 }
2392
2393 fn replace_root_view<V>(
2394 &mut self,
2395 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
2396 ) -> Self::Result<View<V>>
2397 where
2398 V: 'static + Render,
2399 {
2400 let view = self.new_view(build_view);
2401 self.window.root_view = Some(view.clone().into());
2402 self.refresh();
2403 view
2404 }
2405
2406 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
2407 self.update_view(view, |view, cx| {
2408 view.focus_handle(cx).clone().focus(cx);
2409 })
2410 }
2411
2412 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
2413 where
2414 V: ManagedView,
2415 {
2416 self.update_view(view, |_, cx| cx.emit(DismissEvent))
2417 }
2418}
2419
2420impl<'a> std::ops::Deref for WindowContext<'a> {
2421 type Target = AppContext;
2422
2423 fn deref(&self) -> &Self::Target {
2424 self.app
2425 }
2426}
2427
2428impl<'a> std::ops::DerefMut for WindowContext<'a> {
2429 fn deref_mut(&mut self) -> &mut Self::Target {
2430 self.app
2431 }
2432}
2433
2434impl<'a> Borrow<AppContext> for WindowContext<'a> {
2435 fn borrow(&self) -> &AppContext {
2436 self.app
2437 }
2438}
2439
2440impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
2441 fn borrow_mut(&mut self) -> &mut AppContext {
2442 self.app
2443 }
2444}
2445
2446/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
2447pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
2448 #[doc(hidden)]
2449 fn app_mut(&mut self) -> &mut AppContext {
2450 self.borrow_mut()
2451 }
2452
2453 #[doc(hidden)]
2454 fn app(&self) -> &AppContext {
2455 self.borrow()
2456 }
2457
2458 #[doc(hidden)]
2459 fn window(&self) -> &Window {
2460 self.borrow()
2461 }
2462
2463 #[doc(hidden)]
2464 fn window_mut(&mut self) -> &mut Window {
2465 self.borrow_mut()
2466 }
2467
2468 /// Pushes the given element id onto the global stack and invokes the given closure
2469 /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
2470 /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
2471 /// used to associate state with identified elements across separate frames.
2472 fn with_element_id<R>(
2473 &mut self,
2474 id: Option<impl Into<ElementId>>,
2475 f: impl FnOnce(&mut Self) -> R,
2476 ) -> R {
2477 if let Some(id) = id.map(Into::into) {
2478 let window = self.window_mut();
2479 window.element_id_stack.push(id);
2480 let result = f(self);
2481 let window: &mut Window = self.borrow_mut();
2482 window.element_id_stack.pop();
2483 result
2484 } else {
2485 f(self)
2486 }
2487 }
2488
2489 /// Invoke the given function with the given content mask after intersecting it
2490 /// with the current mask.
2491 fn with_content_mask<R>(
2492 &mut self,
2493 mask: Option<ContentMask<Pixels>>,
2494 f: impl FnOnce(&mut Self) -> R,
2495 ) -> R {
2496 if let Some(mask) = mask {
2497 let mask = mask.intersect(&self.content_mask());
2498 self.window_mut().next_frame.content_mask_stack.push(mask);
2499 let result = f(self);
2500 self.window_mut().next_frame.content_mask_stack.pop();
2501 result
2502 } else {
2503 f(self)
2504 }
2505 }
2506
2507 /// Invoke the given function with the content mask reset to that
2508 /// of the window.
2509 fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
2510 let mask = ContentMask {
2511 bounds: Bounds {
2512 origin: Point::default(),
2513 size: self.window().viewport_size,
2514 },
2515 };
2516 let new_stacking_order_id =
2517 post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
2518 let new_root_z_index = post_inc(&mut self.window_mut().next_frame.next_root_z_index);
2519 let old_stacking_order = mem::take(&mut self.window_mut().next_frame.z_index_stack);
2520 self.window_mut().next_frame.z_index_stack.id = new_stacking_order_id;
2521 self.window_mut()
2522 .next_frame
2523 .z_index_stack
2524 .push(new_root_z_index);
2525 self.window_mut().next_frame.content_mask_stack.push(mask);
2526 let result = f(self);
2527 self.window_mut().next_frame.content_mask_stack.pop();
2528 self.window_mut().next_frame.z_index_stack = old_stacking_order;
2529 result
2530 }
2531
2532 /// Called during painting to invoke the given closure in a new stacking context. The given
2533 /// z-index is interpreted relative to the previous call to `stack`.
2534 fn with_z_index<R>(&mut self, z_index: u8, f: impl FnOnce(&mut Self) -> R) -> R {
2535 let new_stacking_order_id =
2536 post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
2537 let old_stacking_order_id = mem::replace(
2538 &mut self.window_mut().next_frame.z_index_stack.id,
2539 new_stacking_order_id,
2540 );
2541 self.window_mut().next_frame.z_index_stack.id = new_stacking_order_id;
2542 self.window_mut().next_frame.z_index_stack.push(z_index);
2543 let result = f(self);
2544 self.window_mut().next_frame.z_index_stack.id = old_stacking_order_id;
2545 self.window_mut().next_frame.z_index_stack.pop();
2546 result
2547 }
2548
2549 /// Updates the global element offset relative to the current offset. This is used to implement
2550 /// scrolling.
2551 fn with_element_offset<R>(
2552 &mut self,
2553 offset: Point<Pixels>,
2554 f: impl FnOnce(&mut Self) -> R,
2555 ) -> R {
2556 if offset.is_zero() {
2557 return f(self);
2558 };
2559
2560 let abs_offset = self.element_offset() + offset;
2561 self.with_absolute_element_offset(abs_offset, f)
2562 }
2563
2564 /// Updates the global element offset based on the given offset. This is used to implement
2565 /// drag handles and other manual painting of elements.
2566 fn with_absolute_element_offset<R>(
2567 &mut self,
2568 offset: Point<Pixels>,
2569 f: impl FnOnce(&mut Self) -> R,
2570 ) -> R {
2571 self.window_mut()
2572 .next_frame
2573 .element_offset_stack
2574 .push(offset);
2575 let result = f(self);
2576 self.window_mut().next_frame.element_offset_stack.pop();
2577 result
2578 }
2579
2580 /// Obtain the current element offset.
2581 fn element_offset(&self) -> Point<Pixels> {
2582 self.window()
2583 .next_frame
2584 .element_offset_stack
2585 .last()
2586 .copied()
2587 .unwrap_or_default()
2588 }
2589
2590 /// Obtain the current content mask.
2591 fn content_mask(&self) -> ContentMask<Pixels> {
2592 self.window()
2593 .next_frame
2594 .content_mask_stack
2595 .last()
2596 .cloned()
2597 .unwrap_or_else(|| ContentMask {
2598 bounds: Bounds {
2599 origin: Point::default(),
2600 size: self.window().viewport_size,
2601 },
2602 })
2603 }
2604
2605 /// The size of an em for the base font of the application. Adjusting this value allows the
2606 /// UI to scale, just like zooming a web page.
2607 fn rem_size(&self) -> Pixels {
2608 self.window().rem_size
2609 }
2610}
2611
2612impl Borrow<Window> for WindowContext<'_> {
2613 fn borrow(&self) -> &Window {
2614 self.window
2615 }
2616}
2617
2618impl BorrowMut<Window> for WindowContext<'_> {
2619 fn borrow_mut(&mut self) -> &mut Window {
2620 self.window
2621 }
2622}
2623
2624impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2625
2626/// Provides access to application state that is specialized for a particular [`View`].
2627/// Allows you to interact with focus, emit events, etc.
2628/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
2629/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
2630pub struct ViewContext<'a, V> {
2631 window_cx: WindowContext<'a>,
2632 view: &'a View<V>,
2633}
2634
2635impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2636 fn borrow(&self) -> &AppContext {
2637 &*self.window_cx.app
2638 }
2639}
2640
2641impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2642 fn borrow_mut(&mut self) -> &mut AppContext {
2643 &mut *self.window_cx.app
2644 }
2645}
2646
2647impl<V> Borrow<Window> for ViewContext<'_, V> {
2648 fn borrow(&self) -> &Window {
2649 &*self.window_cx.window
2650 }
2651}
2652
2653impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2654 fn borrow_mut(&mut self) -> &mut Window {
2655 &mut *self.window_cx.window
2656 }
2657}
2658
2659impl<'a, V: 'static> ViewContext<'a, V> {
2660 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2661 Self {
2662 window_cx: WindowContext::new(app, window),
2663 view,
2664 }
2665 }
2666
2667 /// Get the entity_id of this view.
2668 pub fn entity_id(&self) -> EntityId {
2669 self.view.entity_id()
2670 }
2671
2672 /// Get the view pointer underlying this context.
2673 pub fn view(&self) -> &View<V> {
2674 self.view
2675 }
2676
2677 /// Get the model underlying this view.
2678 pub fn model(&self) -> &Model<V> {
2679 &self.view.model
2680 }
2681
2682 /// Access the underlying window context.
2683 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2684 &mut self.window_cx
2685 }
2686
2687 /// Sets a given callback to be run on the next frame.
2688 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2689 where
2690 V: 'static,
2691 {
2692 let view = self.view().clone();
2693 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2694 }
2695
2696 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2697 /// that are currently on the stack to be returned to the app.
2698 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2699 let view = self.view().downgrade();
2700 self.window_cx.defer(move |cx| {
2701 view.update(cx, f).ok();
2702 });
2703 }
2704
2705 /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
2706 pub fn observe<V2, E>(
2707 &mut self,
2708 entity: &E,
2709 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2710 ) -> Subscription
2711 where
2712 V2: 'static,
2713 V: 'static,
2714 E: Entity<V2>,
2715 {
2716 let view = self.view().downgrade();
2717 let entity_id = entity.entity_id();
2718 let entity = entity.downgrade();
2719 let window_handle = self.window.handle;
2720 let (subscription, activate) = self.app.observers.insert(
2721 entity_id,
2722 Box::new(move |cx| {
2723 window_handle
2724 .update(cx, |_, cx| {
2725 if let Some(handle) = E::upgrade_from(&entity) {
2726 view.update(cx, |this, cx| on_notify(this, handle, cx))
2727 .is_ok()
2728 } else {
2729 false
2730 }
2731 })
2732 .unwrap_or(false)
2733 }),
2734 );
2735 self.app.defer(move |_| activate());
2736 subscription
2737 }
2738
2739 /// Subscribe to events emitted by another model or view.
2740 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
2741 /// 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.
2742 pub fn subscribe<V2, E, Evt>(
2743 &mut self,
2744 entity: &E,
2745 mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2746 ) -> Subscription
2747 where
2748 V2: EventEmitter<Evt>,
2749 E: Entity<V2>,
2750 Evt: 'static,
2751 {
2752 let view = self.view().downgrade();
2753 let entity_id = entity.entity_id();
2754 let handle = entity.downgrade();
2755 let window_handle = self.window.handle;
2756 let (subscription, activate) = self.app.event_listeners.insert(
2757 entity_id,
2758 (
2759 TypeId::of::<Evt>(),
2760 Box::new(move |event, cx| {
2761 window_handle
2762 .update(cx, |_, cx| {
2763 if let Some(handle) = E::upgrade_from(&handle) {
2764 let event = event.downcast_ref().expect("invalid event type");
2765 view.update(cx, |this, cx| on_event(this, handle, event, cx))
2766 .is_ok()
2767 } else {
2768 false
2769 }
2770 })
2771 .unwrap_or(false)
2772 }),
2773 ),
2774 );
2775 self.app.defer(move |_| activate());
2776 subscription
2777 }
2778
2779 /// Register a callback to be invoked when the view is released.
2780 ///
2781 /// The callback receives a handle to the view's window. This handle may be
2782 /// invalid, if the window was closed before the view was released.
2783 pub fn on_release(
2784 &mut self,
2785 on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
2786 ) -> Subscription {
2787 let window_handle = self.window.handle;
2788 let (subscription, activate) = self.app.release_listeners.insert(
2789 self.view.model.entity_id,
2790 Box::new(move |this, cx| {
2791 let this = this.downcast_mut().expect("invalid entity type");
2792 on_release(this, window_handle, cx)
2793 }),
2794 );
2795 activate();
2796 subscription
2797 }
2798
2799 /// Register a callback to be invoked when the given Model or View is released.
2800 pub fn observe_release<V2, E>(
2801 &mut self,
2802 entity: &E,
2803 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2804 ) -> Subscription
2805 where
2806 V: 'static,
2807 V2: 'static,
2808 E: Entity<V2>,
2809 {
2810 let view = self.view().downgrade();
2811 let entity_id = entity.entity_id();
2812 let window_handle = self.window.handle;
2813 let (subscription, activate) = self.app.release_listeners.insert(
2814 entity_id,
2815 Box::new(move |entity, cx| {
2816 let entity = entity.downcast_mut().expect("invalid entity type");
2817 let _ = window_handle.update(cx, |_, cx| {
2818 view.update(cx, |this, cx| on_release(this, entity, cx))
2819 });
2820 }),
2821 );
2822 activate();
2823 subscription
2824 }
2825
2826 /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
2827 /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
2828 pub fn notify(&mut self) {
2829 for view_id in self
2830 .window
2831 .rendered_frame
2832 .dispatch_tree
2833 .view_path(self.view.entity_id())
2834 .into_iter()
2835 .rev()
2836 {
2837 if !self.window.dirty_views.insert(view_id) {
2838 break;
2839 }
2840 }
2841
2842 if !self.window.drawing {
2843 self.window_cx.window.dirty = true;
2844 self.window_cx.app.push_effect(Effect::Notify {
2845 emitter: self.view.model.entity_id,
2846 });
2847 }
2848 }
2849
2850 /// Register a callback to be invoked when the window is resized.
2851 pub fn observe_window_bounds(
2852 &mut self,
2853 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2854 ) -> Subscription {
2855 let view = self.view.downgrade();
2856 let (subscription, activate) = self.window.bounds_observers.insert(
2857 (),
2858 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2859 );
2860 activate();
2861 subscription
2862 }
2863
2864 /// Register a callback to be invoked when the window is activated or deactivated.
2865 pub fn observe_window_activation(
2866 &mut self,
2867 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2868 ) -> Subscription {
2869 let view = self.view.downgrade();
2870 let (subscription, activate) = self.window.activation_observers.insert(
2871 (),
2872 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2873 );
2874 activate();
2875 subscription
2876 }
2877
2878 /// Register a listener to be called when the given focus handle receives focus.
2879 /// Returns a subscription and persists until the subscription is dropped.
2880 pub fn on_focus(
2881 &mut self,
2882 handle: &FocusHandle,
2883 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2884 ) -> Subscription {
2885 let view = self.view.downgrade();
2886 let focus_id = handle.id;
2887 let (subscription, activate) = self.window.focus_listeners.insert(
2888 (),
2889 Box::new(move |event, cx| {
2890 view.update(cx, |view, cx| {
2891 if event.previous_focus_path.last() != Some(&focus_id)
2892 && event.current_focus_path.last() == Some(&focus_id)
2893 {
2894 listener(view, cx)
2895 }
2896 })
2897 .is_ok()
2898 }),
2899 );
2900 self.app.defer(move |_| activate());
2901 subscription
2902 }
2903
2904 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2905 /// Returns a subscription and persists until the subscription is dropped.
2906 pub fn on_focus_in(
2907 &mut self,
2908 handle: &FocusHandle,
2909 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2910 ) -> Subscription {
2911 let view = self.view.downgrade();
2912 let focus_id = handle.id;
2913 let (subscription, activate) = self.window.focus_listeners.insert(
2914 (),
2915 Box::new(move |event, cx| {
2916 view.update(cx, |view, cx| {
2917 if !event.previous_focus_path.contains(&focus_id)
2918 && event.current_focus_path.contains(&focus_id)
2919 {
2920 listener(view, cx)
2921 }
2922 })
2923 .is_ok()
2924 }),
2925 );
2926 self.app.defer(move |_| activate());
2927 subscription
2928 }
2929
2930 /// Register a listener to be called when the given focus handle loses focus.
2931 /// Returns a subscription and persists until the subscription is dropped.
2932 pub fn on_blur(
2933 &mut self,
2934 handle: &FocusHandle,
2935 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2936 ) -> Subscription {
2937 let view = self.view.downgrade();
2938 let focus_id = handle.id;
2939 let (subscription, activate) = self.window.focus_listeners.insert(
2940 (),
2941 Box::new(move |event, cx| {
2942 view.update(cx, |view, cx| {
2943 if event.previous_focus_path.last() == Some(&focus_id)
2944 && event.current_focus_path.last() != Some(&focus_id)
2945 {
2946 listener(view, cx)
2947 }
2948 })
2949 .is_ok()
2950 }),
2951 );
2952 self.app.defer(move |_| activate());
2953 subscription
2954 }
2955
2956 /// Register a listener to be called when nothing in the window has focus.
2957 /// This typically happens when the node that was focused is removed from the tree,
2958 /// and this callback lets you chose a default place to restore the users focus.
2959 /// Returns a subscription and persists until the subscription is dropped.
2960 pub fn on_focus_lost(
2961 &mut self,
2962 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2963 ) -> Subscription {
2964 let view = self.view.downgrade();
2965 let (subscription, activate) = self.window.focus_lost_listeners.insert(
2966 (),
2967 Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2968 );
2969 activate();
2970 subscription
2971 }
2972
2973 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2974 /// Returns a subscription and persists until the subscription is dropped.
2975 pub fn on_focus_out(
2976 &mut self,
2977 handle: &FocusHandle,
2978 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2979 ) -> Subscription {
2980 let view = self.view.downgrade();
2981 let focus_id = handle.id;
2982 let (subscription, activate) = self.window.focus_listeners.insert(
2983 (),
2984 Box::new(move |event, cx| {
2985 view.update(cx, |view, cx| {
2986 if event.previous_focus_path.contains(&focus_id)
2987 && !event.current_focus_path.contains(&focus_id)
2988 {
2989 listener(view, cx)
2990 }
2991 })
2992 .is_ok()
2993 }),
2994 );
2995 self.app.defer(move |_| activate());
2996 subscription
2997 }
2998
2999 /// Schedule a future to be run asynchronously.
3000 /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
3001 /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
3002 /// The returned future will be polled on the main thread.
3003 pub fn spawn<Fut, R>(
3004 &mut self,
3005 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
3006 ) -> Task<R>
3007 where
3008 R: 'static,
3009 Fut: Future<Output = R> + 'static,
3010 {
3011 let view = self.view().downgrade();
3012 self.window_cx.spawn(|cx| f(view, cx))
3013 }
3014
3015 /// Updates the global state of the given type.
3016 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
3017 where
3018 G: 'static,
3019 {
3020 let mut global = self.app.lease_global::<G>();
3021 let result = f(&mut global, self);
3022 self.app.end_global_lease(global);
3023 result
3024 }
3025
3026 /// Register a callback to be invoked when the given global state changes.
3027 pub fn observe_global<G: 'static>(
3028 &mut self,
3029 mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
3030 ) -> Subscription {
3031 let window_handle = self.window.handle;
3032 let view = self.view().downgrade();
3033 let (subscription, activate) = self.global_observers.insert(
3034 TypeId::of::<G>(),
3035 Box::new(move |cx| {
3036 window_handle
3037 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
3038 .unwrap_or(false)
3039 }),
3040 );
3041 self.app.defer(move |_| activate());
3042 subscription
3043 }
3044
3045 /// Add a listener for any mouse event that occurs in the window.
3046 /// This is a fairly low level method.
3047 /// Typically, you'll want to use methods on UI elements, which perform bounds checking etc.
3048 pub fn on_mouse_event<Event: MouseEvent>(
3049 &mut self,
3050 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
3051 ) {
3052 let handle = self.view().clone();
3053 self.window_cx.on_mouse_event(move |event, phase, cx| {
3054 handle.update(cx, |view, cx| {
3055 handler(view, event, phase, cx);
3056 })
3057 });
3058 }
3059
3060 /// Register a callback to be invoked when the given Key Event is dispatched to the window.
3061 pub fn on_key_event<Event: KeyEvent>(
3062 &mut self,
3063 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
3064 ) {
3065 let handle = self.view().clone();
3066 self.window_cx.on_key_event(move |event, phase, cx| {
3067 handle.update(cx, |view, cx| {
3068 handler(view, event, phase, cx);
3069 })
3070 });
3071 }
3072
3073 /// Register a callback to be invoked when the given Action type is dispatched to the window.
3074 pub fn on_action(
3075 &mut self,
3076 action_type: TypeId,
3077 listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
3078 ) {
3079 let handle = self.view().clone();
3080 self.window_cx
3081 .on_action(action_type, move |action, phase, cx| {
3082 handle.update(cx, |view, cx| {
3083 listener(view, action, phase, cx);
3084 })
3085 });
3086 }
3087
3088 /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
3089 pub fn emit<Evt>(&mut self, event: Evt)
3090 where
3091 Evt: 'static,
3092 V: EventEmitter<Evt>,
3093 {
3094 let emitter = self.view.model.entity_id;
3095 self.app.push_effect(Effect::Emit {
3096 emitter,
3097 event_type: TypeId::of::<Evt>(),
3098 event: Box::new(event),
3099 });
3100 }
3101
3102 /// Move focus to the current view, assuming it implements [`FocusableView`].
3103 pub fn focus_self(&mut self)
3104 where
3105 V: FocusableView,
3106 {
3107 self.defer(|view, cx| view.focus_handle(cx).focus(cx))
3108 }
3109
3110 /// Convenience method for accessing view state in an event callback.
3111 ///
3112 /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
3113 /// but it's often useful to be able to access view state in these
3114 /// callbacks. This method provides a convenient way to do so.
3115 pub fn listener<E>(
3116 &self,
3117 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
3118 ) -> impl Fn(&E, &mut WindowContext) + 'static {
3119 let view = self.view().downgrade();
3120 move |e: &E, cx: &mut WindowContext| {
3121 view.update(cx, |view, cx| f(view, e, cx)).ok();
3122 }
3123 }
3124}
3125
3126impl<V> Context for ViewContext<'_, V> {
3127 type Result<U> = U;
3128
3129 fn new_model<T: 'static>(
3130 &mut self,
3131 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
3132 ) -> Model<T> {
3133 self.window_cx.new_model(build_model)
3134 }
3135
3136 fn update_model<T: 'static, R>(
3137 &mut self,
3138 model: &Model<T>,
3139 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
3140 ) -> R {
3141 self.window_cx.update_model(model, update)
3142 }
3143
3144 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
3145 where
3146 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
3147 {
3148 self.window_cx.update_window(window, update)
3149 }
3150
3151 fn read_model<T, R>(
3152 &self,
3153 handle: &Model<T>,
3154 read: impl FnOnce(&T, &AppContext) -> R,
3155 ) -> Self::Result<R>
3156 where
3157 T: 'static,
3158 {
3159 self.window_cx.read_model(handle, read)
3160 }
3161
3162 fn read_window<T, R>(
3163 &self,
3164 window: &WindowHandle<T>,
3165 read: impl FnOnce(View<T>, &AppContext) -> R,
3166 ) -> Result<R>
3167 where
3168 T: 'static,
3169 {
3170 self.window_cx.read_window(window, read)
3171 }
3172}
3173
3174impl<V: 'static> VisualContext for ViewContext<'_, V> {
3175 fn new_view<W: Render + 'static>(
3176 &mut self,
3177 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
3178 ) -> Self::Result<View<W>> {
3179 self.window_cx.new_view(build_view_state)
3180 }
3181
3182 fn update_view<V2: 'static, R>(
3183 &mut self,
3184 view: &View<V2>,
3185 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
3186 ) -> Self::Result<R> {
3187 self.window_cx.update_view(view, update)
3188 }
3189
3190 fn replace_root_view<W>(
3191 &mut self,
3192 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
3193 ) -> Self::Result<View<W>>
3194 where
3195 W: 'static + Render,
3196 {
3197 self.window_cx.replace_root_view(build_view)
3198 }
3199
3200 fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
3201 self.window_cx.focus_view(view)
3202 }
3203
3204 fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
3205 self.window_cx.dismiss_view(view)
3206 }
3207}
3208
3209impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
3210 type Target = WindowContext<'a>;
3211
3212 fn deref(&self) -> &Self::Target {
3213 &self.window_cx
3214 }
3215}
3216
3217impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
3218 fn deref_mut(&mut self) -> &mut Self::Target {
3219 &mut self.window_cx
3220 }
3221}
3222
3223// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
3224slotmap::new_key_type! {
3225 /// A unique identifier for a window.
3226 pub struct WindowId;
3227}
3228
3229impl WindowId {
3230 /// Converts this window ID to a `u64`.
3231 pub fn as_u64(&self) -> u64 {
3232 self.0.as_ffi()
3233 }
3234}
3235
3236/// A handle to a window with a specific root view type.
3237/// Note that this does not keep the window alive on its own.
3238#[derive(Deref, DerefMut)]
3239pub struct WindowHandle<V> {
3240 #[deref]
3241 #[deref_mut]
3242 pub(crate) any_handle: AnyWindowHandle,
3243 state_type: PhantomData<V>,
3244}
3245
3246impl<V: 'static + Render> WindowHandle<V> {
3247 /// Creates a new handle from a window ID.
3248 /// This does not check if the root type of the window is `V`.
3249 pub fn new(id: WindowId) -> Self {
3250 WindowHandle {
3251 any_handle: AnyWindowHandle {
3252 id,
3253 state_type: TypeId::of::<V>(),
3254 },
3255 state_type: PhantomData,
3256 }
3257 }
3258
3259 /// Get the root view out of this window.
3260 ///
3261 /// This will fail if the window is closed or if the root view's type does not match `V`.
3262 pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
3263 where
3264 C: Context,
3265 {
3266 Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
3267 root_view
3268 .downcast::<V>()
3269 .map_err(|_| anyhow!("the type of the window's root view has changed"))
3270 }))
3271 }
3272
3273 /// Updates the root view of this window.
3274 ///
3275 /// This will fail if the window has been closed or if the root view's type does not match
3276 pub fn update<C, R>(
3277 &self,
3278 cx: &mut C,
3279 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
3280 ) -> Result<R>
3281 where
3282 C: Context,
3283 {
3284 cx.update_window(self.any_handle, |root_view, cx| {
3285 let view = root_view
3286 .downcast::<V>()
3287 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3288 Ok(cx.update_view(&view, update))
3289 })?
3290 }
3291
3292 /// Read the root view out of this window.
3293 ///
3294 /// This will fail if the window is closed or if the root view's type does not match `V`.
3295 pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
3296 let x = cx
3297 .windows
3298 .get(self.id)
3299 .and_then(|window| {
3300 window
3301 .as_ref()
3302 .and_then(|window| window.root_view.clone())
3303 .map(|root_view| root_view.downcast::<V>())
3304 })
3305 .ok_or_else(|| anyhow!("window not found"))?
3306 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3307
3308 Ok(x.read(cx))
3309 }
3310
3311 /// Read the root view out of this window, with a callback
3312 ///
3313 /// This will fail if the window is closed or if the root view's type does not match `V`.
3314 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
3315 where
3316 C: Context,
3317 {
3318 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
3319 }
3320
3321 /// Read the root view pointer off of this window.
3322 ///
3323 /// This will fail if the window is closed or if the root view's type does not match `V`.
3324 pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
3325 where
3326 C: Context,
3327 {
3328 cx.read_window(self, |root_view, _cx| root_view.clone())
3329 }
3330
3331 /// Check if this window is 'active'.
3332 ///
3333 /// Will return `None` if the window is closed.
3334 pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
3335 cx.windows
3336 .get(self.id)
3337 .and_then(|window| window.as_ref().map(|window| window.active))
3338 }
3339}
3340
3341impl<V> Copy for WindowHandle<V> {}
3342
3343impl<V> Clone for WindowHandle<V> {
3344 fn clone(&self) -> Self {
3345 *self
3346 }
3347}
3348
3349impl<V> PartialEq for WindowHandle<V> {
3350 fn eq(&self, other: &Self) -> bool {
3351 self.any_handle == other.any_handle
3352 }
3353}
3354
3355impl<V> Eq for WindowHandle<V> {}
3356
3357impl<V> Hash for WindowHandle<V> {
3358 fn hash<H: Hasher>(&self, state: &mut H) {
3359 self.any_handle.hash(state);
3360 }
3361}
3362
3363impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
3364 fn from(val: WindowHandle<V>) -> Self {
3365 val.any_handle
3366 }
3367}
3368
3369/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
3370#[derive(Copy, Clone, PartialEq, Eq, Hash)]
3371pub struct AnyWindowHandle {
3372 pub(crate) id: WindowId,
3373 state_type: TypeId,
3374}
3375
3376impl AnyWindowHandle {
3377 /// Get the ID of this window.
3378 pub fn window_id(&self) -> WindowId {
3379 self.id
3380 }
3381
3382 /// Attempt to convert this handle to a window handle with a specific root view type.
3383 /// If the types do not match, this will return `None`.
3384 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
3385 if TypeId::of::<T>() == self.state_type {
3386 Some(WindowHandle {
3387 any_handle: *self,
3388 state_type: PhantomData,
3389 })
3390 } else {
3391 None
3392 }
3393 }
3394
3395 /// Updates the state of the root view of this window.
3396 ///
3397 /// This will fail if the window has been closed.
3398 pub fn update<C, R>(
3399 self,
3400 cx: &mut C,
3401 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
3402 ) -> Result<R>
3403 where
3404 C: Context,
3405 {
3406 cx.update_window(self, update)
3407 }
3408
3409 /// Read the state of the root view of this window.
3410 ///
3411 /// This will fail if the window has been closed.
3412 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
3413 where
3414 C: Context,
3415 T: 'static,
3416 {
3417 let view = self
3418 .downcast::<T>()
3419 .context("the type of the window's root view has changed")?;
3420
3421 cx.read_window(&view, read)
3422 }
3423}
3424
3425/// An identifier for an [`Element`](crate::Element).
3426///
3427/// Can be constructed with a string, a number, or both, as well
3428/// as other internal representations.
3429#[derive(Clone, Debug, Eq, PartialEq, Hash)]
3430pub enum ElementId {
3431 /// The ID of a View element
3432 View(EntityId),
3433 /// An integer ID.
3434 Integer(usize),
3435 /// A string based ID.
3436 Name(SharedString),
3437 /// An ID that's equated with a focus handle.
3438 FocusHandle(FocusId),
3439 /// A combination of a name and an integer.
3440 NamedInteger(SharedString, usize),
3441}
3442
3443impl Display for ElementId {
3444 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3445 match self {
3446 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
3447 ElementId::Integer(ix) => write!(f, "{}", ix)?,
3448 ElementId::Name(name) => write!(f, "{}", name)?,
3449 ElementId::FocusHandle(__) => write!(f, "FocusHandle")?,
3450 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
3451 }
3452
3453 Ok(())
3454 }
3455}
3456
3457impl ElementId {
3458 pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
3459 ElementId::View(entity_id)
3460 }
3461}
3462
3463impl TryInto<SharedString> for ElementId {
3464 type Error = anyhow::Error;
3465
3466 fn try_into(self) -> anyhow::Result<SharedString> {
3467 if let ElementId::Name(name) = self {
3468 Ok(name)
3469 } else {
3470 Err(anyhow!("element id is not string"))
3471 }
3472 }
3473}
3474
3475impl From<usize> for ElementId {
3476 fn from(id: usize) -> Self {
3477 ElementId::Integer(id)
3478 }
3479}
3480
3481impl From<i32> for ElementId {
3482 fn from(id: i32) -> Self {
3483 Self::Integer(id as usize)
3484 }
3485}
3486
3487impl From<SharedString> for ElementId {
3488 fn from(name: SharedString) -> Self {
3489 ElementId::Name(name)
3490 }
3491}
3492
3493impl From<&'static str> for ElementId {
3494 fn from(name: &'static str) -> Self {
3495 ElementId::Name(name.into())
3496 }
3497}
3498
3499impl<'a> From<&'a FocusHandle> for ElementId {
3500 fn from(handle: &'a FocusHandle) -> Self {
3501 ElementId::FocusHandle(handle.id)
3502 }
3503}
3504
3505impl From<(&'static str, EntityId)> for ElementId {
3506 fn from((name, id): (&'static str, EntityId)) -> Self {
3507 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
3508 }
3509}
3510
3511impl From<(&'static str, usize)> for ElementId {
3512 fn from((name, id): (&'static str, usize)) -> Self {
3513 ElementId::NamedInteger(name.into(), id)
3514 }
3515}
3516
3517impl From<(&'static str, u64)> for ElementId {
3518 fn from((name, id): (&'static str, u64)) -> Self {
3519 ElementId::NamedInteger(name.into(), id as usize)
3520 }
3521}
3522
3523/// A rectangle to be rendered in the window at the given position and size.
3524/// Passed as an argument [`WindowContext::paint_quad`].
3525#[derive(Clone)]
3526pub struct PaintQuad {
3527 bounds: Bounds<Pixels>,
3528 corner_radii: Corners<Pixels>,
3529 background: Hsla,
3530 border_widths: Edges<Pixels>,
3531 border_color: Hsla,
3532}
3533
3534impl PaintQuad {
3535 /// Sets the corner radii of the quad.
3536 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
3537 PaintQuad {
3538 corner_radii: corner_radii.into(),
3539 ..self
3540 }
3541 }
3542
3543 /// Sets the border widths of the quad.
3544 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
3545 PaintQuad {
3546 border_widths: border_widths.into(),
3547 ..self
3548 }
3549 }
3550
3551 /// Sets the border color of the quad.
3552 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
3553 PaintQuad {
3554 border_color: border_color.into(),
3555 ..self
3556 }
3557 }
3558
3559 /// Sets the background color of the quad.
3560 pub fn background(self, background: impl Into<Hsla>) -> Self {
3561 PaintQuad {
3562 background: background.into(),
3563 ..self
3564 }
3565 }
3566}
3567
3568/// Creates a quad with the given parameters.
3569pub fn quad(
3570 bounds: Bounds<Pixels>,
3571 corner_radii: impl Into<Corners<Pixels>>,
3572 background: impl Into<Hsla>,
3573 border_widths: impl Into<Edges<Pixels>>,
3574 border_color: impl Into<Hsla>,
3575) -> PaintQuad {
3576 PaintQuad {
3577 bounds,
3578 corner_radii: corner_radii.into(),
3579 background: background.into(),
3580 border_widths: border_widths.into(),
3581 border_color: border_color.into(),
3582 }
3583}
3584
3585/// Creates a filled quad with the given bounds and background color.
3586pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
3587 PaintQuad {
3588 bounds: bounds.into(),
3589 corner_radii: (0.).into(),
3590 background: background.into(),
3591 border_widths: (0.).into(),
3592 border_color: transparent_black(),
3593 }
3594}
3595
3596/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
3597pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
3598 PaintQuad {
3599 bounds: bounds.into(),
3600 corner_radii: (0.).into(),
3601 background: transparent_black(),
3602 border_widths: (1.).into(),
3603 border_color: border_color.into(),
3604 }
3605}