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