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