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