1use crate::{
2 px, size, Action, AnyBox, AnyDrag, AnyView, AppContext, AsyncWindowContext, AvailableSpace,
3 Bounds, BoxShadow, Context, Corners, DevicePixels, DispatchContext, DisplayId, Edges, Effect,
4 Entity, EntityId, EventEmitter, FileDropEvent, FocusEvent, FontId, GlobalElementId, GlyphId,
5 Hsla, ImageData, InputEvent, IsZero, KeyListener, KeyMatch, KeyMatcher, Keystroke, LayoutId,
6 MainThread, MainThreadOnly, Model, ModelContext, Modifiers, MonochromeSprite, MouseButton,
7 MouseDownEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformWindow,
8 Point, PolychromeSprite, Quad, Render, RenderGlyphParams, RenderImageParams, RenderSvgParams,
9 ScaledPixels, SceneBuilder, Shadow, SharedString, Size, Style, Subscription, TaffyLayoutEngine,
10 Task, Underline, UnderlineStyle, UpdateView, View, VisualContext, WeakView, WindowOptions,
11 SUBPIXEL_VARIANTS,
12};
13use anyhow::{anyhow, Result};
14use collections::HashMap;
15use derive_more::{Deref, DerefMut};
16use parking_lot::RwLock;
17use slotmap::SlotMap;
18use smallvec::SmallVec;
19use std::{
20 any::{Any, TypeId},
21 borrow::{Borrow, BorrowMut, Cow},
22 fmt::Debug,
23 future::Future,
24 hash::{Hash, Hasher},
25 marker::PhantomData,
26 mem,
27 sync::{
28 atomic::{AtomicUsize, Ordering::SeqCst},
29 Arc,
30 },
31};
32use util::ResultExt;
33
34/// A global stacking order, which is created by stacking successive z-index values.
35/// Each z-index will always be interpreted in the context of its parent z-index.
36#[derive(Deref, DerefMut, Ord, PartialOrd, Eq, PartialEq, Clone, Default)]
37pub(crate) struct StackingOrder(pub(crate) SmallVec<[u32; 16]>);
38
39/// Represents the two different phases when dispatching events.
40#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
41pub enum DispatchPhase {
42 /// After the capture phase comes the bubble phase, in which mouse event listeners are
43 /// invoked front to back and keyboard event listeners are invoked from the focused element
44 /// to the root of the element tree. This is the phase you'll most commonly want to use when
45 /// registering event listeners.
46 #[default]
47 Bubble,
48 /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
49 /// listeners are invoked from the root of the tree downward toward the focused element. This phase
50 /// is used for special purposes such as clearing the "pressed" state for click events. If
51 /// you stop event propagation during this phase, you need to know what you're doing. Handlers
52 /// outside of the immediate region may rely on detecting non-local events during this phase.
53 Capture,
54}
55
56type AnyListener = Box<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + Send + 'static>;
57type AnyKeyListener = Box<
58 dyn Fn(
59 &dyn Any,
60 &[&DispatchContext],
61 DispatchPhase,
62 &mut WindowContext,
63 ) -> Option<Box<dyn Action>>
64 + Send
65 + 'static,
66>;
67type AnyFocusListener = Box<dyn Fn(&FocusEvent, &mut WindowContext) + Send + 'static>;
68
69slotmap::new_key_type! { pub struct FocusId; }
70
71/// A handle which can be used to track and manipulate the focused element in a window.
72pub struct FocusHandle {
73 pub(crate) id: FocusId,
74 handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
75}
76
77impl FocusHandle {
78 pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
79 let id = handles.write().insert(AtomicUsize::new(1));
80 Self {
81 id,
82 handles: handles.clone(),
83 }
84 }
85
86 pub(crate) fn for_id(
87 id: FocusId,
88 handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
89 ) -> Option<Self> {
90 let lock = handles.read();
91 let ref_count = lock.get(id)?;
92 if ref_count.load(SeqCst) == 0 {
93 None
94 } else {
95 ref_count.fetch_add(1, SeqCst);
96 Some(Self {
97 id,
98 handles: handles.clone(),
99 })
100 }
101 }
102
103 /// Obtains whether the element associated with this handle is currently focused.
104 pub fn is_focused(&self, cx: &WindowContext) -> bool {
105 cx.window.focus == Some(self.id)
106 }
107
108 /// Obtains whether the element associated with this handle contains the focused
109 /// element or is itself focused.
110 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
111 cx.focused()
112 .map_or(false, |focused| self.contains(&focused, cx))
113 }
114
115 /// Obtains whether the element associated with this handle is contained within the
116 /// focused element or is itself focused.
117 pub fn within_focused(&self, cx: &WindowContext) -> bool {
118 let focused = cx.focused();
119 focused.map_or(false, |focused| focused.contains(self, cx))
120 }
121
122 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
123 pub(crate) fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
124 let mut ancestor = Some(other.id);
125 while let Some(ancestor_id) = ancestor {
126 if self.id == ancestor_id {
127 return true;
128 } else {
129 ancestor = cx.window.focus_parents_by_child.get(&ancestor_id).copied();
130 }
131 }
132 false
133 }
134}
135
136impl Clone for FocusHandle {
137 fn clone(&self) -> Self {
138 Self::for_id(self.id, &self.handles).unwrap()
139 }
140}
141
142impl PartialEq for FocusHandle {
143 fn eq(&self, other: &Self) -> bool {
144 self.id == other.id
145 }
146}
147
148impl Eq for FocusHandle {}
149
150impl Drop for FocusHandle {
151 fn drop(&mut self) {
152 self.handles
153 .read()
154 .get(self.id)
155 .unwrap()
156 .fetch_sub(1, SeqCst);
157 }
158}
159
160// Holds the state for a specific window.
161pub struct Window {
162 pub(crate) handle: AnyWindowHandle,
163 platform_window: MainThreadOnly<Box<dyn PlatformWindow>>,
164 display_id: DisplayId,
165 sprite_atlas: Arc<dyn PlatformAtlas>,
166 rem_size: Pixels,
167 content_size: Size<Pixels>,
168 pub(crate) layout_engine: TaffyLayoutEngine,
169 pub(crate) root_view: Option<AnyView>,
170 pub(crate) element_id_stack: GlobalElementId,
171 prev_frame_element_states: HashMap<GlobalElementId, AnyBox>,
172 element_states: HashMap<GlobalElementId, AnyBox>,
173 prev_frame_key_matchers: HashMap<GlobalElementId, KeyMatcher>,
174 key_matchers: HashMap<GlobalElementId, KeyMatcher>,
175 z_index_stack: StackingOrder,
176 content_mask_stack: Vec<ContentMask<Pixels>>,
177 element_offset_stack: Vec<Point<Pixels>>,
178 mouse_listeners: HashMap<TypeId, Vec<(StackingOrder, AnyListener)>>,
179 key_dispatch_stack: Vec<KeyDispatchStackFrame>,
180 freeze_key_dispatch_stack: bool,
181 focus_stack: Vec<FocusId>,
182 focus_parents_by_child: HashMap<FocusId, FocusId>,
183 pub(crate) focus_listeners: Vec<AnyFocusListener>,
184 pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
185 default_prevented: bool,
186 mouse_position: Point<Pixels>,
187 scale_factor: f32,
188 pub(crate) scene_builder: SceneBuilder,
189 pub(crate) dirty: bool,
190 pub(crate) last_blur: Option<Option<FocusId>>,
191 pub(crate) focus: Option<FocusId>,
192}
193
194impl Window {
195 pub(crate) fn new(
196 handle: AnyWindowHandle,
197 options: WindowOptions,
198 cx: &mut MainThread<AppContext>,
199 ) -> Self {
200 let platform_window = cx.platform().open_window(handle, options);
201 let display_id = platform_window.display().id();
202 let sprite_atlas = platform_window.sprite_atlas();
203 let mouse_position = platform_window.mouse_position();
204 let content_size = platform_window.content_size();
205 let scale_factor = platform_window.scale_factor();
206 platform_window.on_resize(Box::new({
207 let mut cx = cx.to_async();
208 move |content_size, scale_factor| {
209 handle
210 .update(&mut cx, |_, cx| {
211 cx.window.scale_factor = scale_factor;
212 cx.window.scene_builder = SceneBuilder::new();
213 cx.window.content_size = content_size;
214 cx.window.display_id = cx
215 .window
216 .platform_window
217 .borrow_on_main_thread()
218 .display()
219 .id();
220 cx.window.dirty = true;
221 })
222 .log_err();
223 }
224 }));
225
226 platform_window.on_input({
227 let mut cx = cx.to_async();
228 Box::new(move |event| {
229 handle
230 .update(&mut cx, |_, cx| cx.dispatch_event(event))
231 .log_err()
232 .unwrap_or(true)
233 })
234 });
235
236 let platform_window = MainThreadOnly::new(Arc::new(platform_window), cx.executor.clone());
237
238 Window {
239 handle,
240 platform_window,
241 display_id,
242 sprite_atlas,
243 rem_size: px(16.),
244 content_size,
245 layout_engine: TaffyLayoutEngine::new(),
246 root_view: None,
247 element_id_stack: GlobalElementId::default(),
248 prev_frame_element_states: HashMap::default(),
249 element_states: HashMap::default(),
250 prev_frame_key_matchers: HashMap::default(),
251 key_matchers: HashMap::default(),
252 z_index_stack: StackingOrder(SmallVec::new()),
253 content_mask_stack: Vec::new(),
254 element_offset_stack: Vec::new(),
255 mouse_listeners: HashMap::default(),
256 key_dispatch_stack: Vec::new(),
257 freeze_key_dispatch_stack: false,
258 focus_stack: Vec::new(),
259 focus_parents_by_child: HashMap::default(),
260 focus_listeners: Vec::new(),
261 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
262 default_prevented: true,
263 mouse_position,
264 scale_factor,
265 scene_builder: SceneBuilder::new(),
266 dirty: true,
267 last_blur: None,
268 focus: None,
269 }
270 }
271}
272
273/// When constructing the element tree, we maintain a stack of key dispatch frames until we
274/// find the focused element. We interleave key listeners with dispatch contexts so we can use the
275/// contexts when matching key events against the keymap.
276enum KeyDispatchStackFrame {
277 Listener {
278 event_type: TypeId,
279 listener: AnyKeyListener,
280 },
281 Context(DispatchContext),
282}
283
284/// Indicates which region of the window is visible. Content falling outside of this mask will not be
285/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
286/// to leave room to support more complex shapes in the future.
287#[derive(Clone, Debug, Default, PartialEq, Eq)]
288#[repr(C)]
289pub struct ContentMask<P: Clone + Default + Debug> {
290 pub bounds: Bounds<P>,
291}
292
293impl ContentMask<Pixels> {
294 /// Scale the content mask's pixel units by the given scaling factor.
295 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
296 ContentMask {
297 bounds: self.bounds.scale(factor),
298 }
299 }
300
301 /// Intersect the content mask with the given content mask.
302 pub fn intersect(&self, other: &Self) -> Self {
303 let bounds = self.bounds.intersect(&other.bounds);
304 ContentMask { bounds }
305 }
306}
307
308/// Provides access to application state in the context of a single window. Derefs
309/// to an `AppContext`, so you can also pass a `WindowContext` to any method that takes
310/// an `AppContext` and call any `AppContext` methods.
311pub struct WindowContext<'a> {
312 pub(crate) app: &'a mut AppContext,
313 pub(crate) window: &'a mut Window,
314}
315
316impl<'a> WindowContext<'a> {
317 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
318 Self { app, window }
319 }
320
321 /// Obtain a handle to the window that belongs to this context.
322 pub fn window_handle(&self) -> AnyWindowHandle {
323 self.window.handle
324 }
325
326 /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
327 pub fn notify(&mut self) {
328 self.window.dirty = true;
329 }
330
331 /// Obtain a new `FocusHandle`, which allows you to track and manipulate the keyboard focus
332 /// for elements rendered within this window.
333 pub fn focus_handle(&mut self) -> FocusHandle {
334 FocusHandle::new(&self.window.focus_handles)
335 }
336
337 /// Obtain the currently focused `FocusHandle`. If no elements are focused, returns `None`.
338 pub fn focused(&self) -> Option<FocusHandle> {
339 self.window
340 .focus
341 .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
342 }
343
344 /// Move focus to the element associated with the given `FocusHandle`.
345 pub fn focus(&mut self, handle: &FocusHandle) {
346 if self.window.last_blur.is_none() {
347 self.window.last_blur = Some(self.window.focus);
348 }
349
350 self.window.focus = Some(handle.id);
351 self.app.push_effect(Effect::FocusChanged {
352 window_handle: self.window.handle,
353 focused: Some(handle.id),
354 });
355 self.notify();
356 }
357
358 /// Remove focus from all elements within this context's window.
359 pub fn blur(&mut self) {
360 if self.window.last_blur.is_none() {
361 self.window.last_blur = Some(self.window.focus);
362 }
363
364 self.window.focus = None;
365 self.app.push_effect(Effect::FocusChanged {
366 window_handle: self.window.handle,
367 focused: None,
368 });
369 self.notify();
370 }
371
372 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
373 /// that are currently on the stack to be returned to the app.
374 pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static + Send) {
375 let handle = self.window.handle;
376 self.app.defer(move |cx| {
377 handle.update(cx, |_, cx| f(cx)).ok();
378 });
379 }
380
381 pub fn subscribe<Emitter, E>(
382 &mut self,
383 entity: &E,
384 mut on_event: impl FnMut(E, &Emitter::Event, &mut WindowContext<'_>) + Send + 'static,
385 ) -> Subscription
386 where
387 Emitter: EventEmitter,
388 E: Entity<Emitter>,
389 {
390 let entity_id = entity.entity_id();
391 let entity = entity.downgrade();
392 let window_handle = self.window.handle;
393 self.app.event_listeners.insert(
394 entity_id,
395 Box::new(move |event, cx| {
396 window_handle
397 .update(cx, |_, cx| {
398 if let Some(handle) = E::upgrade_from(&entity) {
399 let event = event.downcast_ref().expect("invalid event type");
400 on_event(handle, event, cx);
401 true
402 } else {
403 false
404 }
405 })
406 .unwrap_or(false)
407 }),
408 )
409 }
410
411 /// Schedule the given closure to be run on the main thread. It will be invoked with
412 /// a `MainThread<WindowContext>`, which provides access to platform-specific functionality
413 /// of the window.
414 pub fn run_on_main<R>(
415 &mut self,
416 f: impl FnOnce(&mut MainThread<WindowContext<'_>>) -> R + Send + 'static,
417 ) -> Task<Result<R>>
418 where
419 R: Send + 'static,
420 {
421 if self.executor.is_main_thread() {
422 Task::ready(Ok(f(unsafe {
423 mem::transmute::<&mut Self, &mut MainThread<Self>>(self)
424 })))
425 } else {
426 let handle = self.window.handle;
427 self.app
428 .run_on_main(move |cx| handle.update(cx, |_, cx| f(cx)))
429 }
430 }
431
432 /// Create an `AsyncWindowContext`, which has a static lifetime and can be held across
433 /// await points in async code.
434 pub fn to_async(&self) -> AsyncWindowContext {
435 AsyncWindowContext::new(self.app.to_async(), self.window.handle)
436 }
437
438 /// Schedule the given closure to be run directly after the current frame is rendered.
439 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + Send + 'static) {
440 let f = Box::new(f);
441 let display_id = self.window.display_id;
442 self.run_on_main(move |cx| {
443 if let Some(callbacks) = cx.next_frame_callbacks.get_mut(&display_id) {
444 callbacks.push(f);
445 // If there was already a callback, it means that we already scheduled a frame.
446 if callbacks.len() > 1 {
447 return;
448 }
449 } else {
450 let mut async_cx = cx.to_async();
451 cx.next_frame_callbacks.insert(display_id, vec![f]);
452 cx.platform().set_display_link_output_callback(
453 display_id,
454 Box::new(move |_current_time, _output_time| {
455 let _ = async_cx.update(|_, cx| {
456 let callbacks = cx
457 .next_frame_callbacks
458 .get_mut(&display_id)
459 .unwrap()
460 .drain(..)
461 .collect::<Vec<_>>();
462 for callback in callbacks {
463 callback(cx);
464 }
465
466 cx.run_on_main(move |cx| {
467 if cx.next_frame_callbacks.get(&display_id).unwrap().is_empty() {
468 cx.platform().stop_display_link(display_id);
469 }
470 })
471 .detach();
472 });
473 }),
474 );
475 }
476
477 cx.platform().start_display_link(display_id);
478 })
479 .detach();
480 }
481
482 /// Spawn the future returned by the given closure on the application thread pool.
483 /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
484 /// use within your future.
485 pub fn spawn<Fut, R>(
486 &mut self,
487 f: impl FnOnce(AnyWindowHandle, AsyncWindowContext) -> Fut,
488 ) -> Task<R>
489 where
490 R: Send + 'static,
491 Fut: Future<Output = R> + Send + 'static,
492 {
493 let window = self.window.handle;
494 self.app.spawn(move |app| {
495 let cx = AsyncWindowContext::new(app, window);
496 f(window, cx)
497 })
498 }
499
500 /// Update the global of the given type. The given closure is given simultaneous mutable
501 /// access both to the global and the context.
502 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
503 where
504 G: 'static,
505 {
506 let mut global = self.app.lease_global::<G>();
507 let result = f(&mut global, self);
508 self.app.end_global_lease(global);
509 result
510 }
511
512 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
513 /// layout is being requested, along with the layout ids of any children. This method is called during
514 /// calls to the `Element::layout` trait method and enables any element to participate in layout.
515 pub fn request_layout(
516 &mut self,
517 style: &Style,
518 children: impl IntoIterator<Item = LayoutId>,
519 ) -> LayoutId {
520 self.app.layout_id_buffer.clear();
521 self.app.layout_id_buffer.extend(children.into_iter());
522 let rem_size = self.rem_size();
523
524 self.window
525 .layout_engine
526 .request_layout(style, rem_size, &self.app.layout_id_buffer)
527 }
528
529 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
530 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
531 /// determine the element's size. One place this is used internally is when measuring text.
532 ///
533 /// The given closure is invoked at layout time with the known dimensions and available space and
534 /// returns a `Size`.
535 pub fn request_measured_layout<
536 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>) -> Size<Pixels> + Send + Sync + 'static,
537 >(
538 &mut self,
539 style: Style,
540 rem_size: Pixels,
541 measure: F,
542 ) -> LayoutId {
543 self.window
544 .layout_engine
545 .request_measured_layout(style, rem_size, measure)
546 }
547
548 /// Obtain the bounds computed for the given LayoutId relative to the window. This method should not
549 /// be invoked until the paint phase begins, and will usually be invoked by GPUI itself automatically
550 /// in order to pass your element its `Bounds` automatically.
551 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
552 let mut bounds = self
553 .window
554 .layout_engine
555 .layout_bounds(layout_id)
556 .map(Into::into);
557 bounds.origin += self.element_offset();
558 bounds
559 }
560
561 /// The scale factor of the display associated with the window. For example, it could
562 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
563 /// be rendered as two pixels on screen.
564 pub fn scale_factor(&self) -> f32 {
565 self.window.scale_factor
566 }
567
568 /// The size of an em for the base font of the application. Adjusting this value allows the
569 /// UI to scale, just like zooming a web page.
570 pub fn rem_size(&self) -> Pixels {
571 self.window.rem_size
572 }
573
574 /// The line height associated with the current text style.
575 pub fn line_height(&self) -> Pixels {
576 let rem_size = self.rem_size();
577 let text_style = self.text_style();
578 text_style
579 .line_height
580 .to_pixels(text_style.font_size.into(), rem_size)
581 }
582
583 /// Call to prevent the default action of an event. Currently only used to prevent
584 /// parent elements from becoming focused on mouse down.
585 pub fn prevent_default(&mut self) {
586 self.window.default_prevented = true;
587 }
588
589 /// Obtain whether default has been prevented for the event currently being dispatched.
590 pub fn default_prevented(&self) -> bool {
591 self.window.default_prevented
592 }
593
594 /// Register a mouse event listener on the window for the current frame. The type of event
595 /// is determined by the first parameter of the given listener. When the next frame is rendered
596 /// the listener will be cleared.
597 ///
598 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
599 /// a specific need to register a global listener.
600 pub fn on_mouse_event<Event: 'static>(
601 &mut self,
602 handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + Send + 'static,
603 ) {
604 let order = self.window.z_index_stack.clone();
605 self.window
606 .mouse_listeners
607 .entry(TypeId::of::<Event>())
608 .or_default()
609 .push((
610 order,
611 Box::new(move |event: &dyn Any, phase, cx| {
612 handler(event.downcast_ref().unwrap(), phase, cx)
613 }),
614 ))
615 }
616
617 /// The position of the mouse relative to the window.
618 pub fn mouse_position(&self) -> Point<Pixels> {
619 self.window.mouse_position
620 }
621
622 /// Called during painting to invoke the given closure in a new stacking context. The given
623 /// z-index is interpreted relative to the previous call to `stack`.
624 pub fn stack<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
625 self.window.z_index_stack.push(z_index);
626 let result = f(self);
627 self.window.z_index_stack.pop();
628 result
629 }
630
631 /// Paint one or more drop shadows into the scene for the current frame at the current z-index.
632 pub fn paint_shadows(
633 &mut self,
634 bounds: Bounds<Pixels>,
635 corner_radii: Corners<Pixels>,
636 shadows: &[BoxShadow],
637 ) {
638 let scale_factor = self.scale_factor();
639 let content_mask = self.content_mask();
640 let window = &mut *self.window;
641 for shadow in shadows {
642 let mut shadow_bounds = bounds;
643 shadow_bounds.origin += shadow.offset;
644 shadow_bounds.dilate(shadow.spread_radius);
645 window.scene_builder.insert(
646 &window.z_index_stack,
647 Shadow {
648 order: 0,
649 bounds: shadow_bounds.scale(scale_factor),
650 content_mask: content_mask.scale(scale_factor),
651 corner_radii: corner_radii.scale(scale_factor),
652 color: shadow.color,
653 blur_radius: shadow.blur_radius.scale(scale_factor),
654 },
655 );
656 }
657 }
658
659 /// Paint one or more quads into the scene for the current frame at the current stacking context.
660 /// Quads are colored rectangular regions with an optional background, border, and corner radius.
661 pub fn paint_quad(
662 &mut self,
663 bounds: Bounds<Pixels>,
664 corner_radii: Corners<Pixels>,
665 background: impl Into<Hsla>,
666 border_widths: Edges<Pixels>,
667 border_color: impl Into<Hsla>,
668 ) {
669 let scale_factor = self.scale_factor();
670 let content_mask = self.content_mask();
671
672 let window = &mut *self.window;
673 window.scene_builder.insert(
674 &window.z_index_stack,
675 Quad {
676 order: 0,
677 bounds: bounds.scale(scale_factor),
678 content_mask: content_mask.scale(scale_factor),
679 background: background.into(),
680 border_color: border_color.into(),
681 corner_radii: corner_radii.scale(scale_factor),
682 border_widths: border_widths.scale(scale_factor),
683 },
684 );
685 }
686
687 /// Paint the given `Path` into the scene for the current frame at the current z-index.
688 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
689 let scale_factor = self.scale_factor();
690 let content_mask = self.content_mask();
691 path.content_mask = content_mask;
692 path.color = color.into();
693 let window = &mut *self.window;
694 window
695 .scene_builder
696 .insert(&window.z_index_stack, path.scale(scale_factor));
697 }
698
699 /// Paint an underline into the scene for the current frame at the current z-index.
700 pub fn paint_underline(
701 &mut self,
702 origin: Point<Pixels>,
703 width: Pixels,
704 style: &UnderlineStyle,
705 ) -> Result<()> {
706 let scale_factor = self.scale_factor();
707 let height = if style.wavy {
708 style.thickness * 3.
709 } else {
710 style.thickness
711 };
712 let bounds = Bounds {
713 origin,
714 size: size(width, height),
715 };
716 let content_mask = self.content_mask();
717 let window = &mut *self.window;
718 window.scene_builder.insert(
719 &window.z_index_stack,
720 Underline {
721 order: 0,
722 bounds: bounds.scale(scale_factor),
723 content_mask: content_mask.scale(scale_factor),
724 thickness: style.thickness.scale(scale_factor),
725 color: style.color.unwrap_or_default(),
726 wavy: style.wavy,
727 },
728 );
729 Ok(())
730 }
731
732 /// Paint a monochrome (non-emoji) glyph into the scene for the current frame at the current z-index.
733 pub fn paint_glyph(
734 &mut self,
735 origin: Point<Pixels>,
736 font_id: FontId,
737 glyph_id: GlyphId,
738 font_size: Pixels,
739 color: Hsla,
740 ) -> Result<()> {
741 let scale_factor = self.scale_factor();
742 let glyph_origin = origin.scale(scale_factor);
743 let subpixel_variant = Point {
744 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
745 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
746 };
747 let params = RenderGlyphParams {
748 font_id,
749 glyph_id,
750 font_size,
751 subpixel_variant,
752 scale_factor,
753 is_emoji: false,
754 };
755
756 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
757 if !raster_bounds.is_zero() {
758 let tile =
759 self.window
760 .sprite_atlas
761 .get_or_insert_with(¶ms.clone().into(), &mut || {
762 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
763 Ok((size, Cow::Owned(bytes)))
764 })?;
765 let bounds = Bounds {
766 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
767 size: tile.bounds.size.map(Into::into),
768 };
769 let content_mask = self.content_mask().scale(scale_factor);
770 let window = &mut *self.window;
771 window.scene_builder.insert(
772 &window.z_index_stack,
773 MonochromeSprite {
774 order: 0,
775 bounds,
776 content_mask,
777 color,
778 tile,
779 },
780 );
781 }
782 Ok(())
783 }
784
785 /// Paint an emoji glyph into the scene for the current frame at the current z-index.
786 pub fn paint_emoji(
787 &mut self,
788 origin: Point<Pixels>,
789 font_id: FontId,
790 glyph_id: GlyphId,
791 font_size: Pixels,
792 ) -> Result<()> {
793 let scale_factor = self.scale_factor();
794 let glyph_origin = origin.scale(scale_factor);
795 let params = RenderGlyphParams {
796 font_id,
797 glyph_id,
798 font_size,
799 // We don't render emojis with subpixel variants.
800 subpixel_variant: Default::default(),
801 scale_factor,
802 is_emoji: true,
803 };
804
805 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
806 if !raster_bounds.is_zero() {
807 let tile =
808 self.window
809 .sprite_atlas
810 .get_or_insert_with(¶ms.clone().into(), &mut || {
811 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
812 Ok((size, Cow::Owned(bytes)))
813 })?;
814 let bounds = Bounds {
815 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
816 size: tile.bounds.size.map(Into::into),
817 };
818 let content_mask = self.content_mask().scale(scale_factor);
819 let window = &mut *self.window;
820
821 window.scene_builder.insert(
822 &window.z_index_stack,
823 PolychromeSprite {
824 order: 0,
825 bounds,
826 corner_radii: Default::default(),
827 content_mask,
828 tile,
829 grayscale: false,
830 },
831 );
832 }
833 Ok(())
834 }
835
836 /// Paint a monochrome SVG into the scene for the current frame at the current stacking context.
837 pub fn paint_svg(
838 &mut self,
839 bounds: Bounds<Pixels>,
840 path: SharedString,
841 color: Hsla,
842 ) -> Result<()> {
843 let scale_factor = self.scale_factor();
844 let bounds = bounds.scale(scale_factor);
845 // Render the SVG at twice the size to get a higher quality result.
846 let params = RenderSvgParams {
847 path,
848 size: bounds
849 .size
850 .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
851 };
852
853 let tile =
854 self.window
855 .sprite_atlas
856 .get_or_insert_with(¶ms.clone().into(), &mut || {
857 let bytes = self.svg_renderer.render(¶ms)?;
858 Ok((params.size, Cow::Owned(bytes)))
859 })?;
860 let content_mask = self.content_mask().scale(scale_factor);
861
862 let window = &mut *self.window;
863 window.scene_builder.insert(
864 &window.z_index_stack,
865 MonochromeSprite {
866 order: 0,
867 bounds,
868 content_mask,
869 color,
870 tile,
871 },
872 );
873
874 Ok(())
875 }
876
877 /// Paint an image into the scene for the current frame at the current z-index.
878 pub fn paint_image(
879 &mut self,
880 bounds: Bounds<Pixels>,
881 corner_radii: Corners<Pixels>,
882 data: Arc<ImageData>,
883 grayscale: bool,
884 ) -> Result<()> {
885 let scale_factor = self.scale_factor();
886 let bounds = bounds.scale(scale_factor);
887 let params = RenderImageParams { image_id: data.id };
888
889 let tile = self
890 .window
891 .sprite_atlas
892 .get_or_insert_with(¶ms.clone().into(), &mut || {
893 Ok((data.size(), Cow::Borrowed(data.as_bytes())))
894 })?;
895 let content_mask = self.content_mask().scale(scale_factor);
896 let corner_radii = corner_radii.scale(scale_factor);
897
898 let window = &mut *self.window;
899 window.scene_builder.insert(
900 &window.z_index_stack,
901 PolychromeSprite {
902 order: 0,
903 bounds,
904 content_mask,
905 corner_radii,
906 tile,
907 grayscale,
908 },
909 );
910 Ok(())
911 }
912
913 /// Draw pixels to the display for this window based on the contents of its scene.
914 pub(crate) fn draw(&mut self) {
915 let root_view = self.window.root_view.take().unwrap();
916
917 self.start_frame();
918
919 self.stack(0, |cx| {
920 let available_space = cx.window.content_size.map(Into::into);
921 root_view.draw(available_space, cx);
922 });
923
924 if let Some(active_drag) = self.app.active_drag.take() {
925 self.stack(1, |cx| {
926 let offset = cx.mouse_position() - active_drag.cursor_offset;
927 cx.with_element_offset(Some(offset), |cx| {
928 let available_space =
929 size(AvailableSpace::MinContent, AvailableSpace::MinContent);
930 active_drag.view.draw(available_space, cx);
931 cx.active_drag = Some(active_drag);
932 });
933 });
934 }
935
936 self.window.root_view = Some(root_view);
937 let scene = self.window.scene_builder.build();
938
939 self.run_on_main(|cx| {
940 cx.window
941 .platform_window
942 .borrow_on_main_thread()
943 .draw(scene);
944 cx.window.dirty = false;
945 })
946 .detach();
947 }
948
949 fn start_frame(&mut self) {
950 self.text_system().start_frame();
951
952 let window = &mut *self.window;
953
954 // Move the current frame element states to the previous frame.
955 // The new empty element states map will be populated for any element states we
956 // reference during the upcoming frame.
957 mem::swap(
958 &mut window.element_states,
959 &mut window.prev_frame_element_states,
960 );
961 window.element_states.clear();
962
963 // Make the current key matchers the previous, and then clear the current.
964 // An empty key matcher map will be created for every identified element in the
965 // upcoming frame.
966 mem::swap(
967 &mut window.key_matchers,
968 &mut window.prev_frame_key_matchers,
969 );
970 window.key_matchers.clear();
971
972 // Clear mouse event listeners, because elements add new element listeners
973 // when the upcoming frame is painted.
974 window.mouse_listeners.values_mut().for_each(Vec::clear);
975
976 // Clear focus state, because we determine what is focused when the new elements
977 // in the upcoming frame are initialized.
978 window.focus_listeners.clear();
979 window.key_dispatch_stack.clear();
980 window.focus_parents_by_child.clear();
981 window.freeze_key_dispatch_stack = false;
982 }
983
984 /// Dispatch a mouse or keyboard event on the window.
985 fn dispatch_event(&mut self, event: InputEvent) -> bool {
986 let event = match event {
987 // Track the mouse position with our own state, since accessing the platform
988 // API for the mouse position can only occur on the main thread.
989 InputEvent::MouseMove(mouse_move) => {
990 self.window.mouse_position = mouse_move.position;
991 InputEvent::MouseMove(mouse_move)
992 }
993 // Translate dragging and dropping of external files from the operating system
994 // to internal drag and drop events.
995 InputEvent::FileDrop(file_drop) => match file_drop {
996 FileDropEvent::Entered { position, files } => {
997 self.window.mouse_position = position;
998 if self.active_drag.is_none() {
999 self.active_drag = Some(AnyDrag {
1000 view: self.build_view(|_| files).into(),
1001 cursor_offset: position,
1002 });
1003 }
1004 InputEvent::MouseDown(MouseDownEvent {
1005 position,
1006 button: MouseButton::Left,
1007 click_count: 1,
1008 modifiers: Modifiers::default(),
1009 })
1010 }
1011 FileDropEvent::Pending { position } => {
1012 self.window.mouse_position = position;
1013 InputEvent::MouseMove(MouseMoveEvent {
1014 position,
1015 pressed_button: Some(MouseButton::Left),
1016 modifiers: Modifiers::default(),
1017 })
1018 }
1019 FileDropEvent::Submit { position } => {
1020 self.window.mouse_position = position;
1021 InputEvent::MouseUp(MouseUpEvent {
1022 button: MouseButton::Left,
1023 position,
1024 modifiers: Modifiers::default(),
1025 click_count: 1,
1026 })
1027 }
1028 FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1029 button: MouseButton::Left,
1030 position: Point::default(),
1031 modifiers: Modifiers::default(),
1032 click_count: 1,
1033 }),
1034 },
1035 _ => event,
1036 };
1037
1038 if let Some(any_mouse_event) = event.mouse_event() {
1039 // Handlers may set this to false by calling `stop_propagation`
1040 self.app.propagate_event = true;
1041 self.window.default_prevented = false;
1042
1043 if let Some(mut handlers) = self
1044 .window
1045 .mouse_listeners
1046 .remove(&any_mouse_event.type_id())
1047 {
1048 // Because handlers may add other handlers, we sort every time.
1049 handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1050
1051 // Capture phase, events bubble from back to front. Handlers for this phase are used for
1052 // special purposes, such as detecting events outside of a given Bounds.
1053 for (_, handler) in &handlers {
1054 handler(any_mouse_event, DispatchPhase::Capture, self);
1055 if !self.app.propagate_event {
1056 break;
1057 }
1058 }
1059
1060 // Bubble phase, where most normal handlers do their work.
1061 if self.app.propagate_event {
1062 for (_, handler) in handlers.iter().rev() {
1063 handler(any_mouse_event, DispatchPhase::Bubble, self);
1064 if !self.app.propagate_event {
1065 break;
1066 }
1067 }
1068 }
1069
1070 if self.app.propagate_event
1071 && any_mouse_event.downcast_ref::<MouseUpEvent>().is_some()
1072 {
1073 self.active_drag = None;
1074 }
1075
1076 // Just in case any handlers added new handlers, which is weird, but possible.
1077 handlers.extend(
1078 self.window
1079 .mouse_listeners
1080 .get_mut(&any_mouse_event.type_id())
1081 .into_iter()
1082 .flat_map(|handlers| handlers.drain(..)),
1083 );
1084 self.window
1085 .mouse_listeners
1086 .insert(any_mouse_event.type_id(), handlers);
1087 }
1088 } else if let Some(any_key_event) = event.keyboard_event() {
1089 let key_dispatch_stack = mem::take(&mut self.window.key_dispatch_stack);
1090 let key_event_type = any_key_event.type_id();
1091 let mut context_stack = SmallVec::<[&DispatchContext; 16]>::new();
1092
1093 for (ix, frame) in key_dispatch_stack.iter().enumerate() {
1094 match frame {
1095 KeyDispatchStackFrame::Listener {
1096 event_type,
1097 listener,
1098 } => {
1099 if key_event_type == *event_type {
1100 if let Some(action) = listener(
1101 any_key_event,
1102 &context_stack,
1103 DispatchPhase::Capture,
1104 self,
1105 ) {
1106 self.dispatch_action(action, &key_dispatch_stack[..ix]);
1107 }
1108 if !self.app.propagate_event {
1109 break;
1110 }
1111 }
1112 }
1113 KeyDispatchStackFrame::Context(context) => {
1114 context_stack.push(&context);
1115 }
1116 }
1117 }
1118
1119 if self.app.propagate_event {
1120 for (ix, frame) in key_dispatch_stack.iter().enumerate().rev() {
1121 match frame {
1122 KeyDispatchStackFrame::Listener {
1123 event_type,
1124 listener,
1125 } => {
1126 if key_event_type == *event_type {
1127 if let Some(action) = listener(
1128 any_key_event,
1129 &context_stack,
1130 DispatchPhase::Bubble,
1131 self,
1132 ) {
1133 self.dispatch_action(action, &key_dispatch_stack[..ix]);
1134 }
1135
1136 if !self.app.propagate_event {
1137 break;
1138 }
1139 }
1140 }
1141 KeyDispatchStackFrame::Context(_) => {
1142 context_stack.pop();
1143 }
1144 }
1145 }
1146 }
1147
1148 drop(context_stack);
1149 self.window.key_dispatch_stack = key_dispatch_stack;
1150 }
1151
1152 true
1153 }
1154
1155 /// Attempt to map a keystroke to an action based on the keymap.
1156 pub fn match_keystroke(
1157 &mut self,
1158 element_id: &GlobalElementId,
1159 keystroke: &Keystroke,
1160 context_stack: &[&DispatchContext],
1161 ) -> KeyMatch {
1162 let key_match = self
1163 .window
1164 .key_matchers
1165 .get_mut(element_id)
1166 .unwrap()
1167 .match_keystroke(keystroke, context_stack);
1168
1169 if key_match.is_some() {
1170 for matcher in self.window.key_matchers.values_mut() {
1171 matcher.clear_pending();
1172 }
1173 }
1174
1175 key_match
1176 }
1177
1178 /// Register the given handler to be invoked whenever the global of the given type
1179 /// is updated.
1180 pub fn observe_global<G: 'static>(
1181 &mut self,
1182 f: impl Fn(&mut WindowContext<'_>) + Send + 'static,
1183 ) -> Subscription {
1184 let window_handle = self.window.handle;
1185 self.global_observers.insert(
1186 TypeId::of::<G>(),
1187 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1188 )
1189 }
1190
1191 fn dispatch_action(
1192 &mut self,
1193 action: Box<dyn Action>,
1194 dispatch_stack: &[KeyDispatchStackFrame],
1195 ) {
1196 let action_type = action.as_any().type_id();
1197
1198 if let Some(mut global_listeners) = self.app.global_action_listeners.remove(&action_type) {
1199 for listener in &global_listeners {
1200 listener(action.as_ref(), DispatchPhase::Capture, self);
1201 if !self.app.propagate_event {
1202 break;
1203 }
1204 }
1205 global_listeners.extend(
1206 self.global_action_listeners
1207 .remove(&action_type)
1208 .unwrap_or_default(),
1209 );
1210 self.global_action_listeners
1211 .insert(action_type, global_listeners);
1212 }
1213
1214 if self.app.propagate_event {
1215 for stack_frame in dispatch_stack {
1216 if let KeyDispatchStackFrame::Listener {
1217 event_type,
1218 listener,
1219 } = stack_frame
1220 {
1221 if action_type == *event_type {
1222 listener(action.as_any(), &[], DispatchPhase::Capture, self);
1223 if !self.app.propagate_event {
1224 break;
1225 }
1226 }
1227 }
1228 }
1229 }
1230
1231 if self.app.propagate_event {
1232 for stack_frame in dispatch_stack.iter().rev() {
1233 if let KeyDispatchStackFrame::Listener {
1234 event_type,
1235 listener,
1236 } = stack_frame
1237 {
1238 if action_type == *event_type {
1239 listener(action.as_any(), &[], DispatchPhase::Bubble, self);
1240 if !self.app.propagate_event {
1241 break;
1242 }
1243 }
1244 }
1245 }
1246 }
1247
1248 if self.app.propagate_event {
1249 if let Some(mut global_listeners) =
1250 self.app.global_action_listeners.remove(&action_type)
1251 {
1252 for listener in global_listeners.iter().rev() {
1253 listener(action.as_ref(), DispatchPhase::Bubble, self);
1254 if !self.app.propagate_event {
1255 break;
1256 }
1257 }
1258 global_listeners.extend(
1259 self.global_action_listeners
1260 .remove(&action_type)
1261 .unwrap_or_default(),
1262 );
1263 self.global_action_listeners
1264 .insert(action_type, global_listeners);
1265 }
1266 }
1267 }
1268}
1269
1270impl Context for WindowContext<'_> {
1271 type WindowContext<'a> = WindowContext<'a>;
1272 type ModelContext<'a, T> = ModelContext<'a, T>;
1273 type Result<T> = T;
1274
1275 fn build_model<T>(
1276 &mut self,
1277 build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
1278 ) -> Model<T>
1279 where
1280 T: 'static + Send,
1281 {
1282 let slot = self.app.entities.reserve();
1283 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1284 self.entities.insert(slot, model)
1285 }
1286
1287 fn update_model<T: 'static, R>(
1288 &mut self,
1289 model: &Model<T>,
1290 update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
1291 ) -> R {
1292 let mut entity = self.entities.lease(model);
1293 let result = update(
1294 &mut *entity,
1295 &mut ModelContext::new(&mut *self.app, model.downgrade()),
1296 );
1297 self.entities.end_lease(entity);
1298 result
1299 }
1300
1301 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1302 where
1303 F: FnOnce(AnyView, &mut Self::WindowContext<'_>) -> T,
1304 {
1305 if window == self.window.handle {
1306 let root_view = self.window.root_view.clone().unwrap();
1307 Ok(update(root_view, self))
1308 } else {
1309 window.update(self.app, update)
1310 }
1311 }
1312}
1313
1314impl VisualContext for WindowContext<'_> {
1315 type ViewContext<'a, V: 'static> = ViewContext<'a, V>;
1316
1317 fn build_view<V>(
1318 &mut self,
1319 build_view_state: impl FnOnce(&mut Self::ViewContext<'_, V>) -> V,
1320 ) -> Self::Result<View<V>>
1321 where
1322 V: 'static + Send,
1323 {
1324 let slot = self.app.entities.reserve();
1325 let view = View {
1326 model: slot.clone(),
1327 };
1328 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1329 let entity = build_view_state(&mut cx);
1330 self.entities.insert(slot, entity);
1331 view
1332 }
1333
1334 /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1335 fn update_view<T: 'static, R>(
1336 &mut self,
1337 view: &View<T>,
1338 update: impl FnOnce(&mut T, &mut Self::ViewContext<'_, T>) -> R,
1339 ) -> Self::Result<R> {
1340 let mut lease = self.app.entities.lease(&view.model);
1341 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1342 let result = update(&mut *lease, &mut cx);
1343 cx.app.entities.end_lease(lease);
1344 result
1345 }
1346
1347 fn replace_root_view<V>(
1348 &mut self,
1349 build_view: impl FnOnce(&mut Self::ViewContext<'_, V>) -> V,
1350 ) -> Self::Result<View<V>>
1351 where
1352 V: 'static + Send + Render,
1353 {
1354 let slot = self.app.entities.reserve();
1355 let view = View {
1356 model: slot.clone(),
1357 };
1358 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1359 let entity = build_view(&mut cx);
1360 self.entities.insert(slot, entity);
1361 self.window.root_view = Some(view.clone().into());
1362 view
1363 }
1364}
1365
1366impl UpdateView for WindowContext<'_> {
1367 type ViewContext<'a, V: 'static> = ViewContext<'a, V>;
1368
1369 fn update_view<V: 'static, R>(
1370 &mut self,
1371 view: &View<V>,
1372 update: impl FnOnce(&mut V, &mut Self::ViewContext<'_, V>) -> R,
1373 ) -> R {
1374 VisualContext::update_view(self, view, update)
1375 }
1376}
1377
1378impl<'a> std::ops::Deref for WindowContext<'a> {
1379 type Target = AppContext;
1380
1381 fn deref(&self) -> &Self::Target {
1382 &self.app
1383 }
1384}
1385
1386impl<'a> std::ops::DerefMut for WindowContext<'a> {
1387 fn deref_mut(&mut self) -> &mut Self::Target {
1388 &mut self.app
1389 }
1390}
1391
1392impl<'a> Borrow<AppContext> for WindowContext<'a> {
1393 fn borrow(&self) -> &AppContext {
1394 &self.app
1395 }
1396}
1397
1398impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1399 fn borrow_mut(&mut self) -> &mut AppContext {
1400 &mut self.app
1401 }
1402}
1403
1404pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1405 fn app_mut(&mut self) -> &mut AppContext {
1406 self.borrow_mut()
1407 }
1408
1409 fn window(&self) -> &Window {
1410 self.borrow()
1411 }
1412
1413 fn window_mut(&mut self) -> &mut Window {
1414 self.borrow_mut()
1415 }
1416
1417 /// Pushes the given element id onto the global stack and invokes the given closure
1418 /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1419 /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1420 /// used to associate state with identified elements across separate frames.
1421 fn with_element_id<R>(
1422 &mut self,
1423 id: impl Into<ElementId>,
1424 f: impl FnOnce(GlobalElementId, &mut Self) -> R,
1425 ) -> R {
1426 let keymap = self.app_mut().keymap.clone();
1427 let window = self.window_mut();
1428 window.element_id_stack.push(id.into());
1429 let global_id = window.element_id_stack.clone();
1430
1431 if window.key_matchers.get(&global_id).is_none() {
1432 window.key_matchers.insert(
1433 global_id.clone(),
1434 window
1435 .prev_frame_key_matchers
1436 .remove(&global_id)
1437 .unwrap_or_else(|| KeyMatcher::new(keymap)),
1438 );
1439 }
1440
1441 let result = f(global_id, self);
1442 let window: &mut Window = self.borrow_mut();
1443 window.element_id_stack.pop();
1444 result
1445 }
1446
1447 /// Invoke the given function with the given content mask after intersecting it
1448 /// with the current mask.
1449 fn with_content_mask<R>(
1450 &mut self,
1451 mask: ContentMask<Pixels>,
1452 f: impl FnOnce(&mut Self) -> R,
1453 ) -> R {
1454 let mask = mask.intersect(&self.content_mask());
1455 self.window_mut().content_mask_stack.push(mask);
1456 let result = f(self);
1457 self.window_mut().content_mask_stack.pop();
1458 result
1459 }
1460
1461 /// Update the global element offset based on the given offset. This is used to implement
1462 /// scrolling and position drag handles.
1463 fn with_element_offset<R>(
1464 &mut self,
1465 offset: Option<Point<Pixels>>,
1466 f: impl FnOnce(&mut Self) -> R,
1467 ) -> R {
1468 let Some(offset) = offset else {
1469 return f(self);
1470 };
1471
1472 let offset = self.element_offset() + offset;
1473 self.window_mut().element_offset_stack.push(offset);
1474 let result = f(self);
1475 self.window_mut().element_offset_stack.pop();
1476 result
1477 }
1478
1479 /// Obtain the current element offset.
1480 fn element_offset(&self) -> Point<Pixels> {
1481 self.window()
1482 .element_offset_stack
1483 .last()
1484 .copied()
1485 .unwrap_or_default()
1486 }
1487
1488 /// Update or intialize state for an element with the given id that lives across multiple
1489 /// frames. If an element with this id existed in the previous frame, its state will be passed
1490 /// to the given closure. The state returned by the closure will be stored so it can be referenced
1491 /// when drawing the next frame.
1492 fn with_element_state<S, R>(
1493 &mut self,
1494 id: ElementId,
1495 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1496 ) -> R
1497 where
1498 S: 'static + Send,
1499 {
1500 self.with_element_id(id, |global_id, cx| {
1501 if let Some(any) = cx
1502 .window_mut()
1503 .element_states
1504 .remove(&global_id)
1505 .or_else(|| cx.window_mut().prev_frame_element_states.remove(&global_id))
1506 {
1507 // Using the extra inner option to avoid needing to reallocate a new box.
1508 let mut state_box = any
1509 .downcast::<Option<S>>()
1510 .expect("invalid element state type for id");
1511 let state = state_box
1512 .take()
1513 .expect("element state is already on the stack");
1514 let (result, state) = f(Some(state), cx);
1515 state_box.replace(state);
1516 cx.window_mut().element_states.insert(global_id, state_box);
1517 result
1518 } else {
1519 let (result, state) = f(None, cx);
1520 cx.window_mut()
1521 .element_states
1522 .insert(global_id, Box::new(Some(state)));
1523 result
1524 }
1525 })
1526 }
1527
1528 /// Like `with_element_state`, but for situations where the element_id is optional. If the
1529 /// id is `None`, no state will be retrieved or stored.
1530 fn with_optional_element_state<S, R>(
1531 &mut self,
1532 element_id: Option<ElementId>,
1533 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1534 ) -> R
1535 where
1536 S: 'static + Send,
1537 {
1538 if let Some(element_id) = element_id {
1539 self.with_element_state(element_id, f)
1540 } else {
1541 f(None, self).0
1542 }
1543 }
1544
1545 /// Obtain the current content mask.
1546 fn content_mask(&self) -> ContentMask<Pixels> {
1547 self.window()
1548 .content_mask_stack
1549 .last()
1550 .cloned()
1551 .unwrap_or_else(|| ContentMask {
1552 bounds: Bounds {
1553 origin: Point::default(),
1554 size: self.window().content_size,
1555 },
1556 })
1557 }
1558
1559 /// The size of an em for the base font of the application. Adjusting this value allows the
1560 /// UI to scale, just like zooming a web page.
1561 fn rem_size(&self) -> Pixels {
1562 self.window().rem_size
1563 }
1564}
1565
1566impl Borrow<Window> for WindowContext<'_> {
1567 fn borrow(&self) -> &Window {
1568 &self.window
1569 }
1570}
1571
1572impl BorrowMut<Window> for WindowContext<'_> {
1573 fn borrow_mut(&mut self) -> &mut Window {
1574 &mut self.window
1575 }
1576}
1577
1578impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1579
1580pub struct ViewContext<'a, V> {
1581 window_cx: WindowContext<'a>,
1582 view: &'a View<V>,
1583}
1584
1585impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1586 fn borrow(&self) -> &AppContext {
1587 &*self.window_cx.app
1588 }
1589}
1590
1591impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1592 fn borrow_mut(&mut self) -> &mut AppContext {
1593 &mut *self.window_cx.app
1594 }
1595}
1596
1597impl<V> Borrow<Window> for ViewContext<'_, V> {
1598 fn borrow(&self) -> &Window {
1599 &*self.window_cx.window
1600 }
1601}
1602
1603impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1604 fn borrow_mut(&mut self) -> &mut Window {
1605 &mut *self.window_cx.window
1606 }
1607}
1608
1609impl<'a, V: 'static> ViewContext<'a, V> {
1610 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1611 Self {
1612 window_cx: WindowContext::new(app, window),
1613 view,
1614 }
1615 }
1616
1617 pub fn view(&self) -> View<V> {
1618 self.view.clone()
1619 }
1620
1621 pub fn model(&self) -> Model<V> {
1622 self.view.model.clone()
1623 }
1624
1625 pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1626 self.window.z_index_stack.push(order);
1627 let result = f(self);
1628 self.window.z_index_stack.pop();
1629 result
1630 }
1631
1632 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + Send + 'static)
1633 where
1634 V: Any + Send,
1635 {
1636 let view = self.view();
1637 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1638 }
1639
1640 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1641 /// that are currently on the stack to be returned to the app.
1642 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static + Send) {
1643 let view = self.view().downgrade();
1644 self.window_cx.defer(move |cx| {
1645 view.update(cx, f).ok();
1646 });
1647 }
1648
1649 pub fn observe<V2, E>(
1650 &mut self,
1651 entity: &E,
1652 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + Send + 'static,
1653 ) -> Subscription
1654 where
1655 V2: 'static,
1656 V: 'static + Send,
1657 E: Entity<V2>,
1658 {
1659 let view = self.view().downgrade();
1660 let entity_id = entity.entity_id();
1661 let entity = entity.downgrade();
1662 let window_handle = self.window.handle;
1663 self.app.observers.insert(
1664 entity_id,
1665 Box::new(move |cx| {
1666 window_handle
1667 .update(cx, |_, cx| {
1668 if let Some(handle) = E::upgrade_from(&entity) {
1669 view.update(cx, |this, cx| on_notify(this, handle, cx))
1670 .is_ok()
1671 } else {
1672 false
1673 }
1674 })
1675 .unwrap_or(false)
1676 }),
1677 )
1678 }
1679
1680 pub fn subscribe<V2, E>(
1681 &mut self,
1682 entity: &E,
1683 mut on_event: impl FnMut(&mut V, E, &V2::Event, &mut ViewContext<'_, V>) + Send + 'static,
1684 ) -> Subscription
1685 where
1686 V2: EventEmitter,
1687 E: Entity<V2>,
1688 {
1689 let view = self.view().downgrade();
1690 let entity_id = entity.entity_id();
1691 let handle = entity.downgrade();
1692 let window_handle = self.window.handle;
1693 self.app.event_listeners.insert(
1694 entity_id,
1695 Box::new(move |event, cx| {
1696 window_handle
1697 .update(cx, |_, cx| {
1698 if let Some(handle) = E::upgrade_from(&handle) {
1699 let event = event.downcast_ref().expect("invalid event type");
1700 view.update(cx, |this, cx| on_event(this, handle, event, cx))
1701 .is_ok()
1702 } else {
1703 false
1704 }
1705 })
1706 .unwrap_or(false)
1707 }),
1708 )
1709 }
1710
1711 pub fn on_release(
1712 &mut self,
1713 on_release: impl FnOnce(&mut V, &mut WindowContext) + Send + 'static,
1714 ) -> Subscription {
1715 let window_handle = self.window.handle;
1716 self.app.release_listeners.insert(
1717 self.view.model.entity_id,
1718 Box::new(move |this, cx| {
1719 let this = this.downcast_mut().expect("invalid entity type");
1720 // todo!("are we okay with silently swallowing the error?")
1721 let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
1722 }),
1723 )
1724 }
1725
1726 pub fn observe_release<V2, E>(
1727 &mut self,
1728 entity: &E,
1729 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + Send + 'static,
1730 ) -> Subscription
1731 where
1732 V: Any + Send,
1733 V2: 'static,
1734 E: Entity<V2>,
1735 {
1736 let view = self.view().downgrade();
1737 let entity_id = entity.entity_id();
1738 let window_handle = self.window.handle;
1739 self.app.release_listeners.insert(
1740 entity_id,
1741 Box::new(move |entity, cx| {
1742 let entity = entity.downcast_mut().expect("invalid entity type");
1743 let _ = window_handle.update(cx, |_, cx| {
1744 view.update(cx, |this, cx| on_release(this, entity, cx))
1745 });
1746 }),
1747 )
1748 }
1749
1750 pub fn notify(&mut self) {
1751 self.window_cx.notify();
1752 self.window_cx.app.push_effect(Effect::Notify {
1753 emitter: self.view.model.entity_id,
1754 });
1755 }
1756
1757 pub fn on_focus_changed(
1758 &mut self,
1759 listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,
1760 ) {
1761 let handle = self.view().downgrade();
1762 self.window.focus_listeners.push(Box::new(move |event, cx| {
1763 handle
1764 .update(cx, |view, cx| listener(view, event, cx))
1765 .log_err();
1766 }));
1767 }
1768
1769 pub fn with_key_listeners<R>(
1770 &mut self,
1771 key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
1772 f: impl FnOnce(&mut Self) -> R,
1773 ) -> R {
1774 let old_stack_len = self.window.key_dispatch_stack.len();
1775 if !self.window.freeze_key_dispatch_stack {
1776 for (event_type, listener) in key_listeners {
1777 let handle = self.view().downgrade();
1778 let listener = Box::new(
1779 move |event: &dyn Any,
1780 context_stack: &[&DispatchContext],
1781 phase: DispatchPhase,
1782 cx: &mut WindowContext<'_>| {
1783 handle
1784 .update(cx, |view, cx| {
1785 listener(view, event, context_stack, phase, cx)
1786 })
1787 .log_err()
1788 .flatten()
1789 },
1790 );
1791 self.window
1792 .key_dispatch_stack
1793 .push(KeyDispatchStackFrame::Listener {
1794 event_type,
1795 listener,
1796 });
1797 }
1798 }
1799
1800 let result = f(self);
1801
1802 if !self.window.freeze_key_dispatch_stack {
1803 self.window.key_dispatch_stack.truncate(old_stack_len);
1804 }
1805
1806 result
1807 }
1808
1809 pub fn with_key_dispatch_context<R>(
1810 &mut self,
1811 context: DispatchContext,
1812 f: impl FnOnce(&mut Self) -> R,
1813 ) -> R {
1814 if context.is_empty() {
1815 return f(self);
1816 }
1817
1818 if !self.window.freeze_key_dispatch_stack {
1819 self.window
1820 .key_dispatch_stack
1821 .push(KeyDispatchStackFrame::Context(context));
1822 }
1823
1824 let result = f(self);
1825
1826 if !self.window.freeze_key_dispatch_stack {
1827 self.window.key_dispatch_stack.pop();
1828 }
1829
1830 result
1831 }
1832
1833 pub fn with_focus<R>(
1834 &mut self,
1835 focus_handle: FocusHandle,
1836 f: impl FnOnce(&mut Self) -> R,
1837 ) -> R {
1838 if let Some(parent_focus_id) = self.window.focus_stack.last().copied() {
1839 self.window
1840 .focus_parents_by_child
1841 .insert(focus_handle.id, parent_focus_id);
1842 }
1843 self.window.focus_stack.push(focus_handle.id);
1844
1845 if Some(focus_handle.id) == self.window.focus {
1846 self.window.freeze_key_dispatch_stack = true;
1847 }
1848
1849 let result = f(self);
1850
1851 self.window.focus_stack.pop();
1852 result
1853 }
1854
1855 pub fn run_on_main<R>(
1856 &mut self,
1857 view: &mut V,
1858 f: impl FnOnce(&mut V, &mut MainThread<ViewContext<'_, V>>) -> R + Send + 'static,
1859 ) -> Task<Result<R>>
1860 where
1861 R: Send + 'static,
1862 {
1863 if self.executor.is_main_thread() {
1864 let cx = unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(self) };
1865 Task::ready(Ok(f(view, cx)))
1866 } else {
1867 let view = self.view();
1868 self.window_cx.run_on_main(move |cx| view.update(cx, f))
1869 }
1870 }
1871
1872 pub fn spawn<Fut, R>(
1873 &mut self,
1874 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
1875 ) -> Task<R>
1876 where
1877 R: Send + 'static,
1878 Fut: Future<Output = R> + Send + 'static,
1879 {
1880 let view = self.view().downgrade();
1881 self.window_cx.spawn(move |_, cx| f(view, cx))
1882 }
1883
1884 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
1885 where
1886 G: 'static + Send,
1887 {
1888 let mut global = self.app.lease_global::<G>();
1889 let result = f(&mut global, self);
1890 self.app.end_global_lease(global);
1891 result
1892 }
1893
1894 pub fn observe_global<G: 'static>(
1895 &mut self,
1896 f: impl Fn(&mut V, &mut ViewContext<'_, V>) + Send + 'static,
1897 ) -> Subscription {
1898 let window_handle = self.window.handle;
1899 let view = self.view().downgrade();
1900 self.global_observers.insert(
1901 TypeId::of::<G>(),
1902 Box::new(move |cx| {
1903 window_handle
1904 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
1905 .unwrap_or(false)
1906 }),
1907 )
1908 }
1909
1910 pub fn on_mouse_event<Event: 'static>(
1911 &mut self,
1912 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + Send + 'static,
1913 ) {
1914 let handle = self.view();
1915 self.window_cx.on_mouse_event(move |event, phase, cx| {
1916 handle.update(cx, |view, cx| {
1917 handler(view, event, phase, cx);
1918 })
1919 });
1920 }
1921}
1922
1923impl<V> ViewContext<'_, V>
1924where
1925 V: EventEmitter,
1926 V::Event: 'static + Send,
1927{
1928 pub fn emit(&mut self, event: V::Event) {
1929 let emitter = self.view.model.entity_id;
1930 self.app.push_effect(Effect::Emit {
1931 emitter,
1932 event: Box::new(event),
1933 });
1934 }
1935}
1936
1937impl<V: 'static> MainThread<ViewContext<'_, V>> {
1938 fn platform_window(&self) -> &dyn PlatformWindow {
1939 self.window.platform_window.borrow_on_main_thread().as_ref()
1940 }
1941
1942 pub fn activate_window(&self) {
1943 self.platform_window().activate();
1944 }
1945}
1946
1947impl<V> Context for ViewContext<'_, V> {
1948 type WindowContext<'a> = WindowContext<'a>;
1949 type ModelContext<'b, U> = ModelContext<'b, U>;
1950 type Result<U> = U;
1951
1952 fn build_model<T>(
1953 &mut self,
1954 build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
1955 ) -> Model<T>
1956 where
1957 T: 'static + Send,
1958 {
1959 self.window_cx.build_model(build_model)
1960 }
1961
1962 fn update_model<T: 'static, R>(
1963 &mut self,
1964 model: &Model<T>,
1965 update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
1966 ) -> R {
1967 self.window_cx.update_model(model, update)
1968 }
1969
1970 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1971 where
1972 F: FnOnce(AnyView, &mut Self::WindowContext<'_>) -> T,
1973 {
1974 self.window_cx.update_window(window, update)
1975 }
1976}
1977
1978impl<V: 'static> VisualContext for ViewContext<'_, V> {
1979 type ViewContext<'a, W: 'static> = ViewContext<'a, W>;
1980
1981 fn build_view<W: 'static + Send>(
1982 &mut self,
1983 build_view: impl FnOnce(&mut Self::ViewContext<'_, W>) -> W,
1984 ) -> Self::Result<View<W>> {
1985 self.window_cx.build_view(build_view)
1986 }
1987
1988 fn update_view<V2: 'static, R>(
1989 &mut self,
1990 view: &View<V2>,
1991 update: impl FnOnce(&mut V2, &mut Self::ViewContext<'_, V2>) -> R,
1992 ) -> Self::Result<R> {
1993 VisualContext::update_view(&mut self.window_cx, view, update)
1994 }
1995
1996 fn replace_root_view<W>(
1997 &mut self,
1998 build_view: impl FnOnce(&mut Self::ViewContext<'_, W>) -> W,
1999 ) -> Self::Result<View<W>>
2000 where
2001 W: 'static + Send + Render,
2002 {
2003 self.window_cx.replace_root_view(build_view)
2004 }
2005}
2006
2007impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2008 type Target = WindowContext<'a>;
2009
2010 fn deref(&self) -> &Self::Target {
2011 &self.window_cx
2012 }
2013}
2014
2015impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2016 fn deref_mut(&mut self) -> &mut Self::Target {
2017 &mut self.window_cx
2018 }
2019}
2020
2021// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2022slotmap::new_key_type! { pub struct WindowId; }
2023
2024impl WindowId {
2025 pub fn as_u64(&self) -> u64 {
2026 self.0.as_ffi()
2027 }
2028}
2029
2030#[derive(Deref, DerefMut)]
2031pub struct WindowHandle<V> {
2032 #[deref]
2033 #[deref_mut]
2034 pub(crate) any_handle: AnyWindowHandle,
2035 state_type: PhantomData<V>,
2036}
2037
2038impl<V: 'static + Render> WindowHandle<V> {
2039 pub fn new(id: WindowId) -> Self {
2040 WindowHandle {
2041 any_handle: AnyWindowHandle {
2042 id,
2043 state_type: TypeId::of::<V>(),
2044 },
2045 state_type: PhantomData,
2046 }
2047 }
2048
2049 pub fn update<C, R>(
2050 &self,
2051 cx: &mut C,
2052 update: impl FnOnce(&mut V, &mut <C::WindowContext<'_> as UpdateView>::ViewContext<'_, V>) -> R,
2053 ) -> Result<R>
2054 where
2055 C: Context,
2056 {
2057 cx.update_window(self.any_handle, |root_view, cx| {
2058 let view = root_view
2059 .downcast::<V>()
2060 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2061
2062 Ok(cx.update_view(&view, update))
2063 })?
2064 }
2065}
2066
2067impl<V> Copy for WindowHandle<V> {}
2068
2069impl<V> Clone for WindowHandle<V> {
2070 fn clone(&self) -> Self {
2071 WindowHandle {
2072 any_handle: self.any_handle,
2073 state_type: PhantomData,
2074 }
2075 }
2076}
2077
2078impl<V> PartialEq for WindowHandle<V> {
2079 fn eq(&self, other: &Self) -> bool {
2080 self.any_handle == other.any_handle
2081 }
2082}
2083
2084impl<V> Eq for WindowHandle<V> {}
2085
2086impl<V> Hash for WindowHandle<V> {
2087 fn hash<H: Hasher>(&self, state: &mut H) {
2088 self.any_handle.hash(state);
2089 }
2090}
2091
2092impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2093 fn into(self) -> AnyWindowHandle {
2094 self.any_handle
2095 }
2096}
2097
2098#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2099pub struct AnyWindowHandle {
2100 pub(crate) id: WindowId,
2101 state_type: TypeId,
2102}
2103
2104impl AnyWindowHandle {
2105 pub fn window_id(&self) -> WindowId {
2106 self.id
2107 }
2108
2109 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2110 if TypeId::of::<T>() == self.state_type {
2111 Some(WindowHandle {
2112 any_handle: *self,
2113 state_type: PhantomData,
2114 })
2115 } else {
2116 None
2117 }
2118 }
2119
2120 pub fn update<C, R>(
2121 &self,
2122 cx: &mut C,
2123 update: impl FnOnce(AnyView, &mut C::WindowContext<'_>) -> R,
2124 ) -> Result<R>
2125 where
2126 C: Context,
2127 {
2128 cx.update_window(*self, update)
2129 }
2130}
2131
2132#[cfg(any(test, feature = "test-support"))]
2133impl From<SmallVec<[u32; 16]>> for StackingOrder {
2134 fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2135 StackingOrder(small_vec)
2136 }
2137}
2138
2139#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2140pub enum ElementId {
2141 View(EntityId),
2142 Number(usize),
2143 Name(SharedString),
2144 FocusHandle(FocusId),
2145}
2146
2147impl From<EntityId> for ElementId {
2148 fn from(id: EntityId) -> Self {
2149 ElementId::View(id)
2150 }
2151}
2152
2153impl From<usize> for ElementId {
2154 fn from(id: usize) -> Self {
2155 ElementId::Number(id)
2156 }
2157}
2158
2159impl From<i32> for ElementId {
2160 fn from(id: i32) -> Self {
2161 Self::Number(id as usize)
2162 }
2163}
2164
2165impl From<SharedString> for ElementId {
2166 fn from(name: SharedString) -> Self {
2167 ElementId::Name(name)
2168 }
2169}
2170
2171impl From<&'static str> for ElementId {
2172 fn from(name: &'static str) -> Self {
2173 ElementId::Name(name.into())
2174 }
2175}
2176
2177impl<'a> From<&'a FocusHandle> for ElementId {
2178 fn from(handle: &'a FocusHandle) -> Self {
2179 ElementId::FocusHandle(handle.id)
2180 }
2181}