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