1use crate::{
2 px, size, AnyBox, AnyView, AppContext, AsyncWindowContext, AvailableSpace, BorrowAppContext,
3 Bounds, BoxShadow, Context, Corners, DevicePixels, DisplayId, Edges, Effect, Element, EntityId,
4 EventEmitter, FocusEvent, FontId, GlobalElementId, GlyphId, Handle, Hsla, ImageData,
5 InputEvent, IsZero, KeyDownEvent, KeyDownListener, KeyUpEvent, KeyUpListener, LayoutId,
6 MainThread, MainThreadOnly, MonochromeSprite, MouseMoveEvent, Path, Pixels, Platform,
7 PlatformAtlas, PlatformWindow, Point, PolychromeSprite, Quad, Reference, RenderGlyphParams,
8 RenderImageParams, RenderSvgParams, ScaledPixels, SceneBuilder, Shadow, SharedString, Size,
9 Style, Subscription, TaffyLayoutEngine, Task, Underline, UnderlineStyle, WeakHandle,
10 WindowOptions, SUBPIXEL_VARIANTS,
11};
12use anyhow::Result;
13use collections::{HashMap, HashSet};
14use derive_more::{Deref, DerefMut};
15use smallvec::SmallVec;
16use std::{
17 any::{Any, TypeId},
18 borrow::Cow,
19 fmt::Debug,
20 future::Future,
21 marker::PhantomData,
22 mem,
23 sync::Arc,
24};
25use util::{post_inc, ResultExt};
26
27#[derive(Deref, DerefMut, Ord, PartialOrd, Eq, PartialEq, Clone, Default)]
28pub struct StackingOrder(pub(crate) SmallVec<[u32; 16]>);
29
30#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
31pub enum DispatchPhase {
32 /// After the capture phase comes the bubble phase, in which event handlers are
33 /// invoked front to back. This is the phase you'll usually want to use for event handlers.
34 #[default]
35 Bubble,
36 /// During the initial capture phase, event handlers are invoked back to front. This phase
37 /// is used for special purposes such as clearing the "pressed" state for click events. If
38 /// you stop event propagation during this phase, you need to know what you're doing. Handlers
39 /// outside of the immediate region may rely on detecting non-local events during this phase.
40 Capture,
41}
42
43type MouseEventHandler =
44 Arc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + Send + Sync + 'static>;
45
46#[derive(Copy, Clone, PartialEq, Eq, Hash)]
47pub struct FocusId(usize);
48
49#[derive(Clone)]
50pub struct FocusHandle {
51 pub(crate) id: FocusId,
52}
53
54impl FocusHandle {
55 pub(crate) fn new(id: FocusId) -> Self {
56 Self { id }
57 }
58
59 pub fn is_focused(&self, cx: &WindowContext) -> bool {
60 cx.window.focus == Some(self.id)
61 }
62
63 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
64 cx.window.containing_focus.contains(&self.id)
65 }
66
67 pub fn within_focused(&self, cx: &WindowContext) -> bool {
68 let mut ancestor = Some(self.id);
69 while let Some(ancestor_id) = ancestor {
70 if cx.window.focus == Some(ancestor_id) {
71 return true;
72 } else {
73 ancestor = cx.window.focus_parents_by_child.get(&ancestor_id).copied();
74 }
75 }
76 false
77 }
78}
79
80pub struct Window {
81 handle: AnyWindowHandle,
82 platform_window: MainThreadOnly<Box<dyn PlatformWindow>>,
83 display_id: DisplayId,
84 sprite_atlas: Arc<dyn PlatformAtlas>,
85 rem_size: Pixels,
86 content_size: Size<Pixels>,
87 layout_engine: TaffyLayoutEngine,
88 pub(crate) root_view: Option<AnyView>,
89 pub(crate) element_id_stack: GlobalElementId,
90 prev_element_states: HashMap<GlobalElementId, AnyBox>,
91 element_states: HashMap<GlobalElementId, AnyBox>,
92 z_index_stack: StackingOrder,
93 content_mask_stack: Vec<ContentMask<Pixels>>,
94 mouse_listeners: HashMap<TypeId, Vec<(StackingOrder, MouseEventHandler)>>,
95 focus_stack: Vec<FocusStackFrame>,
96 focus_parents_by_child: HashMap<FocusId, FocusId>,
97 containing_focus: HashSet<FocusId>,
98 pub(crate) focus_change_listeners:
99 Vec<Arc<dyn Fn(&FocusEvent, &mut WindowContext) + Send + Sync + 'static>>,
100 key_down_listeners:
101 Vec<Arc<dyn Fn(&KeyDownEvent, DispatchPhase, &mut WindowContext) + Send + Sync + 'static>>,
102 key_up_listeners:
103 Vec<Arc<dyn Fn(&KeyUpEvent, DispatchPhase, &mut WindowContext) + Send + Sync + 'static>>,
104 propagate_event: bool,
105 mouse_position: Point<Pixels>,
106 scale_factor: f32,
107 pub(crate) scene_builder: SceneBuilder,
108 pub(crate) dirty: bool,
109 pub(crate) last_blur: Option<Option<FocusId>>,
110 pub(crate) focus: Option<FocusId>,
111 next_focus_id: FocusId,
112}
113
114impl Window {
115 pub fn new(
116 handle: AnyWindowHandle,
117 options: WindowOptions,
118 cx: &mut MainThread<AppContext>,
119 ) -> Self {
120 let platform_window = cx.platform().open_window(handle, options);
121 let display_id = platform_window.display().id();
122 let sprite_atlas = platform_window.sprite_atlas();
123 let mouse_position = platform_window.mouse_position();
124 let content_size = platform_window.content_size();
125 let scale_factor = platform_window.scale_factor();
126 platform_window.on_resize(Box::new({
127 let cx = cx.to_async();
128 move |content_size, scale_factor| {
129 cx.update_window(handle, |cx| {
130 cx.window.scale_factor = scale_factor;
131 cx.window.scene_builder = SceneBuilder::new();
132 cx.window.content_size = content_size;
133 cx.window.display_id = cx
134 .window
135 .platform_window
136 .borrow_on_main_thread()
137 .display()
138 .id();
139 cx.window.dirty = true;
140 })
141 .log_err();
142 }
143 }));
144
145 platform_window.on_event({
146 let cx = cx.to_async();
147 Box::new(move |event| {
148 cx.update_window(handle, |cx| cx.dispatch_event(event))
149 .log_err()
150 .unwrap_or(true)
151 })
152 });
153
154 let platform_window = MainThreadOnly::new(Arc::new(platform_window), cx.executor.clone());
155
156 Window {
157 handle,
158 platform_window,
159 display_id,
160 sprite_atlas,
161 rem_size: px(16.),
162 content_size,
163 layout_engine: TaffyLayoutEngine::new(),
164 root_view: None,
165 element_id_stack: GlobalElementId::default(),
166 prev_element_states: HashMap::default(),
167 element_states: HashMap::default(),
168 z_index_stack: StackingOrder(SmallVec::new()),
169 content_mask_stack: Vec::new(),
170 focus_stack: Vec::new(),
171 focus_parents_by_child: HashMap::default(),
172 containing_focus: HashSet::default(),
173 mouse_listeners: HashMap::default(),
174 focus_change_listeners: Vec::new(),
175 key_down_listeners: Vec::new(),
176 key_up_listeners: Vec::new(),
177 propagate_event: true,
178 mouse_position,
179 scale_factor,
180 scene_builder: SceneBuilder::new(),
181 dirty: true,
182 last_blur: None,
183 focus: None,
184 next_focus_id: FocusId(0),
185 }
186 }
187}
188
189#[derive(Clone, Debug, Default, PartialEq, Eq)]
190#[repr(C)]
191pub struct ContentMask<P: Clone + Default + Debug> {
192 pub bounds: Bounds<P>,
193}
194
195impl ContentMask<Pixels> {
196 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
197 ContentMask {
198 bounds: self.bounds.scale(factor),
199 }
200 }
201
202 pub fn intersect(&self, other: &Self) -> Self {
203 let bounds = self.bounds.intersect(&other.bounds);
204 ContentMask { bounds }
205 }
206}
207
208struct FocusStackFrame {
209 handle: FocusHandle,
210 key_down_listeners: SmallVec<
211 [Arc<dyn Fn(&KeyDownEvent, DispatchPhase, &mut WindowContext) + Send + Sync + 'static>; 2],
212 >,
213 key_up_listeners: SmallVec<
214 [Arc<dyn Fn(&KeyUpEvent, DispatchPhase, &mut WindowContext) + Send + Sync + 'static>; 2],
215 >,
216}
217
218pub struct WindowContext<'a, 'w> {
219 app: Reference<'a, AppContext>,
220 pub(crate) window: Reference<'w, Window>,
221}
222
223impl<'a, 'w> WindowContext<'a, 'w> {
224 pub(crate) fn mutable(app: &'a mut AppContext, window: &'w mut Window) -> Self {
225 Self {
226 app: Reference::Mutable(app),
227 window: Reference::Mutable(window),
228 }
229 }
230
231 pub fn notify(&mut self) {
232 self.window.dirty = true;
233 }
234
235 pub fn focus_handle(&mut self) -> FocusHandle {
236 let id = FocusId(post_inc(&mut self.window.next_focus_id.0));
237 FocusHandle { id }
238 }
239
240 pub fn focus(&mut self, handle: &FocusHandle) {
241 if self.window.last_blur.is_none() {
242 self.window.last_blur = Some(self.window.focus);
243 }
244
245 let window_id = self.window.handle.id;
246 self.window.focus = Some(handle.id);
247 self.push_effect(Effect::FocusChanged {
248 window_id,
249 focused: Some(handle.id),
250 });
251 self.notify();
252 }
253
254 pub fn blur(&mut self) {
255 if self.window.last_blur.is_none() {
256 self.window.last_blur = Some(self.window.focus);
257 }
258
259 let window_id = self.window.handle.id;
260 self.window.focus = None;
261 self.push_effect(Effect::FocusChanged {
262 window_id,
263 focused: None,
264 });
265 self.notify();
266 }
267
268 pub fn run_on_main<R>(
269 &mut self,
270 f: impl FnOnce(&mut MainThread<WindowContext<'_, '_>>) -> R + Send + 'static,
271 ) -> Task<Result<R>>
272 where
273 R: Send + 'static,
274 {
275 if self.executor.is_main_thread() {
276 Task::ready(Ok(f(unsafe {
277 mem::transmute::<&mut Self, &mut MainThread<Self>>(self)
278 })))
279 } else {
280 let id = self.window.handle.id;
281 self.app.run_on_main(move |cx| cx.update_window(id, f))
282 }
283 }
284
285 pub fn to_async(&self) -> AsyncWindowContext {
286 AsyncWindowContext::new(self.app.to_async(), self.window.handle)
287 }
288
289 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + Send + 'static) {
290 let f = Box::new(f);
291 let display_id = self.window.display_id;
292 self.run_on_main(move |cx| {
293 if let Some(callbacks) = cx.next_frame_callbacks.get_mut(&display_id) {
294 callbacks.push(f);
295 // If there was already a callback, it means that we already scheduled a frame.
296 if callbacks.len() > 1 {
297 return;
298 }
299 } else {
300 let async_cx = cx.to_async();
301 cx.next_frame_callbacks.insert(display_id, vec![f]);
302 cx.platform().set_display_link_output_callback(
303 display_id,
304 Box::new(move |_current_time, _output_time| {
305 let _ = async_cx.update(|cx| {
306 let callbacks = cx
307 .next_frame_callbacks
308 .get_mut(&display_id)
309 .unwrap()
310 .drain(..)
311 .collect::<Vec<_>>();
312 for callback in callbacks {
313 callback(cx);
314 }
315
316 cx.run_on_main(move |cx| {
317 if cx.next_frame_callbacks.get(&display_id).unwrap().is_empty() {
318 cx.platform().stop_display_link(display_id);
319 }
320 })
321 .detach();
322 });
323 }),
324 );
325 }
326
327 cx.platform().start_display_link(display_id);
328 })
329 .detach();
330 }
331
332 pub fn spawn<Fut, R>(
333 &mut self,
334 f: impl FnOnce(AnyWindowHandle, AsyncWindowContext) -> Fut + Send + 'static,
335 ) -> Task<R>
336 where
337 R: Send + 'static,
338 Fut: Future<Output = R> + Send + 'static,
339 {
340 let window = self.window.handle;
341 self.app.spawn(move |app| {
342 let cx = AsyncWindowContext::new(app, window);
343 let future = f(window, cx);
344 async move { future.await }
345 })
346 }
347
348 pub fn request_layout(
349 &mut self,
350 style: &Style,
351 children: impl IntoIterator<Item = LayoutId>,
352 ) -> LayoutId {
353 self.app.layout_id_buffer.clear();
354 self.app.layout_id_buffer.extend(children.into_iter());
355 let rem_size = self.rem_size();
356
357 self.window
358 .layout_engine
359 .request_layout(style, rem_size, &self.app.layout_id_buffer)
360 }
361
362 pub fn request_measured_layout<
363 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>) -> Size<Pixels> + Send + Sync + 'static,
364 >(
365 &mut self,
366 style: Style,
367 rem_size: Pixels,
368 measure: F,
369 ) -> LayoutId {
370 self.window
371 .layout_engine
372 .request_measured_layout(style, rem_size, measure)
373 }
374
375 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
376 self.window
377 .layout_engine
378 .layout_bounds(layout_id)
379 .map(Into::into)
380 }
381
382 pub fn scale_factor(&self) -> f32 {
383 self.window.scale_factor
384 }
385
386 pub fn rem_size(&self) -> Pixels {
387 self.window.rem_size
388 }
389
390 pub fn stop_propagation(&mut self) {
391 self.window.propagate_event = false;
392 }
393
394 pub fn on_mouse_event<Event: 'static>(
395 &mut self,
396 handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + Send + Sync + 'static,
397 ) {
398 let order = self.window.z_index_stack.clone();
399 self.window
400 .mouse_listeners
401 .entry(TypeId::of::<Event>())
402 .or_default()
403 .push((
404 order,
405 Arc::new(move |event: &dyn Any, phase, cx| {
406 handler(event.downcast_ref().unwrap(), phase, cx)
407 }),
408 ))
409 }
410
411 pub fn mouse_position(&self) -> Point<Pixels> {
412 self.window.mouse_position
413 }
414
415 pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
416 self.window.z_index_stack.push(order);
417 let result = f(self);
418 self.window.z_index_stack.pop();
419 result
420 }
421
422 pub fn paint_shadows(
423 &mut self,
424 bounds: Bounds<Pixels>,
425 corner_radii: Corners<Pixels>,
426 shadows: &[BoxShadow],
427 ) {
428 let scale_factor = self.scale_factor();
429 let content_mask = self.content_mask();
430 let window = &mut *self.window;
431 for shadow in shadows {
432 let mut shadow_bounds = bounds;
433 shadow_bounds.origin += shadow.offset;
434 shadow_bounds.dilate(shadow.spread_radius);
435 window.scene_builder.insert(
436 &window.z_index_stack,
437 Shadow {
438 order: 0,
439 bounds: shadow_bounds.scale(scale_factor),
440 content_mask: content_mask.scale(scale_factor),
441 corner_radii: corner_radii.scale(scale_factor),
442 color: shadow.color,
443 blur_radius: shadow.blur_radius.scale(scale_factor),
444 },
445 );
446 }
447 }
448
449 pub fn paint_quad(
450 &mut self,
451 bounds: Bounds<Pixels>,
452 corner_radii: Corners<Pixels>,
453 background: impl Into<Hsla>,
454 border_widths: Edges<Pixels>,
455 border_color: impl Into<Hsla>,
456 ) {
457 let scale_factor = self.scale_factor();
458 let content_mask = self.content_mask();
459
460 let window = &mut *self.window;
461 window.scene_builder.insert(
462 &window.z_index_stack,
463 Quad {
464 order: 0,
465 bounds: bounds.scale(scale_factor),
466 content_mask: content_mask.scale(scale_factor),
467 background: background.into(),
468 border_color: border_color.into(),
469 corner_radii: corner_radii.scale(scale_factor),
470 border_widths: border_widths.scale(scale_factor),
471 },
472 );
473 }
474
475 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
476 let scale_factor = self.scale_factor();
477 let content_mask = self.content_mask();
478 path.content_mask = content_mask;
479 path.color = color.into();
480 let window = &mut *self.window;
481 window
482 .scene_builder
483 .insert(&window.z_index_stack, path.scale(scale_factor));
484 }
485
486 pub fn paint_underline(
487 &mut self,
488 origin: Point<Pixels>,
489 width: Pixels,
490 style: &UnderlineStyle,
491 ) -> Result<()> {
492 let scale_factor = self.scale_factor();
493 let height = if style.wavy {
494 style.thickness * 3.
495 } else {
496 style.thickness
497 };
498 let bounds = Bounds {
499 origin,
500 size: size(width, height),
501 };
502 let content_mask = self.content_mask();
503 let window = &mut *self.window;
504 window.scene_builder.insert(
505 &window.z_index_stack,
506 Underline {
507 order: 0,
508 bounds: bounds.scale(scale_factor),
509 content_mask: content_mask.scale(scale_factor),
510 thickness: style.thickness.scale(scale_factor),
511 color: style.color.unwrap_or_default(),
512 wavy: style.wavy,
513 },
514 );
515 Ok(())
516 }
517
518 pub fn paint_glyph(
519 &mut self,
520 origin: Point<Pixels>,
521 font_id: FontId,
522 glyph_id: GlyphId,
523 font_size: Pixels,
524 color: Hsla,
525 ) -> Result<()> {
526 let scale_factor = self.scale_factor();
527 let glyph_origin = origin.scale(scale_factor);
528 let subpixel_variant = Point {
529 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
530 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
531 };
532 let params = RenderGlyphParams {
533 font_id,
534 glyph_id,
535 font_size,
536 subpixel_variant,
537 scale_factor,
538 is_emoji: false,
539 };
540
541 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
542 if !raster_bounds.is_zero() {
543 let tile =
544 self.window
545 .sprite_atlas
546 .get_or_insert_with(¶ms.clone().into(), &mut || {
547 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
548 Ok((size, Cow::Owned(bytes)))
549 })?;
550 let bounds = Bounds {
551 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
552 size: tile.bounds.size.map(Into::into),
553 };
554 let content_mask = self.content_mask().scale(scale_factor);
555 let window = &mut *self.window;
556 window.scene_builder.insert(
557 &window.z_index_stack,
558 MonochromeSprite {
559 order: 0,
560 bounds,
561 content_mask,
562 color,
563 tile,
564 },
565 );
566 }
567 Ok(())
568 }
569
570 pub fn paint_emoji(
571 &mut self,
572 origin: Point<Pixels>,
573 font_id: FontId,
574 glyph_id: GlyphId,
575 font_size: Pixels,
576 ) -> Result<()> {
577 let scale_factor = self.scale_factor();
578 let glyph_origin = origin.scale(scale_factor);
579 let params = RenderGlyphParams {
580 font_id,
581 glyph_id,
582 font_size,
583 // We don't render emojis with subpixel variants.
584 subpixel_variant: Default::default(),
585 scale_factor,
586 is_emoji: true,
587 };
588
589 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
590 if !raster_bounds.is_zero() {
591 let tile =
592 self.window
593 .sprite_atlas
594 .get_or_insert_with(¶ms.clone().into(), &mut || {
595 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
596 Ok((size, Cow::Owned(bytes)))
597 })?;
598 let bounds = Bounds {
599 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
600 size: tile.bounds.size.map(Into::into),
601 };
602 let content_mask = self.content_mask().scale(scale_factor);
603 let window = &mut *self.window;
604
605 window.scene_builder.insert(
606 &window.z_index_stack,
607 PolychromeSprite {
608 order: 0,
609 bounds,
610 corner_radii: Default::default(),
611 content_mask,
612 tile,
613 grayscale: false,
614 },
615 );
616 }
617 Ok(())
618 }
619
620 pub fn paint_svg(
621 &mut self,
622 bounds: Bounds<Pixels>,
623 path: SharedString,
624 color: Hsla,
625 ) -> Result<()> {
626 let scale_factor = self.scale_factor();
627 let bounds = bounds.scale(scale_factor);
628 // Render the SVG at twice the size to get a higher quality result.
629 let params = RenderSvgParams {
630 path,
631 size: bounds
632 .size
633 .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
634 };
635
636 let tile =
637 self.window
638 .sprite_atlas
639 .get_or_insert_with(¶ms.clone().into(), &mut || {
640 let bytes = self.svg_renderer.render(¶ms)?;
641 Ok((params.size, Cow::Owned(bytes)))
642 })?;
643 let content_mask = self.content_mask().scale(scale_factor);
644
645 let window = &mut *self.window;
646 window.scene_builder.insert(
647 &window.z_index_stack,
648 MonochromeSprite {
649 order: 0,
650 bounds,
651 content_mask,
652 color,
653 tile,
654 },
655 );
656
657 Ok(())
658 }
659
660 pub fn paint_image(
661 &mut self,
662 bounds: Bounds<Pixels>,
663 corner_radii: Corners<Pixels>,
664 data: Arc<ImageData>,
665 grayscale: bool,
666 ) -> Result<()> {
667 let scale_factor = self.scale_factor();
668 let bounds = bounds.scale(scale_factor);
669 let params = RenderImageParams { image_id: data.id };
670
671 let tile = self
672 .window
673 .sprite_atlas
674 .get_or_insert_with(¶ms.clone().into(), &mut || {
675 Ok((data.size(), Cow::Borrowed(data.as_bytes())))
676 })?;
677 let content_mask = self.content_mask().scale(scale_factor);
678 let corner_radii = corner_radii.scale(scale_factor);
679
680 let window = &mut *self.window;
681 window.scene_builder.insert(
682 &window.z_index_stack,
683 PolychromeSprite {
684 order: 0,
685 bounds,
686 content_mask,
687 corner_radii,
688 tile,
689 grayscale,
690 },
691 );
692 Ok(())
693 }
694
695 pub(crate) fn draw(&mut self) {
696 let unit_entity = self.unit_entity.clone();
697 self.update_entity(&unit_entity, |view, cx| {
698 cx.start_frame();
699
700 let mut root_view = cx.window.root_view.take().unwrap();
701
702 if let Some(element_id) = root_view.id() {
703 cx.with_element_state(element_id, |element_state, cx| {
704 let element_state = draw_with_element_state(&mut root_view, element_state, cx);
705 ((), element_state)
706 });
707 } else {
708 draw_with_element_state(&mut root_view, None, cx);
709 };
710
711 cx.window.root_view = Some(root_view);
712 let scene = cx.window.scene_builder.build();
713 cx.end_frame();
714
715 cx.run_on_main(view, |_, cx| {
716 cx.window
717 .platform_window
718 .borrow_on_main_thread()
719 .draw(scene);
720 cx.window.dirty = false;
721 })
722 .detach();
723 });
724
725 fn draw_with_element_state(
726 root_view: &mut AnyView,
727 element_state: Option<AnyBox>,
728 cx: &mut ViewContext<()>,
729 ) -> AnyBox {
730 let mut element_state = root_view.initialize(&mut (), element_state, cx);
731 let layout_id = root_view.layout(&mut (), &mut element_state, cx);
732 let available_space = cx.window.content_size.map(Into::into);
733 cx.window
734 .layout_engine
735 .compute_layout(layout_id, available_space);
736 let bounds = cx.window.layout_engine.layout_bounds(layout_id);
737 root_view.paint(bounds, &mut (), &mut element_state, cx);
738 element_state
739 }
740 }
741
742 fn start_frame(&mut self) {
743 // Make the current element states the previous, and then clear the current.
744 // The empty element states map will be populated for any element states we
745 // reference during the upcoming frame.
746 let window = &mut *self.window;
747 mem::swap(&mut window.element_states, &mut window.prev_element_states);
748 window.element_states.clear();
749
750 // Clear mouse event listeners, because elements add new element listeners
751 // when the upcoming frame is painted.
752 window.mouse_listeners.values_mut().for_each(Vec::clear);
753
754 // Clear focus state, because we determine what is focused when the new elements
755 // in the upcoming frame are initialized.
756 window.focus_change_listeners.clear();
757 window.key_down_listeners.clear();
758 window.key_up_listeners.clear();
759 window.containing_focus.clear();
760 window.focus_parents_by_child.clear();
761 }
762
763 fn end_frame(&mut self) {
764 self.text_system().end_frame();
765 }
766
767 fn dispatch_event(&mut self, event: InputEvent) -> bool {
768 if let Some(any_mouse_event) = event.mouse_event() {
769 if let Some(MouseMoveEvent { position, .. }) = any_mouse_event.downcast_ref() {
770 self.window.mouse_position = *position;
771 }
772
773 if let Some(mut handlers) = self
774 .window
775 .mouse_listeners
776 .remove(&any_mouse_event.type_id())
777 {
778 // Because handlers may add other handlers, we sort every time.
779 handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
780
781 // Handlers may set this to false by calling `stop_propagation`
782 self.window.propagate_event = true;
783
784 // Capture phase, events bubble from back to front. Handlers for this phase are used for
785 // special purposes, such as detecting events outside of a given Bounds.
786 for (_, handler) in &handlers {
787 handler(any_mouse_event, DispatchPhase::Capture, self);
788 if !self.window.propagate_event {
789 break;
790 }
791 }
792
793 // Bubble phase, where most normal handlers do their work.
794 if self.window.propagate_event {
795 for (_, handler) in handlers.iter().rev() {
796 handler(any_mouse_event, DispatchPhase::Bubble, self);
797 if !self.window.propagate_event {
798 break;
799 }
800 }
801 }
802
803 // Just in case any handlers added new handlers, which is weird, but possible.
804 handlers.extend(
805 self.window
806 .mouse_listeners
807 .get_mut(&any_mouse_event.type_id())
808 .into_iter()
809 .flat_map(|handlers| handlers.drain(..)),
810 );
811 self.window
812 .mouse_listeners
813 .insert(any_mouse_event.type_id(), handlers);
814 }
815 }
816
817 true
818 }
819}
820
821impl<'a, 'w> MainThread<WindowContext<'a, 'w>> {
822 fn platform(&self) -> &dyn Platform {
823 self.platform.borrow_on_main_thread()
824 }
825}
826
827impl Context for WindowContext<'_, '_> {
828 type EntityContext<'a, 'w, T: 'static + Send + Sync> = ViewContext<'a, 'w, T>;
829 type Result<T> = T;
830
831 fn entity<T: Send + Sync + 'static>(
832 &mut self,
833 build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
834 ) -> Handle<T> {
835 let slot = self.app.entities.reserve();
836 let entity = build_entity(&mut ViewContext::mutable(
837 &mut *self.app,
838 &mut self.window,
839 slot.id,
840 ));
841 self.entities.insert(slot, entity)
842 }
843
844 fn update_entity<T: Send + Sync + 'static, R>(
845 &mut self,
846 handle: &Handle<T>,
847 update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
848 ) -> R {
849 let mut entity = self.entities.lease(handle);
850 let result = update(
851 &mut *entity,
852 &mut ViewContext::mutable(&mut *self.app, &mut *self.window, handle.id),
853 );
854 self.entities.end_lease(entity);
855 result
856 }
857}
858
859impl<'a, 'w> std::ops::Deref for WindowContext<'a, 'w> {
860 type Target = AppContext;
861
862 fn deref(&self) -> &Self::Target {
863 &self.app
864 }
865}
866
867impl<'a, 'w> std::ops::DerefMut for WindowContext<'a, 'w> {
868 fn deref_mut(&mut self) -> &mut Self::Target {
869 &mut self.app
870 }
871}
872
873impl BorrowAppContext for WindowContext<'_, '_> {
874 fn app_mut(&mut self) -> &mut AppContext {
875 &mut *self.app
876 }
877}
878
879pub trait BorrowWindow: BorrowAppContext {
880 fn window(&self) -> &Window;
881 fn window_mut(&mut self) -> &mut Window;
882
883 fn with_element_id<R>(
884 &mut self,
885 id: impl Into<ElementId>,
886 f: impl FnOnce(&mut Self) -> R,
887 ) -> R {
888 self.window_mut().element_id_stack.push(id.into());
889 let result = f(self);
890 self.window_mut().element_id_stack.pop();
891 result
892 }
893
894 fn with_content_mask<R>(
895 &mut self,
896 mask: ContentMask<Pixels>,
897 f: impl FnOnce(&mut Self) -> R,
898 ) -> R {
899 let mask = mask.intersect(&self.content_mask());
900 self.window_mut().content_mask_stack.push(mask);
901 let result = f(self);
902 self.window_mut().content_mask_stack.pop();
903 result
904 }
905
906 fn with_element_state<S: 'static + Send + Sync, R>(
907 &mut self,
908 id: ElementId,
909 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
910 ) -> R {
911 self.with_element_id(id, |cx| {
912 let global_id = cx.window_mut().element_id_stack.clone();
913 if let Some(any) = cx
914 .window_mut()
915 .element_states
916 .remove(&global_id)
917 .or_else(|| cx.window_mut().prev_element_states.remove(&global_id))
918 {
919 // Using the extra inner option to avoid needing to reallocate a new box.
920 let mut state_box = any
921 .downcast::<Option<S>>()
922 .expect("invalid element state type for id");
923 let state = state_box
924 .take()
925 .expect("element state is already on the stack");
926 let (result, state) = f(Some(state), cx);
927 state_box.replace(state);
928 cx.window_mut().element_states.insert(global_id, state_box);
929 result
930 } else {
931 let (result, state) = f(None, cx);
932 cx.window_mut()
933 .element_states
934 .insert(global_id, Box::new(Some(state)));
935 result
936 }
937 })
938 }
939
940 fn content_mask(&self) -> ContentMask<Pixels> {
941 self.window()
942 .content_mask_stack
943 .last()
944 .cloned()
945 .unwrap_or_else(|| ContentMask {
946 bounds: Bounds {
947 origin: Point::default(),
948 size: self.window().content_size,
949 },
950 })
951 }
952
953 fn rem_size(&self) -> Pixels {
954 self.window().rem_size
955 }
956}
957
958impl BorrowWindow for WindowContext<'_, '_> {
959 fn window(&self) -> &Window {
960 &*self.window
961 }
962
963 fn window_mut(&mut self) -> &mut Window {
964 &mut *self.window
965 }
966}
967
968pub struct ViewContext<'a, 'w, S> {
969 window_cx: WindowContext<'a, 'w>,
970 entity_type: PhantomData<S>,
971 entity_id: EntityId,
972}
973
974impl<S> BorrowAppContext for ViewContext<'_, '_, S> {
975 fn app_mut(&mut self) -> &mut AppContext {
976 &mut *self.window_cx.app
977 }
978}
979
980impl<S> BorrowWindow for ViewContext<'_, '_, S> {
981 fn window(&self) -> &Window {
982 &self.window_cx.window
983 }
984
985 fn window_mut(&mut self) -> &mut Window {
986 &mut *self.window_cx.window
987 }
988}
989
990impl<'a, 'w, V: Send + Sync + 'static> ViewContext<'a, 'w, V> {
991 fn mutable(app: &'a mut AppContext, window: &'w mut Window, entity_id: EntityId) -> Self {
992 Self {
993 window_cx: WindowContext::mutable(app, window),
994 entity_id,
995 entity_type: PhantomData,
996 }
997 }
998
999 pub fn handle(&self) -> WeakHandle<V> {
1000 self.entities.weak_handle(self.entity_id)
1001 }
1002
1003 pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1004 self.window.z_index_stack.push(order);
1005 let result = f(self);
1006 self.window.z_index_stack.pop();
1007 result
1008 }
1009
1010 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + Send + 'static) {
1011 let entity = self.handle();
1012 self.window_cx.on_next_frame(move |cx| {
1013 entity.update(cx, f).ok();
1014 });
1015 }
1016
1017 pub fn observe<E: Send + Sync + 'static>(
1018 &mut self,
1019 handle: &Handle<E>,
1020 on_notify: impl Fn(&mut V, Handle<E>, &mut ViewContext<'_, '_, V>) + Send + Sync + 'static,
1021 ) -> Subscription {
1022 let this = self.handle();
1023 let handle = handle.downgrade();
1024 let window_handle = self.window.handle;
1025 self.app.observers.insert(
1026 handle.id,
1027 Box::new(move |cx| {
1028 cx.update_window(window_handle.id, |cx| {
1029 if let Some(handle) = handle.upgrade(cx) {
1030 this.update(cx, |this, cx| on_notify(this, handle, cx))
1031 .is_ok()
1032 } else {
1033 false
1034 }
1035 })
1036 .unwrap_or(false)
1037 }),
1038 )
1039 }
1040
1041 pub fn subscribe<E: EventEmitter + Send + Sync + 'static>(
1042 &mut self,
1043 handle: &Handle<E>,
1044 on_event: impl Fn(&mut V, Handle<E>, &E::Event, &mut ViewContext<'_, '_, V>)
1045 + Send
1046 + Sync
1047 + 'static,
1048 ) -> Subscription {
1049 let this = self.handle();
1050 let handle = handle.downgrade();
1051 let window_handle = self.window.handle;
1052 self.app.event_handlers.insert(
1053 handle.id,
1054 Box::new(move |event, cx| {
1055 cx.update_window(window_handle.id, |cx| {
1056 if let Some(handle) = handle.upgrade(cx) {
1057 let event = event.downcast_ref().expect("invalid event type");
1058 this.update(cx, |this, cx| on_event(this, handle, event, cx))
1059 .is_ok()
1060 } else {
1061 false
1062 }
1063 })
1064 .unwrap_or(false)
1065 }),
1066 )
1067 }
1068
1069 pub fn on_release(
1070 &mut self,
1071 on_release: impl Fn(&mut V, &mut WindowContext) + Send + Sync + 'static,
1072 ) -> Subscription {
1073 let window_handle = self.window.handle;
1074 self.app.release_handlers.insert(
1075 self.entity_id,
1076 Box::new(move |this, cx| {
1077 let this = this.downcast_mut().expect("invalid entity type");
1078 // todo!("are we okay with silently swallowing the error?")
1079 let _ = cx.update_window(window_handle.id, |cx| on_release(this, cx));
1080 }),
1081 )
1082 }
1083
1084 pub fn observe_release<E: Send + Sync + 'static>(
1085 &mut self,
1086 handle: &Handle<E>,
1087 on_release: impl Fn(&mut V, &mut E, &mut ViewContext<'_, '_, V>) + Send + Sync + 'static,
1088 ) -> Subscription {
1089 let this = self.handle();
1090 let window_handle = self.window.handle;
1091 self.app.release_handlers.insert(
1092 handle.id,
1093 Box::new(move |entity, cx| {
1094 let entity = entity.downcast_mut().expect("invalid entity type");
1095 // todo!("are we okay with silently swallowing the error?")
1096 let _ = cx.update_window(window_handle.id, |cx| {
1097 this.update(cx, |this, cx| on_release(this, entity, cx))
1098 });
1099 }),
1100 )
1101 }
1102
1103 pub fn notify(&mut self) {
1104 self.window_cx.notify();
1105 self.window_cx.app.push_effect(Effect::Notify {
1106 emitter: self.entity_id,
1107 });
1108 }
1109
1110 pub fn with_focus<R>(
1111 &mut self,
1112 focus_handle: Option<FocusHandle>,
1113 key_down: impl IntoIterator<Item = KeyDownListener<V>>,
1114 key_up: impl IntoIterator<Item = KeyUpListener<V>>,
1115 f: impl FnOnce(&mut Self) -> R,
1116 ) -> R {
1117 let Some(focus_handle) = focus_handle else {
1118 return f(self);
1119 };
1120
1121 let handle = self.handle();
1122 let window = &mut *self.window;
1123 if let Some(parent_frame) = window.focus_stack.last() {
1124 window
1125 .focus_parents_by_child
1126 .insert(focus_handle.id, parent_frame.handle.id);
1127 }
1128
1129 let mut frame = FocusStackFrame {
1130 handle: focus_handle.clone(),
1131 key_down_listeners: SmallVec::new(),
1132 key_up_listeners: SmallVec::new(),
1133 };
1134
1135 for listener in key_down {
1136 let handle = handle.clone();
1137 frame
1138 .key_down_listeners
1139 .push(Arc::new(move |event, phase, cx| {
1140 handle
1141 .update(cx, |view, cx| listener(view, event, phase, cx))
1142 .log_err();
1143 }));
1144 }
1145 for listener in key_up {
1146 let handle = handle.clone();
1147 frame
1148 .key_up_listeners
1149 .push(Arc::new(move |event, phase, cx| {
1150 handle
1151 .update(cx, |view, cx| listener(view, event, phase, cx))
1152 .log_err();
1153 }));
1154 }
1155
1156 window.focus_stack.push(frame);
1157
1158 if Some(focus_handle.id) == window.focus {
1159 for frame in &window.focus_stack {
1160 window.containing_focus.insert(frame.handle.id);
1161 window
1162 .key_down_listeners
1163 .extend_from_slice(&frame.key_down_listeners);
1164 window
1165 .key_up_listeners
1166 .extend_from_slice(&frame.key_up_listeners);
1167 }
1168 }
1169
1170 let result = f(self);
1171 self.window.focus_stack.pop();
1172 result
1173 }
1174
1175 pub fn run_on_main<R>(
1176 &mut self,
1177 view: &mut V,
1178 f: impl FnOnce(&mut V, &mut MainThread<ViewContext<'_, '_, V>>) -> R + Send + 'static,
1179 ) -> Task<Result<R>>
1180 where
1181 R: Send + 'static,
1182 {
1183 if self.executor.is_main_thread() {
1184 let cx = unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(self) };
1185 Task::ready(Ok(f(view, cx)))
1186 } else {
1187 let handle = self.handle().upgrade(self).unwrap();
1188 self.window_cx.run_on_main(move |cx| handle.update(cx, f))
1189 }
1190 }
1191
1192 pub fn spawn<Fut, R>(
1193 &mut self,
1194 f: impl FnOnce(WeakHandle<V>, AsyncWindowContext) -> Fut + Send + 'static,
1195 ) -> Task<R>
1196 where
1197 R: Send + 'static,
1198 Fut: Future<Output = R> + Send + 'static,
1199 {
1200 let handle = self.handle();
1201 self.window_cx.spawn(move |_, cx| {
1202 let result = f(handle, cx);
1203 async move { result.await }
1204 })
1205 }
1206
1207 pub fn on_mouse_event<Event: 'static>(
1208 &mut self,
1209 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + Send + Sync + 'static,
1210 ) {
1211 let handle = self.handle().upgrade(self).unwrap();
1212 self.window_cx.on_mouse_event(move |event, phase, cx| {
1213 handle.update(cx, |view, cx| {
1214 handler(view, event, phase, cx);
1215 })
1216 });
1217 }
1218}
1219
1220impl<'a, 'w, S: EventEmitter + Send + Sync + 'static> ViewContext<'a, 'w, S> {
1221 pub fn emit(&mut self, event: S::Event) {
1222 self.window_cx.app.push_effect(Effect::Emit {
1223 emitter: self.entity_id,
1224 event: Box::new(event),
1225 });
1226 }
1227}
1228
1229impl<'a, 'w, S> Context for ViewContext<'a, 'w, S> {
1230 type EntityContext<'b, 'c, U: 'static + Send + Sync> = ViewContext<'b, 'c, U>;
1231 type Result<U> = U;
1232
1233 fn entity<T2: Send + Sync + 'static>(
1234 &mut self,
1235 build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T2>) -> T2,
1236 ) -> Handle<T2> {
1237 self.window_cx.entity(build_entity)
1238 }
1239
1240 fn update_entity<U: Send + Sync + 'static, R>(
1241 &mut self,
1242 handle: &Handle<U>,
1243 update: impl FnOnce(&mut U, &mut Self::EntityContext<'_, '_, U>) -> R,
1244 ) -> R {
1245 self.window_cx.update_entity(handle, update)
1246 }
1247}
1248
1249impl<'a, 'w, S: 'static> std::ops::Deref for ViewContext<'a, 'w, S> {
1250 type Target = WindowContext<'a, 'w>;
1251
1252 fn deref(&self) -> &Self::Target {
1253 &self.window_cx
1254 }
1255}
1256
1257impl<'a, 'w, S: 'static> std::ops::DerefMut for ViewContext<'a, 'w, S> {
1258 fn deref_mut(&mut self) -> &mut Self::Target {
1259 &mut self.window_cx
1260 }
1261}
1262
1263// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
1264slotmap::new_key_type! { pub struct WindowId; }
1265
1266#[derive(PartialEq, Eq)]
1267pub struct WindowHandle<S> {
1268 id: WindowId,
1269 state_type: PhantomData<S>,
1270}
1271
1272impl<S> Copy for WindowHandle<S> {}
1273
1274impl<S> Clone for WindowHandle<S> {
1275 fn clone(&self) -> Self {
1276 WindowHandle {
1277 id: self.id,
1278 state_type: PhantomData,
1279 }
1280 }
1281}
1282
1283impl<S> WindowHandle<S> {
1284 pub fn new(id: WindowId) -> Self {
1285 WindowHandle {
1286 id,
1287 state_type: PhantomData,
1288 }
1289 }
1290}
1291
1292impl<S: 'static> Into<AnyWindowHandle> for WindowHandle<S> {
1293 fn into(self) -> AnyWindowHandle {
1294 AnyWindowHandle {
1295 id: self.id,
1296 state_type: TypeId::of::<S>(),
1297 }
1298 }
1299}
1300
1301#[derive(Copy, Clone, PartialEq, Eq)]
1302pub struct AnyWindowHandle {
1303 pub(crate) id: WindowId,
1304 state_type: TypeId,
1305}
1306
1307#[cfg(any(test, feature = "test"))]
1308impl From<SmallVec<[u32; 16]>> for StackingOrder {
1309 fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
1310 StackingOrder(small_vec)
1311 }
1312}
1313
1314#[derive(Clone, Debug, Eq, PartialEq, Hash)]
1315pub enum ElementId {
1316 View(EntityId),
1317 Number(usize),
1318 Name(SharedString),
1319}
1320
1321impl From<EntityId> for ElementId {
1322 fn from(id: EntityId) -> Self {
1323 ElementId::View(id)
1324 }
1325}
1326
1327impl From<usize> for ElementId {
1328 fn from(id: usize) -> Self {
1329 ElementId::Number(id)
1330 }
1331}
1332
1333impl From<i32> for ElementId {
1334 fn from(id: i32) -> Self {
1335 Self::Number(id as usize)
1336 }
1337}
1338
1339impl From<SharedString> for ElementId {
1340 fn from(name: SharedString) -> Self {
1341 ElementId::Name(name)
1342 }
1343}
1344
1345impl From<&'static str> for ElementId {
1346 fn from(name: &'static str) -> Self {
1347 ElementId::Name(name.into())
1348 }
1349}