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};
49
50mod prompts;
51
52pub use prompts::*;
53
54pub(crate) const DEFAULT_WINDOW_SIZE: Size<DevicePixels> =
55 size(DevicePixels(1024), DevicePixels(700));
56
57/// Represents the two different phases when dispatching events.
58#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
59pub enum DispatchPhase {
60 /// After the capture phase comes the bubble phase, in which mouse event listeners are
61 /// invoked front to back and keyboard event listeners are invoked from the focused element
62 /// to the root of the element tree. This is the phase you'll most commonly want to use when
63 /// registering event listeners.
64 #[default]
65 Bubble,
66 /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
67 /// listeners are invoked from the root of the tree downward toward the focused element. This phase
68 /// is used for special purposes such as clearing the "pressed" state for click events. If
69 /// you stop event propagation during this phase, you need to know what you're doing. Handlers
70 /// outside of the immediate region may rely on detecting non-local events during this phase.
71 Capture,
72}
73
74impl DispatchPhase {
75 /// Returns true if this represents the "bubble" phase.
76 pub fn bubble(self) -> bool {
77 self == DispatchPhase::Bubble
78 }
79
80 /// Returns true if this represents the "capture" phase.
81 pub fn capture(self) -> bool {
82 self == DispatchPhase::Capture
83 }
84}
85
86type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
87
88type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
89
90struct FocusEvent {
91 previous_focus_path: SmallVec<[FocusId; 8]>,
92 current_focus_path: SmallVec<[FocusId; 8]>,
93}
94
95slotmap::new_key_type! {
96 /// A globally unique identifier for a focusable element.
97 pub struct FocusId;
98}
99
100thread_local! {
101 /// 8MB wasn't quite enough...
102 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(32 * 1024 * 1024));
103}
104
105impl FocusId {
106 /// Obtains whether the element associated with this handle is currently focused.
107 pub fn is_focused(&self, cx: &WindowContext) -> bool {
108 cx.window.focus == Some(*self)
109 }
110
111 /// Obtains whether the element associated with this handle contains the focused
112 /// element or is itself focused.
113 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
114 cx.focused()
115 .map_or(false, |focused| self.contains(focused.id, cx))
116 }
117
118 /// Obtains whether the element associated with this handle is contained within the
119 /// focused element or is itself focused.
120 pub fn within_focused(&self, cx: &WindowContext) -> bool {
121 let focused = cx.focused();
122 focused.map_or(false, |focused| focused.id.contains(*self, cx))
123 }
124
125 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
126 pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
127 cx.window
128 .rendered_frame
129 .dispatch_tree
130 .focus_contains(*self, other)
131 }
132}
133
134/// A handle which can be used to track and manipulate the focused element in a window.
135pub struct FocusHandle {
136 pub(crate) id: FocusId,
137 handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
138}
139
140impl std::fmt::Debug for FocusHandle {
141 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
143 }
144}
145
146impl FocusHandle {
147 pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
148 let id = handles.write().insert(AtomicUsize::new(1));
149 Self {
150 id,
151 handles: handles.clone(),
152 }
153 }
154
155 pub(crate) fn for_id(
156 id: FocusId,
157 handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
158 ) -> Option<Self> {
159 let lock = handles.read();
160 let ref_count = lock.get(id)?;
161 if ref_count.load(SeqCst) == 0 {
162 None
163 } else {
164 ref_count.fetch_add(1, SeqCst);
165 Some(Self {
166 id,
167 handles: handles.clone(),
168 })
169 }
170 }
171
172 /// Converts this focus handle into a weak variant, which does not prevent it from being released.
173 pub fn downgrade(&self) -> WeakFocusHandle {
174 WeakFocusHandle {
175 id: self.id,
176 handles: Arc::downgrade(&self.handles),
177 }
178 }
179
180 /// Moves the focus to the element associated with this handle.
181 pub fn focus(&self, cx: &mut WindowContext) {
182 cx.focus(self)
183 }
184
185 /// Obtains whether the element associated with this handle is currently focused.
186 pub fn is_focused(&self, cx: &WindowContext) -> bool {
187 self.id.is_focused(cx)
188 }
189
190 /// Obtains whether the element associated with this handle contains the focused
191 /// element or is itself focused.
192 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
193 self.id.contains_focused(cx)
194 }
195
196 /// Obtains whether the element associated with this handle is contained within the
197 /// focused element or is itself focused.
198 pub fn within_focused(&self, cx: &WindowContext) -> bool {
199 self.id.within_focused(cx)
200 }
201
202 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
203 pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
204 self.id.contains(other.id, cx)
205 }
206
207 /// Dispatch an action on the element that rendered this focus handle
208 pub fn dispatch_action(&self, action: &dyn Action, cx: &mut WindowContext) {
209 if let Some(node_id) = cx
210 .window
211 .rendered_frame
212 .dispatch_tree
213 .focusable_node_id(self.id)
214 {
215 cx.dispatch_action_on_node(node_id, action)
216 }
217 }
218}
219
220impl Clone for FocusHandle {
221 fn clone(&self) -> Self {
222 Self::for_id(self.id, &self.handles).unwrap()
223 }
224}
225
226impl PartialEq for FocusHandle {
227 fn eq(&self, other: &Self) -> bool {
228 self.id == other.id
229 }
230}
231
232impl Eq for FocusHandle {}
233
234impl Drop for FocusHandle {
235 fn drop(&mut self) {
236 self.handles
237 .read()
238 .get(self.id)
239 .unwrap()
240 .fetch_sub(1, SeqCst);
241 }
242}
243
244/// A weak reference to a focus handle.
245#[derive(Clone, Debug)]
246pub struct WeakFocusHandle {
247 pub(crate) id: FocusId,
248 handles: Weak<RwLock<SlotMap<FocusId, AtomicUsize>>>,
249}
250
251impl WeakFocusHandle {
252 /// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle].
253 pub fn upgrade(&self) -> Option<FocusHandle> {
254 let handles = self.handles.upgrade()?;
255 FocusHandle::for_id(self.id, &handles)
256 }
257}
258
259impl PartialEq for WeakFocusHandle {
260 fn eq(&self, other: &WeakFocusHandle) -> bool {
261 self.id == other.id
262 }
263}
264
265impl Eq for WeakFocusHandle {}
266
267impl PartialEq<FocusHandle> for WeakFocusHandle {
268 fn eq(&self, other: &FocusHandle) -> bool {
269 self.id == other.id
270 }
271}
272
273impl PartialEq<WeakFocusHandle> for FocusHandle {
274 fn eq(&self, other: &WeakFocusHandle) -> bool {
275 self.id == other.id
276 }
277}
278
279/// FocusableView allows users of your view to easily
280/// focus it (using cx.focus_view(view))
281pub trait FocusableView: 'static + Render {
282 /// Returns the focus handle associated with this view.
283 fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
284}
285
286/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
287/// where the lifecycle of the view is handled by another view.
288pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
289
290impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
291
292/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
293pub struct DismissEvent;
294
295type FrameCallback = Box<dyn FnOnce(&mut WindowContext)>;
296
297pub(crate) type AnyMouseListener =
298 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
299
300#[derive(Clone)]
301pub(crate) struct CursorStyleRequest {
302 pub(crate) hitbox_id: HitboxId,
303 pub(crate) style: CursorStyle,
304}
305
306/// An identifier for a [Hitbox].
307#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
308pub struct HitboxId(usize);
309
310impl HitboxId {
311 /// Checks if the hitbox with this id is currently hovered.
312 pub fn is_hovered(&self, cx: &WindowContext) -> bool {
313 cx.window.mouse_hit_test.0.contains(self)
314 }
315}
316
317/// A rectangular region that potentially blocks hitboxes inserted prior.
318/// See [WindowContext::insert_hitbox] for more details.
319#[derive(Clone, Debug, Deref)]
320pub struct Hitbox {
321 /// A unique identifier for the hitbox.
322 pub id: HitboxId,
323 /// The bounds of the hitbox.
324 #[deref]
325 pub bounds: Bounds<Pixels>,
326 /// The content mask when the hitbox was inserted.
327 pub content_mask: ContentMask<Pixels>,
328 /// Whether the hitbox occludes other hitboxes inserted prior.
329 pub opaque: bool,
330}
331
332impl Hitbox {
333 /// Checks if the hitbox is currently hovered.
334 pub fn is_hovered(&self, cx: &WindowContext) -> bool {
335 self.id.is_hovered(cx)
336 }
337}
338
339#[derive(Default, Eq, PartialEq)]
340pub(crate) struct HitTest(SmallVec<[HitboxId; 8]>);
341
342/// An identifier for a tooltip.
343#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
344pub struct TooltipId(usize);
345
346impl TooltipId {
347 /// Checks if the tooltip is currently hovered.
348 pub fn is_hovered(&self, cx: &WindowContext) -> bool {
349 cx.window
350 .tooltip_bounds
351 .as_ref()
352 .map_or(false, |tooltip_bounds| {
353 tooltip_bounds.id == *self && tooltip_bounds.bounds.contains(&cx.mouse_position())
354 })
355 }
356}
357
358pub(crate) struct TooltipBounds {
359 id: TooltipId,
360 bounds: Bounds<Pixels>,
361}
362
363#[derive(Clone)]
364pub(crate) struct TooltipRequest {
365 id: TooltipId,
366 tooltip: AnyTooltip,
367}
368
369pub(crate) struct DeferredDraw {
370 priority: usize,
371 parent_node: DispatchNodeId,
372 element_id_stack: SmallVec<[ElementId; 32]>,
373 text_style_stack: Vec<TextStyleRefinement>,
374 element: Option<AnyElement>,
375 absolute_offset: Point<Pixels>,
376 prepaint_range: Range<PrepaintStateIndex>,
377 paint_range: Range<PaintIndex>,
378}
379
380pub(crate) struct Frame {
381 pub(crate) focus: Option<FocusId>,
382 pub(crate) window_active: bool,
383 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
384 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
385 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
386 pub(crate) dispatch_tree: DispatchTree,
387 pub(crate) scene: Scene,
388 pub(crate) hitboxes: Vec<Hitbox>,
389 pub(crate) deferred_draws: Vec<DeferredDraw>,
390 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
391 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
392 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
393 #[cfg(any(test, feature = "test-support"))]
394 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
395}
396
397#[derive(Clone, Default)]
398pub(crate) struct PrepaintStateIndex {
399 hitboxes_index: usize,
400 tooltips_index: usize,
401 deferred_draws_index: usize,
402 dispatch_tree_index: usize,
403 accessed_element_states_index: usize,
404 line_layout_index: LineLayoutIndex,
405}
406
407#[derive(Clone, Default)]
408pub(crate) struct PaintIndex {
409 scene_index: usize,
410 mouse_listeners_index: usize,
411 input_handlers_index: usize,
412 cursor_styles_index: usize,
413 accessed_element_states_index: usize,
414 line_layout_index: LineLayoutIndex,
415}
416
417impl Frame {
418 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
419 Frame {
420 focus: None,
421 window_active: false,
422 element_states: FxHashMap::default(),
423 accessed_element_states: Vec::new(),
424 mouse_listeners: Vec::new(),
425 dispatch_tree,
426 scene: Scene::default(),
427 hitboxes: Vec::new(),
428 deferred_draws: Vec::new(),
429 input_handlers: Vec::new(),
430 tooltip_requests: Vec::new(),
431 cursor_styles: Vec::new(),
432
433 #[cfg(any(test, feature = "test-support"))]
434 debug_bounds: FxHashMap::default(),
435 }
436 }
437
438 pub(crate) fn clear(&mut self) {
439 self.element_states.clear();
440 self.accessed_element_states.clear();
441 self.mouse_listeners.clear();
442 self.dispatch_tree.clear();
443 self.scene.clear();
444 self.input_handlers.clear();
445 self.tooltip_requests.clear();
446 self.cursor_styles.clear();
447 self.hitboxes.clear();
448 self.deferred_draws.clear();
449 }
450
451 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
452 let mut hit_test = HitTest::default();
453 for hitbox in self.hitboxes.iter().rev() {
454 let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
455 if bounds.contains(&position) {
456 hit_test.0.push(hitbox.id);
457 if hitbox.opaque {
458 break;
459 }
460 }
461 }
462 hit_test
463 }
464
465 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
466 self.focus
467 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
468 .unwrap_or_default()
469 }
470
471 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
472 for element_state_key in &self.accessed_element_states {
473 if let Some((element_state_key, element_state)) =
474 prev_frame.element_states.remove_entry(element_state_key)
475 {
476 self.element_states.insert(element_state_key, element_state);
477 }
478 }
479
480 self.scene.finish();
481 }
482}
483
484// Holds the state for a specific window.
485#[doc(hidden)]
486pub struct Window {
487 pub(crate) handle: AnyWindowHandle,
488 pub(crate) removed: bool,
489 pub(crate) platform_window: Box<dyn PlatformWindow>,
490 display_id: DisplayId,
491 sprite_atlas: Arc<dyn PlatformAtlas>,
492 text_system: Arc<WindowTextSystem>,
493 rem_size: Pixels,
494 /// An override value for the window's rem size.
495 ///
496 /// This is used by `with_rem_size` to allow rendering an element tree with
497 /// a given rem size.
498 ///
499 /// Note: Right now we only allow for a single override value at a time, but
500 /// this could likely be changed to be a stack of rem sizes.
501 rem_size_override: Option<Pixels>,
502 pub(crate) viewport_size: Size<Pixels>,
503 layout_engine: Option<TaffyLayoutEngine>,
504 pub(crate) root_view: Option<AnyView>,
505 pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
506 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
507 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
508 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
509 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
510 pub(crate) rendered_frame: Frame,
511 pub(crate) next_frame: Frame,
512 pub(crate) next_hitbox_id: HitboxId,
513 pub(crate) next_tooltip_id: TooltipId,
514 pub(crate) tooltip_bounds: Option<TooltipBounds>,
515 next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
516 pub(crate) dirty_views: FxHashSet<EntityId>,
517 pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
518 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
519 focus_lost_listeners: SubscriberSet<(), AnyObserver>,
520 default_prevented: bool,
521 mouse_position: Point<Pixels>,
522 mouse_hit_test: HitTest,
523 modifiers: Modifiers,
524 scale_factor: f32,
525 bounds_observers: SubscriberSet<(), AnyObserver>,
526 appearance: WindowAppearance,
527 appearance_observers: SubscriberSet<(), AnyObserver>,
528 active: Rc<Cell<bool>>,
529 pub(crate) dirty: Rc<Cell<bool>>,
530 pub(crate) needs_present: Rc<Cell<bool>>,
531 pub(crate) last_input_timestamp: Rc<Cell<Instant>>,
532 pub(crate) refreshing: bool,
533 pub(crate) draw_phase: DrawPhase,
534 activation_observers: SubscriberSet<(), AnyObserver>,
535 pub(crate) focus: Option<FocusId>,
536 focus_enabled: bool,
537 pending_input: Option<PendingInput>,
538 prompt: Option<RenderablePromptHandle>,
539}
540
541#[derive(Clone, Copy, Debug, Eq, PartialEq)]
542pub(crate) enum DrawPhase {
543 None,
544 Prepaint,
545 Paint,
546 Focus,
547}
548
549#[derive(Default, Debug)]
550struct PendingInput {
551 keystrokes: SmallVec<[Keystroke; 1]>,
552 bindings: SmallVec<[KeyBinding; 1]>,
553 focus: Option<FocusId>,
554 timer: Option<Task<()>>,
555}
556
557impl PendingInput {
558 fn input(&self) -> String {
559 self.keystrokes
560 .iter()
561 .flat_map(|k| k.ime_key.clone())
562 .collect::<Vec<String>>()
563 .join("")
564 }
565
566 fn used_by_binding(&self, binding: &KeyBinding) -> bool {
567 if self.keystrokes.is_empty() {
568 return true;
569 }
570 let keystroke = &self.keystrokes[0];
571 for candidate in keystroke.match_candidates() {
572 if binding.match_keystrokes(&[candidate]) == KeyMatch::Pending {
573 return true;
574 }
575 }
576 false
577 }
578}
579
580pub(crate) struct ElementStateBox {
581 pub(crate) inner: Box<dyn Any>,
582 #[cfg(debug_assertions)]
583 pub(crate) type_name: &'static str,
584}
585
586fn default_bounds(display_id: Option<DisplayId>, cx: &mut AppContext) -> Bounds<DevicePixels> {
587 const DEFAULT_WINDOW_OFFSET: Point<DevicePixels> = point(DevicePixels(0), DevicePixels(35));
588
589 cx.active_window()
590 .and_then(|w| w.update(cx, |_, cx| cx.bounds()).ok())
591 .map(|bounds| bounds.map_origin(|origin| origin + DEFAULT_WINDOW_OFFSET))
592 .unwrap_or_else(|| {
593 let display = display_id
594 .map(|id| cx.find_display(id))
595 .unwrap_or_else(|| cx.primary_display());
596
597 display
598 .map(|display| display.default_bounds())
599 .unwrap_or_else(|| {
600 Bounds::new(point(DevicePixels(0), DevicePixels(0)), DEFAULT_WINDOW_SIZE)
601 })
602 })
603}
604
605impl Window {
606 pub(crate) fn new(
607 handle: AnyWindowHandle,
608 options: WindowOptions,
609 cx: &mut AppContext,
610 ) -> Self {
611 let WindowOptions {
612 window_bounds,
613 titlebar,
614 focus,
615 show,
616 kind,
617 is_movable,
618 display_id,
619 window_background,
620 app_id,
621 } = options;
622
623 let bounds = window_bounds
624 .map(|bounds| bounds.get_bounds())
625 .unwrap_or_else(|| default_bounds(display_id, cx));
626 let mut platform_window = cx.platform.open_window(
627 handle,
628 WindowParams {
629 bounds,
630 titlebar,
631 kind,
632 is_movable,
633 focus,
634 show,
635 display_id,
636 window_background,
637 },
638 );
639 let display_id = platform_window.display().id();
640 let sprite_atlas = platform_window.sprite_atlas();
641 let mouse_position = platform_window.mouse_position();
642 let modifiers = platform_window.modifiers();
643 let content_size = platform_window.content_size();
644 let scale_factor = platform_window.scale_factor();
645 let appearance = platform_window.appearance();
646 let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
647 let dirty = Rc::new(Cell::new(true));
648 let active = Rc::new(Cell::new(platform_window.is_active()));
649 let needs_present = Rc::new(Cell::new(false));
650 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
651 let last_input_timestamp = Rc::new(Cell::new(Instant::now()));
652
653 if let Some(ref window_open_state) = window_bounds {
654 match window_open_state {
655 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
656 WindowBounds::Maximized(_) => platform_window.zoom(),
657 WindowBounds::Windowed(_) => {}
658 }
659 }
660
661 platform_window.on_close(Box::new({
662 let mut cx = cx.to_async();
663 move || {
664 let _ = handle.update(&mut cx, |_, cx| cx.remove_window());
665 }
666 }));
667 platform_window.on_request_frame(Box::new({
668 let mut cx = cx.to_async();
669 let dirty = dirty.clone();
670 let active = active.clone();
671 let needs_present = needs_present.clone();
672 let next_frame_callbacks = next_frame_callbacks.clone();
673 let last_input_timestamp = last_input_timestamp.clone();
674 move || {
675 let next_frame_callbacks = next_frame_callbacks.take();
676 if !next_frame_callbacks.is_empty() {
677 handle
678 .update(&mut cx, |_, cx| {
679 for callback in next_frame_callbacks {
680 callback(cx);
681 }
682 })
683 .log_err();
684 }
685
686 // Keep presenting the current scene for 1 extra second since the
687 // last input to prevent the display from underclocking the refresh rate.
688 let needs_present = needs_present.get()
689 || (active.get()
690 && last_input_timestamp.get().elapsed() < Duration::from_secs(1));
691
692 if dirty.get() {
693 measure("frame duration", || {
694 handle
695 .update(&mut cx, |_, cx| {
696 cx.draw();
697 cx.present();
698 })
699 .log_err();
700 })
701 } else if needs_present {
702 handle.update(&mut cx, |_, cx| cx.present()).log_err();
703 }
704
705 handle
706 .update(&mut cx, |_, cx| {
707 cx.complete_frame();
708 })
709 .log_err();
710 }
711 }));
712 platform_window.on_resize(Box::new({
713 let mut cx = cx.to_async();
714 move |_, _| {
715 handle
716 .update(&mut cx, |_, cx| cx.bounds_changed())
717 .log_err();
718 }
719 }));
720 platform_window.on_moved(Box::new({
721 let mut cx = cx.to_async();
722 move || {
723 handle
724 .update(&mut cx, |_, cx| cx.bounds_changed())
725 .log_err();
726 }
727 }));
728 platform_window.on_appearance_changed(Box::new({
729 let mut cx = cx.to_async();
730 move || {
731 handle
732 .update(&mut cx, |_, cx| cx.appearance_changed())
733 .log_err();
734 }
735 }));
736 platform_window.on_active_status_change(Box::new({
737 let mut cx = cx.to_async();
738 move |active| {
739 handle
740 .update(&mut cx, |_, cx| {
741 cx.window.active.set(active);
742 cx.window
743 .activation_observers
744 .clone()
745 .retain(&(), |callback| callback(cx));
746 cx.refresh();
747 })
748 .log_err();
749 }
750 }));
751
752 platform_window.on_input({
753 let mut cx = cx.to_async();
754 Box::new(move |event| {
755 handle
756 .update(&mut cx, |_, cx| cx.dispatch_event(event))
757 .log_err()
758 .unwrap_or(DispatchEventResult::default())
759 })
760 });
761
762 if let Some(app_id) = app_id {
763 platform_window.set_app_id(&app_id);
764 }
765
766 Window {
767 handle,
768 removed: false,
769 platform_window,
770 display_id,
771 sprite_atlas,
772 text_system,
773 rem_size: px(16.),
774 rem_size_override: None,
775 viewport_size: content_size,
776 layout_engine: Some(TaffyLayoutEngine::new()),
777 root_view: None,
778 element_id_stack: SmallVec::default(),
779 text_style_stack: Vec::new(),
780 element_offset_stack: Vec::new(),
781 content_mask_stack: Vec::new(),
782 requested_autoscroll: None,
783 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
784 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
785 next_frame_callbacks,
786 next_hitbox_id: HitboxId::default(),
787 next_tooltip_id: TooltipId::default(),
788 tooltip_bounds: None,
789 dirty_views: FxHashSet::default(),
790 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
791 focus_listeners: SubscriberSet::new(),
792 focus_lost_listeners: SubscriberSet::new(),
793 default_prevented: true,
794 mouse_position,
795 mouse_hit_test: HitTest::default(),
796 modifiers,
797 scale_factor,
798 bounds_observers: SubscriberSet::new(),
799 appearance,
800 appearance_observers: SubscriberSet::new(),
801 active,
802 dirty,
803 needs_present,
804 last_input_timestamp,
805 refreshing: false,
806 draw_phase: DrawPhase::None,
807 activation_observers: SubscriberSet::new(),
808 focus: None,
809 focus_enabled: true,
810 pending_input: None,
811 prompt: None,
812 }
813 }
814 fn new_focus_listener(
815 &mut self,
816 value: AnyWindowFocusListener,
817 ) -> (Subscription, impl FnOnce()) {
818 self.focus_listeners.insert((), value)
819 }
820}
821
822#[derive(Clone, Debug, Default, PartialEq, Eq)]
823pub(crate) struct DispatchEventResult {
824 pub propagate: bool,
825 pub default_prevented: bool,
826}
827
828/// Indicates which region of the window is visible. Content falling outside of this mask will not be
829/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
830/// to leave room to support more complex shapes in the future.
831#[derive(Clone, Debug, Default, PartialEq, Eq)]
832#[repr(C)]
833pub struct ContentMask<P: Clone + Default + Debug> {
834 /// The bounds
835 pub bounds: Bounds<P>,
836}
837
838impl ContentMask<Pixels> {
839 /// Scale the content mask's pixel units by the given scaling factor.
840 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
841 ContentMask {
842 bounds: self.bounds.scale(factor),
843 }
844 }
845
846 /// Intersect the content mask with the given content mask.
847 pub fn intersect(&self, other: &Self) -> Self {
848 let bounds = self.bounds.intersect(&other.bounds);
849 ContentMask { bounds }
850 }
851}
852
853/// Provides access to application state in the context of a single window. Derefs
854/// to an [`AppContext`], so you can also pass a [`WindowContext`] to any method that takes
855/// an [`AppContext`] and call any [`AppContext`] methods.
856pub struct WindowContext<'a> {
857 pub(crate) app: &'a mut AppContext,
858 pub(crate) window: &'a mut Window,
859}
860
861impl<'a> WindowContext<'a> {
862 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
863 Self { app, window }
864 }
865
866 /// Obtain a handle to the window that belongs to this context.
867 pub fn window_handle(&self) -> AnyWindowHandle {
868 self.window.handle
869 }
870
871 /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
872 pub fn refresh(&mut self) {
873 if self.window.draw_phase == DrawPhase::None {
874 self.window.refreshing = true;
875 self.window.dirty.set(true);
876 }
877 }
878
879 /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
880 /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
881 pub fn notify(&mut self, view_id: EntityId) {
882 for view_id in self
883 .window
884 .rendered_frame
885 .dispatch_tree
886 .view_path(view_id)
887 .into_iter()
888 .rev()
889 {
890 if !self.window.dirty_views.insert(view_id) {
891 break;
892 }
893 }
894
895 if self.window.draw_phase == DrawPhase::None {
896 self.window.dirty.set(true);
897 self.app.push_effect(Effect::Notify { emitter: view_id });
898 }
899 }
900
901 /// Close this window.
902 pub fn remove_window(&mut self) {
903 self.window.removed = true;
904 }
905
906 /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
907 /// for elements rendered within this window.
908 pub fn focus_handle(&mut self) -> FocusHandle {
909 FocusHandle::new(&self.window.focus_handles)
910 }
911
912 /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
913 pub fn focused(&self) -> Option<FocusHandle> {
914 self.window
915 .focus
916 .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
917 }
918
919 /// Move focus to the element associated with the given [`FocusHandle`].
920 pub fn focus(&mut self, handle: &FocusHandle) {
921 if !self.window.focus_enabled || self.window.focus == Some(handle.id) {
922 return;
923 }
924
925 self.window.focus = Some(handle.id);
926 self.window
927 .rendered_frame
928 .dispatch_tree
929 .clear_pending_keystrokes();
930 self.refresh();
931 }
932
933 /// Remove focus from all elements within this context's window.
934 pub fn blur(&mut self) {
935 if !self.window.focus_enabled {
936 return;
937 }
938
939 self.window.focus = None;
940 self.refresh();
941 }
942
943 /// Blur the window and don't allow anything in it to be focused again.
944 pub fn disable_focus(&mut self) {
945 self.blur();
946 self.window.focus_enabled = false;
947 }
948
949 /// Accessor for the text system.
950 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
951 &self.window.text_system
952 }
953
954 /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
955 pub fn text_style(&self) -> TextStyle {
956 let mut style = TextStyle::default();
957 for refinement in &self.window.text_style_stack {
958 style.refine(refinement);
959 }
960 style
961 }
962
963 /// Check if the platform window is maximized
964 /// On some platforms (namely Windows) this is different than the bounds being the size of the display
965 pub fn is_maximized(&self) -> bool {
966 self.window.platform_window.is_maximized()
967 }
968
969 /// Return the `WindowBounds` to indicate that how a window should be opened
970 /// after it has been closed
971 pub fn window_bounds(&self) -> WindowBounds {
972 self.window.platform_window.window_bounds()
973 }
974
975 /// Dispatch the given action on the currently focused element.
976 pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
977 let focus_handle = self.focused();
978
979 let window = self.window.handle;
980 self.app.defer(move |cx| {
981 window
982 .update(cx, |_, cx| {
983 let node_id = focus_handle
984 .and_then(|handle| {
985 cx.window
986 .rendered_frame
987 .dispatch_tree
988 .focusable_node_id(handle.id)
989 })
990 .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
991
992 cx.dispatch_action_on_node(node_id, action.as_ref());
993 })
994 .log_err();
995 })
996 }
997
998 pub(crate) fn dispatch_keystroke_observers(
999 &mut self,
1000 event: &dyn Any,
1001 action: Option<Box<dyn Action>>,
1002 ) {
1003 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1004 return;
1005 };
1006
1007 self.keystroke_observers
1008 .clone()
1009 .retain(&(), move |callback| {
1010 (callback)(
1011 &KeystrokeEvent {
1012 keystroke: key_down_event.keystroke.clone(),
1013 action: action.as_ref().map(|action| action.boxed_clone()),
1014 },
1015 self,
1016 );
1017 true
1018 });
1019 }
1020
1021 pub(crate) fn clear_pending_keystrokes(&mut self) {
1022 self.window
1023 .rendered_frame
1024 .dispatch_tree
1025 .clear_pending_keystrokes();
1026 self.window
1027 .next_frame
1028 .dispatch_tree
1029 .clear_pending_keystrokes();
1030 }
1031
1032 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1033 /// that are currently on the stack to be returned to the app.
1034 pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
1035 let handle = self.window.handle;
1036 self.app.defer(move |cx| {
1037 handle.update(cx, |_, cx| f(cx)).ok();
1038 });
1039 }
1040
1041 /// Subscribe to events emitted by a model or view.
1042 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1043 /// 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.
1044 pub fn subscribe<Emitter, E, Evt>(
1045 &mut self,
1046 entity: &E,
1047 mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
1048 ) -> Subscription
1049 where
1050 Emitter: EventEmitter<Evt>,
1051 E: Entity<Emitter>,
1052 Evt: 'static,
1053 {
1054 let entity_id = entity.entity_id();
1055 let entity = entity.downgrade();
1056 let window_handle = self.window.handle;
1057 self.app.new_subscription(
1058 entity_id,
1059 (
1060 TypeId::of::<Evt>(),
1061 Box::new(move |event, cx| {
1062 window_handle
1063 .update(cx, |_, cx| {
1064 if let Some(handle) = E::upgrade_from(&entity) {
1065 let event = event.downcast_ref().expect("invalid event type");
1066 on_event(handle, event, cx);
1067 true
1068 } else {
1069 false
1070 }
1071 })
1072 .unwrap_or(false)
1073 }),
1074 ),
1075 )
1076 }
1077
1078 /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
1079 /// await points in async code.
1080 pub fn to_async(&self) -> AsyncWindowContext {
1081 AsyncWindowContext::new(self.app.to_async(), self.window.handle)
1082 }
1083
1084 /// Schedule the given closure to be run directly after the current frame is rendered.
1085 pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
1086 RefCell::borrow_mut(&self.window.next_frame_callbacks).push(Box::new(callback));
1087 }
1088
1089 /// Spawn the future returned by the given closure on the application thread pool.
1090 /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
1091 /// use within your future.
1092 pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
1093 where
1094 R: 'static,
1095 Fut: Future<Output = R> + 'static,
1096 {
1097 self.app
1098 .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
1099 }
1100
1101 fn bounds_changed(&mut self) {
1102 self.window.scale_factor = self.window.platform_window.scale_factor();
1103 self.window.viewport_size = self.window.platform_window.content_size();
1104 self.window.display_id = self.window.platform_window.display().id();
1105 self.refresh();
1106
1107 self.window
1108 .bounds_observers
1109 .clone()
1110 .retain(&(), |callback| callback(self));
1111 }
1112
1113 /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
1114 pub fn bounds(&self) -> Bounds<DevicePixels> {
1115 self.window.platform_window.bounds()
1116 }
1117
1118 /// Returns whether or not the window is currently fullscreen
1119 pub fn is_fullscreen(&self) -> bool {
1120 self.window.platform_window.is_fullscreen()
1121 }
1122
1123 fn appearance_changed(&mut self) {
1124 self.window.appearance = self.window.platform_window.appearance();
1125
1126 self.window
1127 .appearance_observers
1128 .clone()
1129 .retain(&(), |callback| callback(self));
1130 }
1131
1132 /// Returns the appearance of the current window.
1133 pub fn appearance(&self) -> WindowAppearance {
1134 self.window.appearance
1135 }
1136
1137 /// Returns the size of the drawable area within the window.
1138 pub fn viewport_size(&self) -> Size<Pixels> {
1139 self.window.viewport_size
1140 }
1141
1142 /// Returns whether this window is focused by the operating system (receiving key events).
1143 pub fn is_window_active(&self) -> bool {
1144 self.window.active.get()
1145 }
1146
1147 /// Toggle zoom on the window.
1148 pub fn zoom_window(&self) {
1149 self.window.platform_window.zoom();
1150 }
1151
1152 /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland only)
1153 pub fn show_window_menu(&self, position: Point<Pixels>) {
1154 self.window.platform_window.show_window_menu(position)
1155 }
1156
1157 /// Tells the compositor to take control of window movement (Wayland only)
1158 ///
1159 /// Events may not be received during a move operation.
1160 pub fn start_system_move(&self) {
1161 self.window.platform_window.start_system_move()
1162 }
1163
1164 /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
1165 pub fn should_render_window_controls(&self) -> bool {
1166 self.window.platform_window.should_render_window_controls()
1167 }
1168
1169 /// Updates the window's title at the platform level.
1170 pub fn set_window_title(&mut self, title: &str) {
1171 self.window.platform_window.set_title(title);
1172 }
1173
1174 /// Sets the application identifier.
1175 pub fn set_app_id(&mut self, app_id: &str) {
1176 self.window.platform_window.set_app_id(app_id);
1177 }
1178
1179 /// Sets the window background appearance.
1180 pub fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance) {
1181 self.window
1182 .platform_window
1183 .set_background_appearance(background_appearance);
1184 }
1185
1186 /// Mark the window as dirty at the platform level.
1187 pub fn set_window_edited(&mut self, edited: bool) {
1188 self.window.platform_window.set_edited(edited);
1189 }
1190
1191 /// Determine the display on which the window is visible.
1192 pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1193 self.platform
1194 .displays()
1195 .into_iter()
1196 .find(|display| display.id() == self.window.display_id)
1197 }
1198
1199 /// Show the platform character palette.
1200 pub fn show_character_palette(&self) {
1201 self.window.platform_window.show_character_palette();
1202 }
1203
1204 /// The scale factor of the display associated with the window. For example, it could
1205 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
1206 /// be rendered as two pixels on screen.
1207 pub fn scale_factor(&self) -> f32 {
1208 self.window.scale_factor
1209 }
1210
1211 /// The size of an em for the base font of the application. Adjusting this value allows the
1212 /// UI to scale, just like zooming a web page.
1213 pub fn rem_size(&self) -> Pixels {
1214 self.window
1215 .rem_size_override
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 = Some(rem_size.into());
1242 let result = f(self);
1243 self.window.rem_size_override.take();
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 =
2351 self.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((size, Cow::Owned(bytes)))
2356 })?;
2357 let bounds = Bounds {
2358 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2359 size: tile.bounds.size.map(Into::into),
2360 };
2361 let content_mask = self.content_mask().scale(scale_factor);
2362 self.window
2363 .next_frame
2364 .scene
2365 .insert_primitive(MonochromeSprite {
2366 order: 0,
2367 pad: 0,
2368 bounds,
2369 content_mask,
2370 color,
2371 tile,
2372 transformation: TransformationMatrix::unit(),
2373 });
2374 }
2375 Ok(())
2376 }
2377
2378 /// Paints an emoji glyph into the scene for the next frame at the current z-index.
2379 ///
2380 /// The y component of the origin is the baseline of the glyph.
2381 /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2382 /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2383 /// This method is only useful if you need to paint a single emoji that has already been shaped.
2384 ///
2385 /// This method should only be called as part of the paint phase of element drawing.
2386 pub fn paint_emoji(
2387 &mut self,
2388 origin: Point<Pixels>,
2389 font_id: FontId,
2390 glyph_id: GlyphId,
2391 font_size: Pixels,
2392 ) -> Result<()> {
2393 debug_assert_eq!(
2394 self.window.draw_phase,
2395 DrawPhase::Paint,
2396 "this method can only be called during paint"
2397 );
2398
2399 let scale_factor = self.scale_factor();
2400 let glyph_origin = origin.scale(scale_factor);
2401 let params = RenderGlyphParams {
2402 font_id,
2403 glyph_id,
2404 font_size,
2405 // We don't render emojis with subpixel variants.
2406 subpixel_variant: Default::default(),
2407 scale_factor,
2408 is_emoji: true,
2409 };
2410
2411 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
2412 if !raster_bounds.is_zero() {
2413 let tile =
2414 self.window
2415 .sprite_atlas
2416 .get_or_insert_with(¶ms.clone().into(), &mut || {
2417 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
2418 Ok((size, Cow::Owned(bytes)))
2419 })?;
2420 let bounds = Bounds {
2421 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2422 size: tile.bounds.size.map(Into::into),
2423 };
2424 let content_mask = self.content_mask().scale(scale_factor);
2425
2426 self.window
2427 .next_frame
2428 .scene
2429 .insert_primitive(PolychromeSprite {
2430 order: 0,
2431 grayscale: false,
2432 bounds,
2433 corner_radii: Default::default(),
2434 content_mask,
2435 tile,
2436 });
2437 }
2438 Ok(())
2439 }
2440
2441 /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
2442 ///
2443 /// This method should only be called as part of the paint phase of element drawing.
2444 pub fn paint_svg(
2445 &mut self,
2446 bounds: Bounds<Pixels>,
2447 path: SharedString,
2448 transformation: TransformationMatrix,
2449 color: Hsla,
2450 ) -> Result<()> {
2451 debug_assert_eq!(
2452 self.window.draw_phase,
2453 DrawPhase::Paint,
2454 "this method can only be called during paint"
2455 );
2456
2457 let scale_factor = self.scale_factor();
2458 let bounds = bounds.scale(scale_factor);
2459 // Render the SVG at twice the size to get a higher quality result.
2460 let params = RenderSvgParams {
2461 path,
2462 size: bounds
2463 .size
2464 .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
2465 };
2466
2467 let tile =
2468 self.window
2469 .sprite_atlas
2470 .get_or_insert_with(¶ms.clone().into(), &mut || {
2471 let bytes = self.svg_renderer.render(¶ms)?;
2472 Ok((params.size, Cow::Owned(bytes)))
2473 })?;
2474 let content_mask = self.content_mask().scale(scale_factor);
2475
2476 self.window
2477 .next_frame
2478 .scene
2479 .insert_primitive(MonochromeSprite {
2480 order: 0,
2481 pad: 0,
2482 bounds,
2483 content_mask,
2484 color,
2485 tile,
2486 transformation,
2487 });
2488
2489 Ok(())
2490 }
2491
2492 /// Paint an image into the scene for the next frame at the current z-index.
2493 ///
2494 /// This method should only be called as part of the paint phase of element drawing.
2495 pub fn paint_image(
2496 &mut self,
2497 bounds: Bounds<Pixels>,
2498 corner_radii: Corners<Pixels>,
2499 data: Arc<ImageData>,
2500 grayscale: bool,
2501 ) -> Result<()> {
2502 debug_assert_eq!(
2503 self.window.draw_phase,
2504 DrawPhase::Paint,
2505 "this method can only be called during paint"
2506 );
2507
2508 let scale_factor = self.scale_factor();
2509 let bounds = bounds.scale(scale_factor);
2510 let params = RenderImageParams { image_id: data.id };
2511
2512 let tile = self
2513 .window
2514 .sprite_atlas
2515 .get_or_insert_with(¶ms.clone().into(), &mut || {
2516 Ok((data.size(), Cow::Borrowed(data.as_bytes())))
2517 })?;
2518 let content_mask = self.content_mask().scale(scale_factor);
2519 let corner_radii = corner_radii.scale(scale_factor);
2520
2521 self.window
2522 .next_frame
2523 .scene
2524 .insert_primitive(PolychromeSprite {
2525 order: 0,
2526 grayscale,
2527 bounds,
2528 content_mask,
2529 corner_radii,
2530 tile,
2531 });
2532 Ok(())
2533 }
2534
2535 /// Paint a surface into the scene for the next frame at the current z-index.
2536 ///
2537 /// This method should only be called as part of the paint phase of element drawing.
2538 #[cfg(target_os = "macos")]
2539 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
2540 debug_assert_eq!(
2541 self.window.draw_phase,
2542 DrawPhase::Paint,
2543 "this method can only be called during paint"
2544 );
2545
2546 let scale_factor = self.scale_factor();
2547 let bounds = bounds.scale(scale_factor);
2548 let content_mask = self.content_mask().scale(scale_factor);
2549 self.window
2550 .next_frame
2551 .scene
2552 .insert_primitive(crate::Surface {
2553 order: 0,
2554 bounds,
2555 content_mask,
2556 image_buffer,
2557 });
2558 }
2559
2560 #[must_use]
2561 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
2562 /// layout is being requested, along with the layout ids of any children. This method is called during
2563 /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
2564 ///
2565 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2566 pub fn request_layout(
2567 &mut self,
2568 style: Style,
2569 children: impl IntoIterator<Item = LayoutId>,
2570 ) -> LayoutId {
2571 debug_assert_eq!(
2572 self.window.draw_phase,
2573 DrawPhase::Prepaint,
2574 "this method can only be called during request_layout, or prepaint"
2575 );
2576
2577 self.app.layout_id_buffer.clear();
2578 self.app.layout_id_buffer.extend(children);
2579 let rem_size = self.rem_size();
2580
2581 self.window.layout_engine.as_mut().unwrap().request_layout(
2582 style,
2583 rem_size,
2584 &self.app.layout_id_buffer,
2585 )
2586 }
2587
2588 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
2589 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
2590 /// determine the element's size. One place this is used internally is when measuring text.
2591 ///
2592 /// The given closure is invoked at layout time with the known dimensions and available space and
2593 /// returns a `Size`.
2594 ///
2595 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2596 pub fn request_measured_layout<
2597 F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
2598 + 'static,
2599 >(
2600 &mut self,
2601 style: Style,
2602 measure: F,
2603 ) -> LayoutId {
2604 debug_assert_eq!(
2605 self.window.draw_phase,
2606 DrawPhase::Prepaint,
2607 "this method can only be called during request_layout, or prepaint"
2608 );
2609
2610 let rem_size = self.rem_size();
2611 self.window
2612 .layout_engine
2613 .as_mut()
2614 .unwrap()
2615 .request_measured_layout(style, rem_size, measure)
2616 }
2617
2618 /// Compute the layout for the given id within the given available space.
2619 /// This method is called for its side effect, typically by the framework prior to painting.
2620 /// After calling it, you can request the bounds of the given layout node id or any descendant.
2621 ///
2622 /// This method should only be called as part of the prepaint phase of element drawing.
2623 pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
2624 debug_assert_eq!(
2625 self.window.draw_phase,
2626 DrawPhase::Prepaint,
2627 "this method can only be called during request_layout, or prepaint"
2628 );
2629
2630 let mut layout_engine = self.window.layout_engine.take().unwrap();
2631 layout_engine.compute_layout(layout_id, available_space, self);
2632 self.window.layout_engine = Some(layout_engine);
2633 }
2634
2635 /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
2636 /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
2637 ///
2638 /// This method should only be called as part of element drawing.
2639 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
2640 debug_assert_eq!(
2641 self.window.draw_phase,
2642 DrawPhase::Prepaint,
2643 "this method can only be called during request_layout, prepaint, or paint"
2644 );
2645
2646 let mut bounds = self
2647 .window
2648 .layout_engine
2649 .as_mut()
2650 .unwrap()
2651 .layout_bounds(layout_id)
2652 .map(Into::into);
2653 bounds.origin += self.element_offset();
2654 bounds
2655 }
2656
2657 /// This method should be called during `prepaint`. You can use
2658 /// the returned [Hitbox] during `paint` or in an event handler
2659 /// to determine whether the inserted hitbox was the topmost.
2660 ///
2661 /// This method should only be called as part of the prepaint phase of element drawing.
2662 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, opaque: bool) -> Hitbox {
2663 debug_assert_eq!(
2664 self.window.draw_phase,
2665 DrawPhase::Prepaint,
2666 "this method can only be called during prepaint"
2667 );
2668
2669 let content_mask = self.content_mask();
2670 let window = &mut self.window;
2671 let id = window.next_hitbox_id;
2672 window.next_hitbox_id.0 += 1;
2673 let hitbox = Hitbox {
2674 id,
2675 bounds,
2676 content_mask,
2677 opaque,
2678 };
2679 window.next_frame.hitboxes.push(hitbox.clone());
2680 hitbox
2681 }
2682
2683 /// Sets the key context for the current element. This context will be used to translate
2684 /// keybindings into actions.
2685 ///
2686 /// This method should only be called as part of the paint phase of element drawing.
2687 pub fn set_key_context(&mut self, context: KeyContext) {
2688 debug_assert_eq!(
2689 self.window.draw_phase,
2690 DrawPhase::Paint,
2691 "this method can only be called during paint"
2692 );
2693 self.window
2694 .next_frame
2695 .dispatch_tree
2696 .set_key_context(context);
2697 }
2698
2699 /// Sets the focus handle for the current element. This handle will be used to manage focus state
2700 /// and keyboard event dispatch for the element.
2701 ///
2702 /// This method should only be called as part of the paint phase of element drawing.
2703 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle) {
2704 debug_assert_eq!(
2705 self.window.draw_phase,
2706 DrawPhase::Paint,
2707 "this method can only be called during paint"
2708 );
2709 self.window
2710 .next_frame
2711 .dispatch_tree
2712 .set_focus_id(focus_handle.id);
2713 }
2714
2715 /// Sets the view id for the current element, which will be used to manage view caching.
2716 ///
2717 /// This method should only be called as part of element prepaint. We plan on removing this
2718 /// method eventually when we solve some issues that require us to construct editor elements
2719 /// directly instead of always using editors via views.
2720 pub fn set_view_id(&mut self, view_id: EntityId) {
2721 debug_assert_eq!(
2722 self.window.draw_phase,
2723 DrawPhase::Prepaint,
2724 "this method can only be called during prepaint"
2725 );
2726 self.window.next_frame.dispatch_tree.set_view_id(view_id);
2727 }
2728
2729 /// Get the last view id for the current element
2730 pub fn parent_view_id(&mut self) -> Option<EntityId> {
2731 self.window.next_frame.dispatch_tree.parent_view_id()
2732 }
2733
2734 /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
2735 /// platform to receive textual input with proper integration with concerns such
2736 /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
2737 /// rendered.
2738 ///
2739 /// This method should only be called as part of the paint phase of element drawing.
2740 ///
2741 /// [element_input_handler]: crate::ElementInputHandler
2742 pub fn handle_input(&mut self, focus_handle: &FocusHandle, input_handler: impl InputHandler) {
2743 debug_assert_eq!(
2744 self.window.draw_phase,
2745 DrawPhase::Paint,
2746 "this method can only be called during paint"
2747 );
2748
2749 if focus_handle.is_focused(self) {
2750 let cx = self.to_async();
2751 self.window
2752 .next_frame
2753 .input_handlers
2754 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
2755 }
2756 }
2757
2758 /// Register a mouse event listener on the window for the next frame. The type of event
2759 /// is determined by the first parameter of the given listener. When the next frame is rendered
2760 /// the listener will be cleared.
2761 ///
2762 /// This method should only be called as part of the paint phase of element drawing.
2763 pub fn on_mouse_event<Event: MouseEvent>(
2764 &mut self,
2765 mut handler: impl FnMut(&Event, DispatchPhase, &mut WindowContext) + 'static,
2766 ) {
2767 debug_assert_eq!(
2768 self.window.draw_phase,
2769 DrawPhase::Paint,
2770 "this method can only be called during paint"
2771 );
2772
2773 self.window.next_frame.mouse_listeners.push(Some(Box::new(
2774 move |event: &dyn Any, phase: DispatchPhase, cx: &mut WindowContext<'_>| {
2775 if let Some(event) = event.downcast_ref() {
2776 handler(event, phase, cx)
2777 }
2778 },
2779 )));
2780 }
2781
2782 /// Register a key event listener on the window for the next frame. The type of event
2783 /// is determined by the first parameter of the given listener. When the next frame is rendered
2784 /// the listener will be cleared.
2785 ///
2786 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2787 /// a specific need to register a global listener.
2788 ///
2789 /// This method should only be called as part of the paint phase of element drawing.
2790 pub fn on_key_event<Event: KeyEvent>(
2791 &mut self,
2792 listener: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
2793 ) {
2794 debug_assert_eq!(
2795 self.window.draw_phase,
2796 DrawPhase::Paint,
2797 "this method can only be called during paint"
2798 );
2799
2800 self.window.next_frame.dispatch_tree.on_key_event(Rc::new(
2801 move |event: &dyn Any, phase, cx: &mut WindowContext<'_>| {
2802 if let Some(event) = event.downcast_ref::<Event>() {
2803 listener(event, phase, cx)
2804 }
2805 },
2806 ));
2807 }
2808
2809 /// Register a modifiers changed event listener on the window for the next frame.
2810 ///
2811 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2812 /// a specific need to register a global listener.
2813 ///
2814 /// This method should only be called as part of the paint phase of element drawing.
2815 pub fn on_modifiers_changed(
2816 &mut self,
2817 listener: impl Fn(&ModifiersChangedEvent, &mut WindowContext) + 'static,
2818 ) {
2819 debug_assert_eq!(
2820 self.window.draw_phase,
2821 DrawPhase::Paint,
2822 "this method can only be called during paint"
2823 );
2824
2825 self.window
2826 .next_frame
2827 .dispatch_tree
2828 .on_modifiers_changed(Rc::new(
2829 move |event: &ModifiersChangedEvent, cx: &mut WindowContext<'_>| {
2830 listener(event, cx)
2831 },
2832 ));
2833 }
2834
2835 fn reset_cursor_style(&self) {
2836 // Set the cursor only if we're the active window.
2837 if self.is_window_active() {
2838 let style = self
2839 .window
2840 .rendered_frame
2841 .cursor_styles
2842 .iter()
2843 .rev()
2844 .find(|request| request.hitbox_id.is_hovered(self))
2845 .map(|request| request.style)
2846 .unwrap_or(CursorStyle::Arrow);
2847 self.platform.set_cursor_style(style);
2848 }
2849 }
2850
2851 /// Dispatch a given keystroke as though the user had typed it.
2852 /// You can create a keystroke with Keystroke::parse("").
2853 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke) -> bool {
2854 let keystroke = keystroke.with_simulated_ime();
2855 let result = self.dispatch_event(PlatformInput::KeyDown(KeyDownEvent {
2856 keystroke: keystroke.clone(),
2857 is_held: false,
2858 }));
2859 if !result.propagate {
2860 return true;
2861 }
2862
2863 if let Some(input) = keystroke.ime_key {
2864 if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
2865 input_handler.dispatch_input(&input, self);
2866 self.window.platform_window.set_input_handler(input_handler);
2867 return true;
2868 }
2869 }
2870
2871 false
2872 }
2873
2874 /// Represent this action as a key binding string, to display in the UI.
2875 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
2876 self.bindings_for_action(action)
2877 .into_iter()
2878 .next()
2879 .map(|binding| {
2880 binding
2881 .keystrokes()
2882 .iter()
2883 .map(ToString::to_string)
2884 .collect::<Vec<_>>()
2885 .join(" ")
2886 })
2887 .unwrap_or_else(|| action.name().to_string())
2888 }
2889
2890 /// Dispatch a mouse or keyboard event on the window.
2891 #[profiling::function]
2892 pub fn dispatch_event(&mut self, event: PlatformInput) -> DispatchEventResult {
2893 self.window.last_input_timestamp.set(Instant::now());
2894 // Handlers may set this to false by calling `stop_propagation`.
2895 self.app.propagate_event = true;
2896 // Handlers may set this to true by calling `prevent_default`.
2897 self.window.default_prevented = false;
2898
2899 let event = match event {
2900 // Track the mouse position with our own state, since accessing the platform
2901 // API for the mouse position can only occur on the main thread.
2902 PlatformInput::MouseMove(mouse_move) => {
2903 self.window.mouse_position = mouse_move.position;
2904 self.window.modifiers = mouse_move.modifiers;
2905 PlatformInput::MouseMove(mouse_move)
2906 }
2907 PlatformInput::MouseDown(mouse_down) => {
2908 self.window.mouse_position = mouse_down.position;
2909 self.window.modifiers = mouse_down.modifiers;
2910 PlatformInput::MouseDown(mouse_down)
2911 }
2912 PlatformInput::MouseUp(mouse_up) => {
2913 self.window.mouse_position = mouse_up.position;
2914 self.window.modifiers = mouse_up.modifiers;
2915 PlatformInput::MouseUp(mouse_up)
2916 }
2917 PlatformInput::MouseExited(mouse_exited) => {
2918 self.window.modifiers = mouse_exited.modifiers;
2919 PlatformInput::MouseExited(mouse_exited)
2920 }
2921 PlatformInput::ModifiersChanged(modifiers_changed) => {
2922 self.window.modifiers = modifiers_changed.modifiers;
2923 PlatformInput::ModifiersChanged(modifiers_changed)
2924 }
2925 PlatformInput::ScrollWheel(scroll_wheel) => {
2926 self.window.mouse_position = scroll_wheel.position;
2927 self.window.modifiers = scroll_wheel.modifiers;
2928 PlatformInput::ScrollWheel(scroll_wheel)
2929 }
2930 // Translate dragging and dropping of external files from the operating system
2931 // to internal drag and drop events.
2932 PlatformInput::FileDrop(file_drop) => match file_drop {
2933 FileDropEvent::Entered { position, paths } => {
2934 self.window.mouse_position = position;
2935 if self.active_drag.is_none() {
2936 self.active_drag = Some(AnyDrag {
2937 value: Box::new(paths.clone()),
2938 view: self.new_view(|_| paths).into(),
2939 cursor_offset: position,
2940 });
2941 }
2942 PlatformInput::MouseMove(MouseMoveEvent {
2943 position,
2944 pressed_button: Some(MouseButton::Left),
2945 modifiers: Modifiers::default(),
2946 })
2947 }
2948 FileDropEvent::Pending { position } => {
2949 self.window.mouse_position = position;
2950 PlatformInput::MouseMove(MouseMoveEvent {
2951 position,
2952 pressed_button: Some(MouseButton::Left),
2953 modifiers: Modifiers::default(),
2954 })
2955 }
2956 FileDropEvent::Submit { position } => {
2957 self.activate(true);
2958 self.window.mouse_position = position;
2959 PlatformInput::MouseUp(MouseUpEvent {
2960 button: MouseButton::Left,
2961 position,
2962 modifiers: Modifiers::default(),
2963 click_count: 1,
2964 })
2965 }
2966 FileDropEvent::Exited => {
2967 self.active_drag.take();
2968 PlatformInput::FileDrop(FileDropEvent::Exited)
2969 }
2970 },
2971 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
2972 };
2973
2974 if let Some(any_mouse_event) = event.mouse_event() {
2975 self.dispatch_mouse_event(any_mouse_event);
2976 } else if let Some(any_key_event) = event.keyboard_event() {
2977 self.dispatch_key_event(any_key_event);
2978 }
2979
2980 DispatchEventResult {
2981 propagate: self.app.propagate_event,
2982 default_prevented: self.window.default_prevented,
2983 }
2984 }
2985
2986 fn dispatch_mouse_event(&mut self, event: &dyn Any) {
2987 let hit_test = self.window.rendered_frame.hit_test(self.mouse_position());
2988 if hit_test != self.window.mouse_hit_test {
2989 self.window.mouse_hit_test = hit_test;
2990 self.reset_cursor_style();
2991 }
2992
2993 let mut mouse_listeners = mem::take(&mut self.window.rendered_frame.mouse_listeners);
2994
2995 // Capture phase, events bubble from back to front. Handlers for this phase are used for
2996 // special purposes, such as detecting events outside of a given Bounds.
2997 for listener in &mut mouse_listeners {
2998 let listener = listener.as_mut().unwrap();
2999 listener(event, DispatchPhase::Capture, self);
3000 if !self.app.propagate_event {
3001 break;
3002 }
3003 }
3004
3005 // Bubble phase, where most normal handlers do their work.
3006 if self.app.propagate_event {
3007 for listener in mouse_listeners.iter_mut().rev() {
3008 let listener = listener.as_mut().unwrap();
3009 listener(event, DispatchPhase::Bubble, self);
3010 if !self.app.propagate_event {
3011 break;
3012 }
3013 }
3014 }
3015
3016 self.window.rendered_frame.mouse_listeners = mouse_listeners;
3017
3018 if self.has_active_drag() {
3019 if event.is::<MouseMoveEvent>() {
3020 // If this was a mouse move event, redraw the window so that the
3021 // active drag can follow the mouse cursor.
3022 self.refresh();
3023 } else if event.is::<MouseUpEvent>() {
3024 // If this was a mouse up event, cancel the active drag and redraw
3025 // the window.
3026 self.active_drag = None;
3027 self.refresh();
3028 }
3029 }
3030 }
3031
3032 fn dispatch_key_event(&mut self, event: &dyn Any) {
3033 if self.window.dirty.get() {
3034 self.draw();
3035 }
3036
3037 let node_id = self
3038 .window
3039 .focus
3040 .and_then(|focus_id| {
3041 self.window
3042 .rendered_frame
3043 .dispatch_tree
3044 .focusable_node_id(focus_id)
3045 })
3046 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3047
3048 let dispatch_path = self
3049 .window
3050 .rendered_frame
3051 .dispatch_tree
3052 .dispatch_path(node_id);
3053
3054 if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3055 let KeymatchResult { bindings, pending } = self
3056 .window
3057 .rendered_frame
3058 .dispatch_tree
3059 .dispatch_key(&key_down_event.keystroke, &dispatch_path);
3060
3061 if pending {
3062 let mut currently_pending = self.window.pending_input.take().unwrap_or_default();
3063 if currently_pending.focus.is_some() && currently_pending.focus != self.window.focus
3064 {
3065 currently_pending = PendingInput::default();
3066 }
3067 currently_pending.focus = self.window.focus;
3068 currently_pending
3069 .keystrokes
3070 .push(key_down_event.keystroke.clone());
3071 for binding in bindings {
3072 currently_pending.bindings.push(binding);
3073 }
3074
3075 currently_pending.timer = Some(self.spawn(|mut cx| async move {
3076 cx.background_executor.timer(Duration::from_secs(1)).await;
3077 cx.update(move |cx| {
3078 cx.clear_pending_keystrokes();
3079 let Some(currently_pending) = cx.window.pending_input.take() else {
3080 return;
3081 };
3082 cx.replay_pending_input(currently_pending)
3083 })
3084 .log_err();
3085 }));
3086
3087 self.window.pending_input = Some(currently_pending);
3088
3089 self.propagate_event = false;
3090 return;
3091 } else if let Some(currently_pending) = self.window.pending_input.take() {
3092 if bindings
3093 .iter()
3094 .all(|binding| !currently_pending.used_by_binding(binding))
3095 {
3096 self.replay_pending_input(currently_pending)
3097 }
3098 }
3099
3100 if !bindings.is_empty() {
3101 self.clear_pending_keystrokes();
3102 }
3103
3104 self.propagate_event = true;
3105 for binding in bindings {
3106 self.dispatch_action_on_node(node_id, binding.action.as_ref());
3107 if !self.propagate_event {
3108 self.dispatch_keystroke_observers(event, Some(binding.action));
3109 return;
3110 }
3111 }
3112 }
3113
3114 self.dispatch_key_down_up_event(event, &dispatch_path);
3115 if !self.propagate_event {
3116 return;
3117 }
3118
3119 self.dispatch_modifiers_changed_event(event, &dispatch_path);
3120 if !self.propagate_event {
3121 return;
3122 }
3123
3124 self.dispatch_keystroke_observers(event, None);
3125 }
3126
3127 fn dispatch_key_down_up_event(
3128 &mut self,
3129 event: &dyn Any,
3130 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3131 ) {
3132 // Capture phase
3133 for node_id in dispatch_path {
3134 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3135
3136 for key_listener in node.key_listeners.clone() {
3137 key_listener(event, DispatchPhase::Capture, self);
3138 if !self.propagate_event {
3139 return;
3140 }
3141 }
3142 }
3143
3144 // Bubble phase
3145 for node_id in dispatch_path.iter().rev() {
3146 // Handle low level key events
3147 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3148 for key_listener in node.key_listeners.clone() {
3149 key_listener(event, DispatchPhase::Bubble, self);
3150 if !self.propagate_event {
3151 return;
3152 }
3153 }
3154 }
3155 }
3156
3157 fn dispatch_modifiers_changed_event(
3158 &mut self,
3159 event: &dyn Any,
3160 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3161 ) {
3162 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
3163 return;
3164 };
3165 for node_id in dispatch_path.iter().rev() {
3166 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3167 for listener in node.modifiers_changed_listeners.clone() {
3168 listener(event, self);
3169 if !self.propagate_event {
3170 return;
3171 }
3172 }
3173 }
3174 }
3175
3176 /// Determine whether a potential multi-stroke key binding is in progress on this window.
3177 pub fn has_pending_keystrokes(&self) -> bool {
3178 self.window
3179 .rendered_frame
3180 .dispatch_tree
3181 .has_pending_keystrokes()
3182 }
3183
3184 fn replay_pending_input(&mut self, currently_pending: PendingInput) {
3185 let node_id = self
3186 .window
3187 .focus
3188 .and_then(|focus_id| {
3189 self.window
3190 .rendered_frame
3191 .dispatch_tree
3192 .focusable_node_id(focus_id)
3193 })
3194 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3195
3196 if self.window.focus != currently_pending.focus {
3197 return;
3198 }
3199
3200 let input = currently_pending.input();
3201
3202 self.propagate_event = true;
3203 for binding in currently_pending.bindings {
3204 self.dispatch_action_on_node(node_id, binding.action.as_ref());
3205 if !self.propagate_event {
3206 return;
3207 }
3208 }
3209
3210 let dispatch_path = self
3211 .window
3212 .rendered_frame
3213 .dispatch_tree
3214 .dispatch_path(node_id);
3215
3216 for keystroke in currently_pending.keystrokes {
3217 let event = KeyDownEvent {
3218 keystroke,
3219 is_held: false,
3220 };
3221
3222 self.dispatch_key_down_up_event(&event, &dispatch_path);
3223 if !self.propagate_event {
3224 return;
3225 }
3226 }
3227
3228 if !input.is_empty() {
3229 if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
3230 input_handler.dispatch_input(&input, self);
3231 self.window.platform_window.set_input_handler(input_handler)
3232 }
3233 }
3234 }
3235
3236 fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: &dyn Action) {
3237 let dispatch_path = self
3238 .window
3239 .rendered_frame
3240 .dispatch_tree
3241 .dispatch_path(node_id);
3242
3243 // Capture phase for global actions.
3244 self.propagate_event = true;
3245 if let Some(mut global_listeners) = self
3246 .global_action_listeners
3247 .remove(&action.as_any().type_id())
3248 {
3249 for listener in &global_listeners {
3250 listener(action.as_any(), DispatchPhase::Capture, self);
3251 if !self.propagate_event {
3252 break;
3253 }
3254 }
3255
3256 global_listeners.extend(
3257 self.global_action_listeners
3258 .remove(&action.as_any().type_id())
3259 .unwrap_or_default(),
3260 );
3261
3262 self.global_action_listeners
3263 .insert(action.as_any().type_id(), global_listeners);
3264 }
3265
3266 if !self.propagate_event {
3267 return;
3268 }
3269
3270 // Capture phase for window actions.
3271 for node_id in &dispatch_path {
3272 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3273 for DispatchActionListener {
3274 action_type,
3275 listener,
3276 } in node.action_listeners.clone()
3277 {
3278 let any_action = action.as_any();
3279 if action_type == any_action.type_id() {
3280 listener(any_action, DispatchPhase::Capture, self);
3281
3282 if !self.propagate_event {
3283 return;
3284 }
3285 }
3286 }
3287 }
3288
3289 // Bubble phase for window actions.
3290 for node_id in dispatch_path.iter().rev() {
3291 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3292 for DispatchActionListener {
3293 action_type,
3294 listener,
3295 } in node.action_listeners.clone()
3296 {
3297 let any_action = action.as_any();
3298 if action_type == any_action.type_id() {
3299 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3300 listener(any_action, DispatchPhase::Bubble, self);
3301
3302 if !self.propagate_event {
3303 return;
3304 }
3305 }
3306 }
3307 }
3308
3309 // Bubble phase for global actions.
3310 if let Some(mut global_listeners) = self
3311 .global_action_listeners
3312 .remove(&action.as_any().type_id())
3313 {
3314 for listener in global_listeners.iter().rev() {
3315 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3316
3317 listener(action.as_any(), DispatchPhase::Bubble, self);
3318 if !self.propagate_event {
3319 break;
3320 }
3321 }
3322
3323 global_listeners.extend(
3324 self.global_action_listeners
3325 .remove(&action.as_any().type_id())
3326 .unwrap_or_default(),
3327 );
3328
3329 self.global_action_listeners
3330 .insert(action.as_any().type_id(), global_listeners);
3331 }
3332 }
3333
3334 /// Register the given handler to be invoked whenever the global of the given type
3335 /// is updated.
3336 pub fn observe_global<G: Global>(
3337 &mut self,
3338 f: impl Fn(&mut WindowContext<'_>) + 'static,
3339 ) -> Subscription {
3340 let window_handle = self.window.handle;
3341 let (subscription, activate) = self.global_observers.insert(
3342 TypeId::of::<G>(),
3343 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
3344 );
3345 self.app.defer(move |_| activate());
3346 subscription
3347 }
3348
3349 /// Focus the current window and bring it to the foreground at the platform level.
3350 pub fn activate_window(&self) {
3351 self.window.platform_window.activate();
3352 }
3353
3354 /// Minimize the current window at the platform level.
3355 pub fn minimize_window(&self) {
3356 self.window.platform_window.minimize();
3357 }
3358
3359 /// Toggle full screen status on the current window at the platform level.
3360 pub fn toggle_fullscreen(&self) {
3361 self.window.platform_window.toggle_fullscreen();
3362 }
3363
3364 /// Present a platform dialog.
3365 /// The provided message will be presented, along with buttons for each answer.
3366 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
3367 pub fn prompt(
3368 &mut self,
3369 level: PromptLevel,
3370 message: &str,
3371 detail: Option<&str>,
3372 answers: &[&str],
3373 ) -> oneshot::Receiver<usize> {
3374 let prompt_builder = self.app.prompt_builder.take();
3375 let Some(prompt_builder) = prompt_builder else {
3376 unreachable!("Re-entrant window prompting is not supported by GPUI");
3377 };
3378
3379 let receiver = match &prompt_builder {
3380 PromptBuilder::Default => self
3381 .window
3382 .platform_window
3383 .prompt(level, message, detail, answers)
3384 .unwrap_or_else(|| {
3385 self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3386 }),
3387 PromptBuilder::Custom(_) => {
3388 self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3389 }
3390 };
3391
3392 self.app.prompt_builder = Some(prompt_builder);
3393
3394 receiver
3395 }
3396
3397 fn build_custom_prompt(
3398 &mut self,
3399 prompt_builder: &PromptBuilder,
3400 level: PromptLevel,
3401 message: &str,
3402 detail: Option<&str>,
3403 answers: &[&str],
3404 ) -> oneshot::Receiver<usize> {
3405 let (sender, receiver) = oneshot::channel();
3406 let handle = PromptHandle::new(sender);
3407 let handle = (prompt_builder)(level, message, detail, answers, handle, self);
3408 self.window.prompt = Some(handle);
3409 receiver
3410 }
3411
3412 /// Returns all available actions for the focused element.
3413 pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
3414 let node_id = self
3415 .window
3416 .focus
3417 .and_then(|focus_id| {
3418 self.window
3419 .rendered_frame
3420 .dispatch_tree
3421 .focusable_node_id(focus_id)
3422 })
3423 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3424
3425 let mut actions = self
3426 .window
3427 .rendered_frame
3428 .dispatch_tree
3429 .available_actions(node_id);
3430 for action_type in self.global_action_listeners.keys() {
3431 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
3432 let action = self.actions.build_action_type(action_type).ok();
3433 if let Some(action) = action {
3434 actions.insert(ix, action);
3435 }
3436 }
3437 }
3438 actions
3439 }
3440
3441 /// Returns key bindings that invoke the given action on the currently focused element.
3442 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
3443 self.window
3444 .rendered_frame
3445 .dispatch_tree
3446 .bindings_for_action(
3447 action,
3448 &self.window.rendered_frame.dispatch_tree.context_stack,
3449 )
3450 }
3451
3452 /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
3453 pub fn bindings_for_action_in(
3454 &self,
3455 action: &dyn Action,
3456 focus_handle: &FocusHandle,
3457 ) -> Vec<KeyBinding> {
3458 let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
3459
3460 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
3461 return vec![];
3462 };
3463 let context_stack: Vec<_> = dispatch_tree
3464 .dispatch_path(node_id)
3465 .into_iter()
3466 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
3467 .collect();
3468 dispatch_tree.bindings_for_action(action, &context_stack)
3469 }
3470
3471 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
3472 pub fn listener_for<V: Render, E>(
3473 &self,
3474 view: &View<V>,
3475 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
3476 ) -> impl Fn(&E, &mut WindowContext) + 'static {
3477 let view = view.downgrade();
3478 move |e: &E, cx: &mut WindowContext| {
3479 view.update(cx, |view, cx| f(view, e, cx)).ok();
3480 }
3481 }
3482
3483 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
3484 pub fn handler_for<V: Render>(
3485 &self,
3486 view: &View<V>,
3487 f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
3488 ) -> impl Fn(&mut WindowContext) {
3489 let view = view.downgrade();
3490 move |cx: &mut WindowContext| {
3491 view.update(cx, |view, cx| f(view, cx)).ok();
3492 }
3493 }
3494
3495 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
3496 /// If the callback returns false, the window won't be closed.
3497 pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
3498 let mut this = self.to_async();
3499 self.window
3500 .platform_window
3501 .on_should_close(Box::new(move || this.update(|cx| f(cx)).unwrap_or(true)))
3502 }
3503
3504 /// Register an action listener on the window for the next frame. The type of action
3505 /// is determined by the first parameter of the given listener. When the next frame is rendered
3506 /// the listener will be cleared.
3507 ///
3508 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
3509 /// a specific need to register a global listener.
3510 pub fn on_action(
3511 &mut self,
3512 action_type: TypeId,
3513 listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
3514 ) {
3515 self.window
3516 .next_frame
3517 .dispatch_tree
3518 .on_action(action_type, Rc::new(listener));
3519 }
3520}
3521
3522#[cfg(target_os = "windows")]
3523impl WindowContext<'_> {
3524 /// Returns the raw HWND handle for the window.
3525 pub fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND {
3526 self.window.platform_window.get_raw_handle()
3527 }
3528}
3529
3530impl Context for WindowContext<'_> {
3531 type Result<T> = T;
3532
3533 fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
3534 where
3535 T: 'static,
3536 {
3537 let slot = self.app.entities.reserve();
3538 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
3539 self.entities.insert(slot, model)
3540 }
3541
3542 fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
3543 self.app.reserve_model()
3544 }
3545
3546 fn insert_model<T: 'static>(
3547 &mut self,
3548 reservation: crate::Reservation<T>,
3549 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
3550 ) -> Self::Result<Model<T>> {
3551 self.app.insert_model(reservation, build_model)
3552 }
3553
3554 fn update_model<T: 'static, R>(
3555 &mut self,
3556 model: &Model<T>,
3557 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
3558 ) -> R {
3559 let mut entity = self.entities.lease(model);
3560 let result = update(
3561 &mut *entity,
3562 &mut ModelContext::new(&mut *self.app, model.downgrade()),
3563 );
3564 self.entities.end_lease(entity);
3565 result
3566 }
3567
3568 fn read_model<T, R>(
3569 &self,
3570 handle: &Model<T>,
3571 read: impl FnOnce(&T, &AppContext) -> R,
3572 ) -> Self::Result<R>
3573 where
3574 T: 'static,
3575 {
3576 let entity = self.entities.read(handle);
3577 read(entity, &*self.app)
3578 }
3579
3580 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
3581 where
3582 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
3583 {
3584 if window == self.window.handle {
3585 let root_view = self.window.root_view.clone().unwrap();
3586 Ok(update(root_view, self))
3587 } else {
3588 window.update(self.app, update)
3589 }
3590 }
3591
3592 fn read_window<T, R>(
3593 &self,
3594 window: &WindowHandle<T>,
3595 read: impl FnOnce(View<T>, &AppContext) -> R,
3596 ) -> Result<R>
3597 where
3598 T: 'static,
3599 {
3600 if window.any_handle == self.window.handle {
3601 let root_view = self
3602 .window
3603 .root_view
3604 .clone()
3605 .unwrap()
3606 .downcast::<T>()
3607 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3608 Ok(read(root_view, self))
3609 } else {
3610 self.app.read_window(window, read)
3611 }
3612 }
3613}
3614
3615impl VisualContext for WindowContext<'_> {
3616 fn new_view<V>(
3617 &mut self,
3618 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3619 ) -> Self::Result<View<V>>
3620 where
3621 V: 'static + Render,
3622 {
3623 let slot = self.app.entities.reserve();
3624 let view = View {
3625 model: slot.clone(),
3626 };
3627 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
3628 let entity = build_view_state(&mut cx);
3629 cx.entities.insert(slot, entity);
3630
3631 // Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
3632 fn notify_observers(cx: &mut WindowContext, tid: TypeId, view: AnyView) {
3633 cx.new_view_observers.clone().retain(&tid, |observer| {
3634 let any_view = view.clone();
3635 (observer)(any_view, cx);
3636 true
3637 });
3638 }
3639 notify_observers(self, TypeId::of::<V>(), AnyView::from(view.clone()));
3640
3641 view
3642 }
3643
3644 /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
3645 fn update_view<T: 'static, R>(
3646 &mut self,
3647 view: &View<T>,
3648 update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
3649 ) -> Self::Result<R> {
3650 let mut lease = self.app.entities.lease(&view.model);
3651 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
3652 let result = update(&mut *lease, &mut cx);
3653 cx.app.entities.end_lease(lease);
3654 result
3655 }
3656
3657 fn replace_root_view<V>(
3658 &mut self,
3659 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3660 ) -> Self::Result<View<V>>
3661 where
3662 V: 'static + Render,
3663 {
3664 let view = self.new_view(build_view);
3665 self.window.root_view = Some(view.clone().into());
3666 self.refresh();
3667 view
3668 }
3669
3670 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
3671 self.update_view(view, |view, cx| {
3672 view.focus_handle(cx).clone().focus(cx);
3673 })
3674 }
3675
3676 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
3677 where
3678 V: ManagedView,
3679 {
3680 self.update_view(view, |_, cx| cx.emit(DismissEvent))
3681 }
3682}
3683
3684impl<'a> std::ops::Deref for WindowContext<'a> {
3685 type Target = AppContext;
3686
3687 fn deref(&self) -> &Self::Target {
3688 self.app
3689 }
3690}
3691
3692impl<'a> std::ops::DerefMut for WindowContext<'a> {
3693 fn deref_mut(&mut self) -> &mut Self::Target {
3694 self.app
3695 }
3696}
3697
3698impl<'a> Borrow<AppContext> for WindowContext<'a> {
3699 fn borrow(&self) -> &AppContext {
3700 self.app
3701 }
3702}
3703
3704impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
3705 fn borrow_mut(&mut self) -> &mut AppContext {
3706 self.app
3707 }
3708}
3709
3710/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
3711pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
3712 #[doc(hidden)]
3713 fn app_mut(&mut self) -> &mut AppContext {
3714 self.borrow_mut()
3715 }
3716
3717 #[doc(hidden)]
3718 fn app(&self) -> &AppContext {
3719 self.borrow()
3720 }
3721
3722 #[doc(hidden)]
3723 fn window(&self) -> &Window {
3724 self.borrow()
3725 }
3726
3727 #[doc(hidden)]
3728 fn window_mut(&mut self) -> &mut Window {
3729 self.borrow_mut()
3730 }
3731}
3732
3733impl Borrow<Window> for WindowContext<'_> {
3734 fn borrow(&self) -> &Window {
3735 self.window
3736 }
3737}
3738
3739impl BorrowMut<Window> for WindowContext<'_> {
3740 fn borrow_mut(&mut self) -> &mut Window {
3741 self.window
3742 }
3743}
3744
3745impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
3746
3747/// Provides access to application state that is specialized for a particular [`View`].
3748/// Allows you to interact with focus, emit events, etc.
3749/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
3750/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
3751pub struct ViewContext<'a, V> {
3752 window_cx: WindowContext<'a>,
3753 view: &'a View<V>,
3754}
3755
3756impl<V> Borrow<AppContext> for ViewContext<'_, V> {
3757 fn borrow(&self) -> &AppContext {
3758 &*self.window_cx.app
3759 }
3760}
3761
3762impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
3763 fn borrow_mut(&mut self) -> &mut AppContext {
3764 &mut *self.window_cx.app
3765 }
3766}
3767
3768impl<V> Borrow<Window> for ViewContext<'_, V> {
3769 fn borrow(&self) -> &Window {
3770 &*self.window_cx.window
3771 }
3772}
3773
3774impl<V> BorrowMut<Window> for ViewContext<'_, V> {
3775 fn borrow_mut(&mut self) -> &mut Window {
3776 &mut *self.window_cx.window
3777 }
3778}
3779
3780impl<'a, V: 'static> ViewContext<'a, V> {
3781 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
3782 Self {
3783 window_cx: WindowContext::new(app, window),
3784 view,
3785 }
3786 }
3787
3788 /// Get the entity_id of this view.
3789 pub fn entity_id(&self) -> EntityId {
3790 self.view.entity_id()
3791 }
3792
3793 /// Get the view pointer underlying this context.
3794 pub fn view(&self) -> &View<V> {
3795 self.view
3796 }
3797
3798 /// Get the model underlying this view.
3799 pub fn model(&self) -> &Model<V> {
3800 &self.view.model
3801 }
3802
3803 /// Access the underlying window context.
3804 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
3805 &mut self.window_cx
3806 }
3807
3808 /// Sets a given callback to be run on the next frame.
3809 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
3810 where
3811 V: 'static,
3812 {
3813 let view = self.view().clone();
3814 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
3815 }
3816
3817 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
3818 /// that are currently on the stack to be returned to the app.
3819 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
3820 let view = self.view().downgrade();
3821 self.window_cx.defer(move |cx| {
3822 view.update(cx, f).ok();
3823 });
3824 }
3825
3826 /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
3827 pub fn observe<V2, E>(
3828 &mut self,
3829 entity: &E,
3830 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
3831 ) -> Subscription
3832 where
3833 V2: 'static,
3834 V: 'static,
3835 E: Entity<V2>,
3836 {
3837 let view = self.view().downgrade();
3838 let entity_id = entity.entity_id();
3839 let entity = entity.downgrade();
3840 let window_handle = self.window.handle;
3841 self.app.new_observer(
3842 entity_id,
3843 Box::new(move |cx| {
3844 window_handle
3845 .update(cx, |_, cx| {
3846 if let Some(handle) = E::upgrade_from(&entity) {
3847 view.update(cx, |this, cx| on_notify(this, handle, cx))
3848 .is_ok()
3849 } else {
3850 false
3851 }
3852 })
3853 .unwrap_or(false)
3854 }),
3855 )
3856 }
3857
3858 /// Subscribe to events emitted by another model or view.
3859 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
3860 /// 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.
3861 pub fn subscribe<V2, E, Evt>(
3862 &mut self,
3863 entity: &E,
3864 mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
3865 ) -> Subscription
3866 where
3867 V2: EventEmitter<Evt>,
3868 E: Entity<V2>,
3869 Evt: 'static,
3870 {
3871 let view = self.view().downgrade();
3872 let entity_id = entity.entity_id();
3873 let handle = entity.downgrade();
3874 let window_handle = self.window.handle;
3875 self.app.new_subscription(
3876 entity_id,
3877 (
3878 TypeId::of::<Evt>(),
3879 Box::new(move |event, cx| {
3880 window_handle
3881 .update(cx, |_, cx| {
3882 if let Some(handle) = E::upgrade_from(&handle) {
3883 let event = event.downcast_ref().expect("invalid event type");
3884 view.update(cx, |this, cx| on_event(this, handle, event, cx))
3885 .is_ok()
3886 } else {
3887 false
3888 }
3889 })
3890 .unwrap_or(false)
3891 }),
3892 ),
3893 )
3894 }
3895
3896 /// Register a callback to be invoked when the view is released.
3897 ///
3898 /// The callback receives a handle to the view's window. This handle may be
3899 /// invalid, if the window was closed before the view was released.
3900 pub fn on_release(
3901 &mut self,
3902 on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
3903 ) -> Subscription {
3904 let window_handle = self.window.handle;
3905 let (subscription, activate) = self.app.release_listeners.insert(
3906 self.view.model.entity_id,
3907 Box::new(move |this, cx| {
3908 let this = this.downcast_mut().expect("invalid entity type");
3909 on_release(this, window_handle, cx)
3910 }),
3911 );
3912 activate();
3913 subscription
3914 }
3915
3916 /// Register a callback to be invoked when the given Model or View is released.
3917 pub fn observe_release<V2, E>(
3918 &mut self,
3919 entity: &E,
3920 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
3921 ) -> Subscription
3922 where
3923 V: 'static,
3924 V2: 'static,
3925 E: Entity<V2>,
3926 {
3927 let view = self.view().downgrade();
3928 let entity_id = entity.entity_id();
3929 let window_handle = self.window.handle;
3930 let (subscription, activate) = self.app.release_listeners.insert(
3931 entity_id,
3932 Box::new(move |entity, cx| {
3933 let entity = entity.downcast_mut().expect("invalid entity type");
3934 let _ = window_handle.update(cx, |_, cx| {
3935 view.update(cx, |this, cx| on_release(this, entity, cx))
3936 });
3937 }),
3938 );
3939 activate();
3940 subscription
3941 }
3942
3943 /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
3944 /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
3945 pub fn notify(&mut self) {
3946 self.window_cx.notify(self.view.entity_id());
3947 }
3948
3949 /// Register a callback to be invoked when the window is resized.
3950 pub fn observe_window_bounds(
3951 &mut self,
3952 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
3953 ) -> Subscription {
3954 let view = self.view.downgrade();
3955 let (subscription, activate) = self.window.bounds_observers.insert(
3956 (),
3957 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
3958 );
3959 activate();
3960 subscription
3961 }
3962
3963 /// Register a callback to be invoked when the window is activated or deactivated.
3964 pub fn observe_window_activation(
3965 &mut self,
3966 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
3967 ) -> Subscription {
3968 let view = self.view.downgrade();
3969 let (subscription, activate) = self.window.activation_observers.insert(
3970 (),
3971 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
3972 );
3973 activate();
3974 subscription
3975 }
3976
3977 /// Registers a callback to be invoked when the window appearance changes.
3978 pub fn observe_window_appearance(
3979 &mut self,
3980 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
3981 ) -> Subscription {
3982 let view = self.view.downgrade();
3983 let (subscription, activate) = self.window.appearance_observers.insert(
3984 (),
3985 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
3986 );
3987 activate();
3988 subscription
3989 }
3990
3991 /// Register a listener to be called when the given focus handle receives focus.
3992 /// Returns a subscription and persists until the subscription is dropped.
3993 pub fn on_focus(
3994 &mut self,
3995 handle: &FocusHandle,
3996 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
3997 ) -> Subscription {
3998 let view = self.view.downgrade();
3999 let focus_id = handle.id;
4000 let (subscription, activate) =
4001 self.window.new_focus_listener(Box::new(move |event, cx| {
4002 view.update(cx, |view, cx| {
4003 if event.previous_focus_path.last() != Some(&focus_id)
4004 && event.current_focus_path.last() == Some(&focus_id)
4005 {
4006 listener(view, cx)
4007 }
4008 })
4009 .is_ok()
4010 }));
4011 self.app.defer(|_| activate());
4012 subscription
4013 }
4014
4015 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
4016 /// Returns a subscription and persists until the subscription is dropped.
4017 pub fn on_focus_in(
4018 &mut self,
4019 handle: &FocusHandle,
4020 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4021 ) -> Subscription {
4022 let view = self.view.downgrade();
4023 let focus_id = handle.id;
4024 let (subscription, activate) =
4025 self.window.new_focus_listener(Box::new(move |event, cx| {
4026 view.update(cx, |view, cx| {
4027 if !event.previous_focus_path.contains(&focus_id)
4028 && event.current_focus_path.contains(&focus_id)
4029 {
4030 listener(view, cx)
4031 }
4032 })
4033 .is_ok()
4034 }));
4035 self.app.defer(move |_| activate());
4036 subscription
4037 }
4038
4039 /// Register a listener to be called when the given focus handle loses focus.
4040 /// Returns a subscription and persists until the subscription is dropped.
4041 pub fn on_blur(
4042 &mut self,
4043 handle: &FocusHandle,
4044 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4045 ) -> Subscription {
4046 let view = self.view.downgrade();
4047 let focus_id = handle.id;
4048 let (subscription, activate) =
4049 self.window.new_focus_listener(Box::new(move |event, cx| {
4050 view.update(cx, |view, cx| {
4051 if event.previous_focus_path.last() == Some(&focus_id)
4052 && event.current_focus_path.last() != Some(&focus_id)
4053 {
4054 listener(view, cx)
4055 }
4056 })
4057 .is_ok()
4058 }));
4059 self.app.defer(move |_| activate());
4060 subscription
4061 }
4062
4063 /// Register a listener to be called when nothing in the window has focus.
4064 /// This typically happens when the node that was focused is removed from the tree,
4065 /// and this callback lets you chose a default place to restore the users focus.
4066 /// Returns a subscription and persists until the subscription is dropped.
4067 pub fn on_focus_lost(
4068 &mut self,
4069 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4070 ) -> Subscription {
4071 let view = self.view.downgrade();
4072 let (subscription, activate) = self.window.focus_lost_listeners.insert(
4073 (),
4074 Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
4075 );
4076 activate();
4077 subscription
4078 }
4079
4080 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
4081 /// Returns a subscription and persists until the subscription is dropped.
4082 pub fn on_focus_out(
4083 &mut self,
4084 handle: &FocusHandle,
4085 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4086 ) -> Subscription {
4087 let view = self.view.downgrade();
4088 let focus_id = handle.id;
4089 let (subscription, activate) =
4090 self.window.new_focus_listener(Box::new(move |event, cx| {
4091 view.update(cx, |view, cx| {
4092 if event.previous_focus_path.contains(&focus_id)
4093 && !event.current_focus_path.contains(&focus_id)
4094 {
4095 listener(view, cx)
4096 }
4097 })
4098 .is_ok()
4099 }));
4100 self.app.defer(move |_| activate());
4101 subscription
4102 }
4103
4104 /// Schedule a future to be run asynchronously.
4105 /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
4106 /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
4107 /// The returned future will be polled on the main thread.
4108 pub fn spawn<Fut, R>(
4109 &mut self,
4110 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
4111 ) -> Task<R>
4112 where
4113 R: 'static,
4114 Fut: Future<Output = R> + 'static,
4115 {
4116 let view = self.view().downgrade();
4117 self.window_cx.spawn(|cx| f(view, cx))
4118 }
4119
4120 /// Register a callback to be invoked when the given global state changes.
4121 pub fn observe_global<G: Global>(
4122 &mut self,
4123 mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
4124 ) -> Subscription {
4125 let window_handle = self.window.handle;
4126 let view = self.view().downgrade();
4127 let (subscription, activate) = self.global_observers.insert(
4128 TypeId::of::<G>(),
4129 Box::new(move |cx| {
4130 window_handle
4131 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
4132 .unwrap_or(false)
4133 }),
4134 );
4135 self.app.defer(move |_| activate());
4136 subscription
4137 }
4138
4139 /// Register a callback to be invoked when the given Action type is dispatched to the window.
4140 pub fn on_action(
4141 &mut self,
4142 action_type: TypeId,
4143 listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
4144 ) {
4145 let handle = self.view().clone();
4146 self.window_cx
4147 .on_action(action_type, move |action, phase, cx| {
4148 handle.update(cx, |view, cx| {
4149 listener(view, action, phase, cx);
4150 })
4151 });
4152 }
4153
4154 /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
4155 pub fn emit<Evt>(&mut self, event: Evt)
4156 where
4157 Evt: 'static,
4158 V: EventEmitter<Evt>,
4159 {
4160 let emitter = self.view.model.entity_id;
4161 self.app.push_effect(Effect::Emit {
4162 emitter,
4163 event_type: TypeId::of::<Evt>(),
4164 event: Box::new(event),
4165 });
4166 }
4167
4168 /// Move focus to the current view, assuming it implements [`FocusableView`].
4169 pub fn focus_self(&mut self)
4170 where
4171 V: FocusableView,
4172 {
4173 self.defer(|view, cx| view.focus_handle(cx).focus(cx))
4174 }
4175
4176 /// Convenience method for accessing view state in an event callback.
4177 ///
4178 /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
4179 /// but it's often useful to be able to access view state in these
4180 /// callbacks. This method provides a convenient way to do so.
4181 pub fn listener<E>(
4182 &self,
4183 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
4184 ) -> impl Fn(&E, &mut WindowContext) + 'static {
4185 let view = self.view().downgrade();
4186 move |e: &E, cx: &mut WindowContext| {
4187 view.update(cx, |view, cx| f(view, e, cx)).ok();
4188 }
4189 }
4190}
4191
4192impl<V> Context for ViewContext<'_, V> {
4193 type Result<U> = U;
4194
4195 fn new_model<T: 'static>(
4196 &mut self,
4197 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4198 ) -> Model<T> {
4199 self.window_cx.new_model(build_model)
4200 }
4201
4202 fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
4203 self.window_cx.reserve_model()
4204 }
4205
4206 fn insert_model<T: 'static>(
4207 &mut self,
4208 reservation: crate::Reservation<T>,
4209 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4210 ) -> Self::Result<Model<T>> {
4211 self.window_cx.insert_model(reservation, build_model)
4212 }
4213
4214 fn update_model<T: 'static, R>(
4215 &mut self,
4216 model: &Model<T>,
4217 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
4218 ) -> R {
4219 self.window_cx.update_model(model, update)
4220 }
4221
4222 fn read_model<T, R>(
4223 &self,
4224 handle: &Model<T>,
4225 read: impl FnOnce(&T, &AppContext) -> R,
4226 ) -> Self::Result<R>
4227 where
4228 T: 'static,
4229 {
4230 self.window_cx.read_model(handle, read)
4231 }
4232
4233 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
4234 where
4235 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
4236 {
4237 self.window_cx.update_window(window, update)
4238 }
4239
4240 fn read_window<T, R>(
4241 &self,
4242 window: &WindowHandle<T>,
4243 read: impl FnOnce(View<T>, &AppContext) -> R,
4244 ) -> Result<R>
4245 where
4246 T: 'static,
4247 {
4248 self.window_cx.read_window(window, read)
4249 }
4250}
4251
4252impl<V: 'static> VisualContext for ViewContext<'_, V> {
4253 fn new_view<W: Render + 'static>(
4254 &mut self,
4255 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4256 ) -> Self::Result<View<W>> {
4257 self.window_cx.new_view(build_view_state)
4258 }
4259
4260 fn update_view<V2: 'static, R>(
4261 &mut self,
4262 view: &View<V2>,
4263 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
4264 ) -> Self::Result<R> {
4265 self.window_cx.update_view(view, update)
4266 }
4267
4268 fn replace_root_view<W>(
4269 &mut self,
4270 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4271 ) -> Self::Result<View<W>>
4272 where
4273 W: 'static + Render,
4274 {
4275 self.window_cx.replace_root_view(build_view)
4276 }
4277
4278 fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
4279 self.window_cx.focus_view(view)
4280 }
4281
4282 fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
4283 self.window_cx.dismiss_view(view)
4284 }
4285}
4286
4287impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
4288 type Target = WindowContext<'a>;
4289
4290 fn deref(&self) -> &Self::Target {
4291 &self.window_cx
4292 }
4293}
4294
4295impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
4296 fn deref_mut(&mut self) -> &mut Self::Target {
4297 &mut self.window_cx
4298 }
4299}
4300
4301// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
4302slotmap::new_key_type! {
4303 /// A unique identifier for a window.
4304 pub struct WindowId;
4305}
4306
4307impl WindowId {
4308 /// Converts this window ID to a `u64`.
4309 pub fn as_u64(&self) -> u64 {
4310 self.0.as_ffi()
4311 }
4312}
4313
4314/// A handle to a window with a specific root view type.
4315/// Note that this does not keep the window alive on its own.
4316#[derive(Deref, DerefMut)]
4317pub struct WindowHandle<V> {
4318 #[deref]
4319 #[deref_mut]
4320 pub(crate) any_handle: AnyWindowHandle,
4321 state_type: PhantomData<V>,
4322}
4323
4324impl<V: 'static + Render> WindowHandle<V> {
4325 /// Creates a new handle from a window ID.
4326 /// This does not check if the root type of the window is `V`.
4327 pub fn new(id: WindowId) -> Self {
4328 WindowHandle {
4329 any_handle: AnyWindowHandle {
4330 id,
4331 state_type: TypeId::of::<V>(),
4332 },
4333 state_type: PhantomData,
4334 }
4335 }
4336
4337 /// Get the root view out of this window.
4338 ///
4339 /// This will fail if the window is closed or if the root view's type does not match `V`.
4340 pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
4341 where
4342 C: Context,
4343 {
4344 Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
4345 root_view
4346 .downcast::<V>()
4347 .map_err(|_| anyhow!("the type of the window's root view has changed"))
4348 }))
4349 }
4350
4351 /// Updates the root view of this window.
4352 ///
4353 /// This will fail if the window has been closed or if the root view's type does not match
4354 pub fn update<C, R>(
4355 &self,
4356 cx: &mut C,
4357 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
4358 ) -> Result<R>
4359 where
4360 C: Context,
4361 {
4362 cx.update_window(self.any_handle, |root_view, cx| {
4363 let view = root_view
4364 .downcast::<V>()
4365 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4366 Ok(cx.update_view(&view, update))
4367 })?
4368 }
4369
4370 /// Read the root view out of this window.
4371 ///
4372 /// This will fail if the window is closed or if the root view's type does not match `V`.
4373 pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
4374 let x = cx
4375 .windows
4376 .get(self.id)
4377 .and_then(|window| {
4378 window
4379 .as_ref()
4380 .and_then(|window| window.root_view.clone())
4381 .map(|root_view| root_view.downcast::<V>())
4382 })
4383 .ok_or_else(|| anyhow!("window not found"))?
4384 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4385
4386 Ok(x.read(cx))
4387 }
4388
4389 /// Read the root view out of this window, with a callback
4390 ///
4391 /// This will fail if the window is closed or if the root view's type does not match `V`.
4392 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
4393 where
4394 C: Context,
4395 {
4396 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
4397 }
4398
4399 /// Read the root view pointer off of this window.
4400 ///
4401 /// This will fail if the window is closed or if the root view's type does not match `V`.
4402 pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
4403 where
4404 C: Context,
4405 {
4406 cx.read_window(self, |root_view, _cx| root_view.clone())
4407 }
4408
4409 /// Check if this window is 'active'.
4410 ///
4411 /// Will return `None` if the window is closed or currently
4412 /// borrowed.
4413 pub fn is_active(&self, cx: &mut AppContext) -> Option<bool> {
4414 cx.update_window(self.any_handle, |_, cx| cx.is_window_active())
4415 .ok()
4416 }
4417}
4418
4419impl<V> Copy for WindowHandle<V> {}
4420
4421impl<V> Clone for WindowHandle<V> {
4422 fn clone(&self) -> Self {
4423 *self
4424 }
4425}
4426
4427impl<V> PartialEq for WindowHandle<V> {
4428 fn eq(&self, other: &Self) -> bool {
4429 self.any_handle == other.any_handle
4430 }
4431}
4432
4433impl<V> Eq for WindowHandle<V> {}
4434
4435impl<V> Hash for WindowHandle<V> {
4436 fn hash<H: Hasher>(&self, state: &mut H) {
4437 self.any_handle.hash(state);
4438 }
4439}
4440
4441impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
4442 fn from(val: WindowHandle<V>) -> Self {
4443 val.any_handle
4444 }
4445}
4446
4447/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
4448#[derive(Copy, Clone, PartialEq, Eq, Hash)]
4449pub struct AnyWindowHandle {
4450 pub(crate) id: WindowId,
4451 state_type: TypeId,
4452}
4453
4454impl AnyWindowHandle {
4455 /// Get the ID of this window.
4456 pub fn window_id(&self) -> WindowId {
4457 self.id
4458 }
4459
4460 /// Attempt to convert this handle to a window handle with a specific root view type.
4461 /// If the types do not match, this will return `None`.
4462 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
4463 if TypeId::of::<T>() == self.state_type {
4464 Some(WindowHandle {
4465 any_handle: *self,
4466 state_type: PhantomData,
4467 })
4468 } else {
4469 None
4470 }
4471 }
4472
4473 /// Updates the state of the root view of this window.
4474 ///
4475 /// This will fail if the window has been closed.
4476 pub fn update<C, R>(
4477 self,
4478 cx: &mut C,
4479 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
4480 ) -> Result<R>
4481 where
4482 C: Context,
4483 {
4484 cx.update_window(self, update)
4485 }
4486
4487 /// Read the state of the root view of this window.
4488 ///
4489 /// This will fail if the window has been closed.
4490 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
4491 where
4492 C: Context,
4493 T: 'static,
4494 {
4495 let view = self
4496 .downcast::<T>()
4497 .context("the type of the window's root view has changed")?;
4498
4499 cx.read_window(&view, read)
4500 }
4501}
4502
4503/// An identifier for an [`Element`](crate::Element).
4504///
4505/// Can be constructed with a string, a number, or both, as well
4506/// as other internal representations.
4507#[derive(Clone, Debug, Eq, PartialEq, Hash)]
4508pub enum ElementId {
4509 /// The ID of a View element
4510 View(EntityId),
4511 /// An integer ID.
4512 Integer(usize),
4513 /// A string based ID.
4514 Name(SharedString),
4515 /// An ID that's equated with a focus handle.
4516 FocusHandle(FocusId),
4517 /// A combination of a name and an integer.
4518 NamedInteger(SharedString, usize),
4519}
4520
4521impl Display for ElementId {
4522 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4523 match self {
4524 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
4525 ElementId::Integer(ix) => write!(f, "{}", ix)?,
4526 ElementId::Name(name) => write!(f, "{}", name)?,
4527 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
4528 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
4529 }
4530
4531 Ok(())
4532 }
4533}
4534
4535impl TryInto<SharedString> for ElementId {
4536 type Error = anyhow::Error;
4537
4538 fn try_into(self) -> anyhow::Result<SharedString> {
4539 if let ElementId::Name(name) = self {
4540 Ok(name)
4541 } else {
4542 Err(anyhow!("element id is not string"))
4543 }
4544 }
4545}
4546
4547impl From<usize> for ElementId {
4548 fn from(id: usize) -> Self {
4549 ElementId::Integer(id)
4550 }
4551}
4552
4553impl From<i32> for ElementId {
4554 fn from(id: i32) -> Self {
4555 Self::Integer(id as usize)
4556 }
4557}
4558
4559impl From<SharedString> for ElementId {
4560 fn from(name: SharedString) -> Self {
4561 ElementId::Name(name)
4562 }
4563}
4564
4565impl From<&'static str> for ElementId {
4566 fn from(name: &'static str) -> Self {
4567 ElementId::Name(name.into())
4568 }
4569}
4570
4571impl<'a> From<&'a FocusHandle> for ElementId {
4572 fn from(handle: &'a FocusHandle) -> Self {
4573 ElementId::FocusHandle(handle.id)
4574 }
4575}
4576
4577impl From<(&'static str, EntityId)> for ElementId {
4578 fn from((name, id): (&'static str, EntityId)) -> Self {
4579 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
4580 }
4581}
4582
4583impl From<(&'static str, usize)> for ElementId {
4584 fn from((name, id): (&'static str, usize)) -> Self {
4585 ElementId::NamedInteger(name.into(), id)
4586 }
4587}
4588
4589impl From<(&'static str, u64)> for ElementId {
4590 fn from((name, id): (&'static str, u64)) -> Self {
4591 ElementId::NamedInteger(name.into(), id as usize)
4592 }
4593}
4594
4595/// A rectangle to be rendered in the window at the given position and size.
4596/// Passed as an argument [`WindowContext::paint_quad`].
4597#[derive(Clone)]
4598pub struct PaintQuad {
4599 /// The bounds of the quad within the window.
4600 pub bounds: Bounds<Pixels>,
4601 /// The radii of the quad's corners.
4602 pub corner_radii: Corners<Pixels>,
4603 /// The background color of the quad.
4604 pub background: Hsla,
4605 /// The widths of the quad's borders.
4606 pub border_widths: Edges<Pixels>,
4607 /// The color of the quad's borders.
4608 pub border_color: Hsla,
4609}
4610
4611impl PaintQuad {
4612 /// Sets the corner radii of the quad.
4613 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
4614 PaintQuad {
4615 corner_radii: corner_radii.into(),
4616 ..self
4617 }
4618 }
4619
4620 /// Sets the border widths of the quad.
4621 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
4622 PaintQuad {
4623 border_widths: border_widths.into(),
4624 ..self
4625 }
4626 }
4627
4628 /// Sets the border color of the quad.
4629 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
4630 PaintQuad {
4631 border_color: border_color.into(),
4632 ..self
4633 }
4634 }
4635
4636 /// Sets the background color of the quad.
4637 pub fn background(self, background: impl Into<Hsla>) -> Self {
4638 PaintQuad {
4639 background: background.into(),
4640 ..self
4641 }
4642 }
4643}
4644
4645/// Creates a quad with the given parameters.
4646pub fn quad(
4647 bounds: Bounds<Pixels>,
4648 corner_radii: impl Into<Corners<Pixels>>,
4649 background: impl Into<Hsla>,
4650 border_widths: impl Into<Edges<Pixels>>,
4651 border_color: impl Into<Hsla>,
4652) -> PaintQuad {
4653 PaintQuad {
4654 bounds,
4655 corner_radii: corner_radii.into(),
4656 background: background.into(),
4657 border_widths: border_widths.into(),
4658 border_color: border_color.into(),
4659 }
4660}
4661
4662/// Creates a filled quad with the given bounds and background color.
4663pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
4664 PaintQuad {
4665 bounds: bounds.into(),
4666 corner_radii: (0.).into(),
4667 background: background.into(),
4668 border_widths: (0.).into(),
4669 border_color: transparent_black(),
4670 }
4671}
4672
4673/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
4674pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
4675 PaintQuad {
4676 bounds: bounds.into(),
4677 corner_radii: (0.).into(),
4678 background: transparent_black(),
4679 border_widths: (1.).into(),
4680 border_color: border_color.into(),
4681 }
4682}