1use crate::{
2 elements::AnyRootElement,
3 geometry::rect::RectF,
4 json::ToJson,
5 keymap_matcher::{Binding, KeymapContext, Keystroke, MatchResult},
6 platform::{
7 self, Appearance, CursorStyle, Event, KeyDownEvent, KeyUpEvent, ModifiersChangedEvent,
8 MouseButton, MouseMovedEvent, PromptLevel, WindowBounds,
9 },
10 scene::{
11 CursorRegion, MouseClick, MouseClickOut, MouseDown, MouseDownOut, MouseDrag, MouseEvent,
12 MouseHover, MouseMove, MouseMoveOut, MouseScrollWheel, MouseUp, MouseUpOut, Scene,
13 },
14 text_layout::TextLayoutCache,
15 util::post_inc,
16 Action, AnyView, AnyViewHandle, AnyWindowHandle, AppContext, BorrowAppContext,
17 BorrowWindowContext, Effect, Element, Entity, Handle, LayoutContext, MouseRegion,
18 MouseRegionId, PaintContext, SceneBuilder, Subscription, View, ViewContext, ViewHandle,
19 WindowInvalidation,
20};
21use anyhow::{anyhow, bail, Result};
22use collections::{HashMap, HashSet};
23use pathfinder_geometry::vector::{vec2f, Vector2F};
24use postage::oneshot;
25use serde_json::json;
26use smallvec::SmallVec;
27use sqlez::{
28 bindable::{Bind, Column, StaticColumnCount},
29 statement::Statement,
30};
31use std::{
32 any::TypeId,
33 mem,
34 ops::{Deref, DerefMut, Range, Sub},
35};
36use taffy::Taffy;
37use util::ResultExt;
38use uuid::Uuid;
39
40use super::{Reference, ViewMetadata};
41
42pub struct Window {
43 layout_engine: Taffy,
44 pub(crate) root_view: Option<AnyViewHandle>,
45 pub(crate) focused_view_id: Option<usize>,
46 pub(crate) parents: HashMap<usize, usize>,
47 pub(crate) is_active: bool,
48 pub(crate) is_fullscreen: bool,
49 pub(crate) invalidation: Option<WindowInvalidation>,
50 pub(crate) platform_window: Box<dyn platform::Window>,
51 pub(crate) rendered_views: HashMap<usize, Box<dyn AnyRootElement>>,
52 titlebar_height: f32,
53 appearance: Appearance,
54 cursor_regions: Vec<CursorRegion>,
55 mouse_regions: Vec<(MouseRegion, usize)>,
56 last_mouse_moved_event: Option<Event>,
57 pub(crate) hovered_region_ids: HashSet<MouseRegionId>,
58 pub(crate) clicked_region_ids: HashSet<MouseRegionId>,
59 pub(crate) clicked_region: Option<(MouseRegionId, MouseButton)>,
60 mouse_position: Vector2F,
61 text_layout_cache: TextLayoutCache,
62}
63
64impl Window {
65 pub fn new<V, F>(
66 handle: AnyWindowHandle,
67 platform_window: Box<dyn platform::Window>,
68 cx: &mut AppContext,
69 build_view: F,
70 ) -> Self
71 where
72 V: View,
73 F: FnOnce(&mut ViewContext<V>) -> V,
74 {
75 let titlebar_height = platform_window.titlebar_height();
76 let appearance = platform_window.appearance();
77 let mut window = Self {
78 layout_engine: Taffy::new(),
79 root_view: None,
80 focused_view_id: None,
81 parents: Default::default(),
82 is_active: false,
83 invalidation: None,
84 is_fullscreen: false,
85 platform_window,
86 rendered_views: Default::default(),
87 cursor_regions: Default::default(),
88 mouse_regions: Default::default(),
89 text_layout_cache: TextLayoutCache::new(cx.font_system.clone()),
90 last_mouse_moved_event: None,
91 hovered_region_ids: Default::default(),
92 clicked_region_ids: Default::default(),
93 clicked_region: None,
94 mouse_position: vec2f(0., 0.),
95 titlebar_height,
96 appearance,
97 };
98
99 let mut window_context = WindowContext::mutable(cx, &mut window, handle);
100 let root_view = window_context.add_view(|cx| build_view(cx));
101 if let Some(invalidation) = window_context.window.invalidation.take() {
102 window_context.invalidate(invalidation, appearance);
103 }
104 window.focused_view_id = Some(root_view.id());
105 window.root_view = Some(root_view.into_any());
106 window
107 }
108
109 pub fn root_view(&self) -> &AnyViewHandle {
110 &self
111 .root_view
112 .as_ref()
113 .expect("root_view called during window construction")
114 }
115}
116
117pub struct WindowContext<'a> {
118 pub(crate) app_context: Reference<'a, AppContext>,
119 pub(crate) window: Reference<'a, Window>,
120 pub(crate) window_handle: AnyWindowHandle,
121 pub(crate) removed: bool,
122}
123
124impl Deref for WindowContext<'_> {
125 type Target = AppContext;
126
127 fn deref(&self) -> &Self::Target {
128 &self.app_context
129 }
130}
131
132impl DerefMut for WindowContext<'_> {
133 fn deref_mut(&mut self) -> &mut Self::Target {
134 &mut self.app_context
135 }
136}
137
138impl BorrowAppContext for WindowContext<'_> {
139 fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
140 self.app_context.read_with(f)
141 }
142
143 fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
144 self.app_context.update(f)
145 }
146}
147
148impl BorrowWindowContext for WindowContext<'_> {
149 type Result<T> = T;
150
151 fn read_window<T, F: FnOnce(&WindowContext) -> T>(&self, handle: AnyWindowHandle, f: F) -> T {
152 if self.window_handle == handle {
153 f(self)
154 } else {
155 panic!("read_with called with id of window that does not belong to this context")
156 }
157 }
158
159 fn read_window_optional<T, F>(&self, window: AnyWindowHandle, f: F) -> Option<T>
160 where
161 F: FnOnce(&WindowContext) -> Option<T>,
162 {
163 BorrowWindowContext::read_window(self, window, f)
164 }
165
166 fn update_window<T, F: FnOnce(&mut WindowContext) -> T>(
167 &mut self,
168 handle: AnyWindowHandle,
169 f: F,
170 ) -> T {
171 if self.window_handle == handle {
172 f(self)
173 } else {
174 panic!("update called with id of window that does not belong to this context")
175 }
176 }
177
178 fn update_window_optional<T, F>(&mut self, handle: AnyWindowHandle, f: F) -> Option<T>
179 where
180 F: FnOnce(&mut WindowContext) -> Option<T>,
181 {
182 BorrowWindowContext::update_window(self, handle, f)
183 }
184}
185
186impl<'a> WindowContext<'a> {
187 pub fn mutable(
188 app_context: &'a mut AppContext,
189 window: &'a mut Window,
190 handle: AnyWindowHandle,
191 ) -> Self {
192 Self {
193 app_context: Reference::Mutable(app_context),
194 window: Reference::Mutable(window),
195 window_handle: handle,
196 removed: false,
197 }
198 }
199
200 pub fn immutable(
201 app_context: &'a AppContext,
202 window: &'a Window,
203 handle: AnyWindowHandle,
204 ) -> Self {
205 Self {
206 app_context: Reference::Immutable(app_context),
207 window: Reference::Immutable(window),
208 window_handle: handle,
209 removed: false,
210 }
211 }
212
213 pub fn layout_engine(&mut self) -> &mut Taffy {
214 &mut self.window.layout_engine
215 }
216
217 pub fn remove_window(&mut self) {
218 self.removed = true;
219 }
220
221 pub fn window(&self) -> AnyWindowHandle {
222 self.window_handle
223 }
224
225 pub fn app_context(&mut self) -> &mut AppContext {
226 &mut self.app_context
227 }
228
229 pub fn root_view(&self) -> &AnyViewHandle {
230 self.window.root_view()
231 }
232
233 pub fn window_size(&self) -> Vector2F {
234 self.window.platform_window.content_size()
235 }
236
237 pub fn text_layout_cache(&self) -> &TextLayoutCache {
238 &self.window.text_layout_cache
239 }
240
241 pub(crate) fn update_any_view<F, T>(&mut self, view_id: usize, f: F) -> Option<T>
242 where
243 F: FnOnce(&mut dyn AnyView, &mut Self) -> T,
244 {
245 let handle = self.window_handle;
246 let mut view = self.views.remove(&(handle, view_id))?;
247 let result = f(view.as_mut(), self);
248 self.views.insert((handle, view_id), view);
249 Some(result)
250 }
251
252 pub(crate) fn update_view<V: 'static, S>(
253 &mut self,
254 handle: &ViewHandle<V>,
255 update: &mut dyn FnMut(&mut V, &mut ViewContext<V>) -> S,
256 ) -> S {
257 self.update_any_view(handle.view_id, |view, cx| {
258 let mut cx = ViewContext::mutable(cx, handle.view_id);
259 update(
260 view.as_any_mut()
261 .downcast_mut()
262 .expect("downcast is type safe"),
263 &mut cx,
264 )
265 })
266 .expect("view is already on the stack")
267 }
268
269 pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut WindowContext)) {
270 let handle = self.window_handle;
271 self.app_context.defer(move |cx| {
272 cx.update_window(handle, |cx| callback(cx));
273 })
274 }
275
276 pub fn update_global<T, F, U>(&mut self, update: F) -> U
277 where
278 T: 'static,
279 F: FnOnce(&mut T, &mut Self) -> U,
280 {
281 AppContext::update_global_internal(self, |global, cx| update(global, cx))
282 }
283
284 pub fn update_default_global<T, F, U>(&mut self, update: F) -> U
285 where
286 T: 'static + Default,
287 F: FnOnce(&mut T, &mut Self) -> U,
288 {
289 AppContext::update_default_global_internal(self, |global, cx| update(global, cx))
290 }
291
292 pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
293 where
294 E: Entity,
295 E::Event: 'static,
296 H: Handle<E>,
297 F: 'static + FnMut(H, &E::Event, &mut WindowContext),
298 {
299 self.subscribe_internal(handle, move |emitter, event, cx| {
300 callback(emitter, event, cx);
301 true
302 })
303 }
304
305 pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
306 where
307 E: Entity,
308 E::Event: 'static,
309 H: Handle<E>,
310 F: 'static + FnMut(H, &E::Event, &mut WindowContext) -> bool,
311 {
312 let window_handle = self.window_handle;
313 self.app_context
314 .subscribe_internal(handle, move |emitter, event, cx| {
315 cx.update_window(window_handle, |cx| callback(emitter, event, cx))
316 .unwrap_or(false)
317 })
318 }
319
320 pub(crate) fn observe_window_activation<F>(&mut self, callback: F) -> Subscription
321 where
322 F: 'static + FnMut(bool, &mut WindowContext) -> bool,
323 {
324 let handle = self.window_handle;
325 let subscription_id = post_inc(&mut self.next_subscription_id);
326 self.pending_effects
327 .push_back(Effect::WindowActivationObservation {
328 window: handle,
329 subscription_id,
330 callback: Box::new(callback),
331 });
332 Subscription::WindowActivationObservation(
333 self.window_activation_observations
334 .subscribe(handle, subscription_id),
335 )
336 }
337
338 pub(crate) fn observe_fullscreen<F>(&mut self, callback: F) -> Subscription
339 where
340 F: 'static + FnMut(bool, &mut WindowContext) -> bool,
341 {
342 let window = self.window_handle;
343 let subscription_id = post_inc(&mut self.next_subscription_id);
344 self.pending_effects
345 .push_back(Effect::WindowFullscreenObservation {
346 window,
347 subscription_id,
348 callback: Box::new(callback),
349 });
350 Subscription::WindowActivationObservation(
351 self.window_activation_observations
352 .subscribe(window, subscription_id),
353 )
354 }
355
356 pub(crate) fn observe_window_bounds<F>(&mut self, callback: F) -> Subscription
357 where
358 F: 'static + FnMut(WindowBounds, Uuid, &mut WindowContext) -> bool,
359 {
360 let window = self.window_handle;
361 let subscription_id = post_inc(&mut self.next_subscription_id);
362 self.pending_effects
363 .push_back(Effect::WindowBoundsObservation {
364 window,
365 subscription_id,
366 callback: Box::new(callback),
367 });
368 Subscription::WindowBoundsObservation(
369 self.window_bounds_observations
370 .subscribe(window, subscription_id),
371 )
372 }
373
374 pub fn observe_keystrokes<F>(&mut self, callback: F) -> Subscription
375 where
376 F: 'static
377 + FnMut(&Keystroke, &MatchResult, Option<&Box<dyn Action>>, &mut WindowContext) -> bool,
378 {
379 let window = self.window_handle;
380 let subscription_id = post_inc(&mut self.next_subscription_id);
381 self.keystroke_observations
382 .add_callback(window, subscription_id, Box::new(callback));
383 Subscription::KeystrokeObservation(
384 self.keystroke_observations
385 .subscribe(window, subscription_id),
386 )
387 }
388
389 pub(crate) fn available_actions(
390 &self,
391 view_id: usize,
392 ) -> Vec<(&'static str, Box<dyn Action>, SmallVec<[Binding; 1]>)> {
393 let handle = self.window_handle;
394 let mut contexts = Vec::new();
395 let mut handler_depths_by_action_id = HashMap::<TypeId, usize>::default();
396 for (depth, view_id) in self.ancestors(view_id).enumerate() {
397 if let Some(view_metadata) = self.views_metadata.get(&(handle, view_id)) {
398 contexts.push(view_metadata.keymap_context.clone());
399 if let Some(actions) = self.actions.get(&view_metadata.type_id) {
400 handler_depths_by_action_id
401 .extend(actions.keys().copied().map(|action_id| (action_id, depth)));
402 }
403 } else {
404 log::error!(
405 "view {} not found when computing available actions",
406 view_id
407 );
408 }
409 }
410
411 handler_depths_by_action_id.extend(
412 self.global_actions
413 .keys()
414 .copied()
415 .map(|action_id| (action_id, contexts.len())),
416 );
417
418 self.action_deserializers
419 .iter()
420 .filter_map(move |(name, (action_id, deserialize))| {
421 if let Some(action_depth) = handler_depths_by_action_id.get(action_id).copied() {
422 let action = deserialize(serde_json::Value::Object(Default::default())).ok()?;
423 let bindings = self
424 .keystroke_matcher
425 .bindings_for_action(*action_id)
426 .filter(|b| {
427 action.eq(b.action())
428 && (0..=action_depth)
429 .any(|depth| b.match_context(&contexts[depth..]))
430 })
431 .cloned()
432 .collect();
433 Some((*name, action, bindings))
434 } else {
435 None
436 }
437 })
438 .collect()
439 }
440
441 pub(crate) fn dispatch_keystroke(&mut self, keystroke: &Keystroke) -> bool {
442 let handle = self.window_handle;
443 if let Some(focused_view_id) = self.focused_view_id() {
444 let dispatch_path = self
445 .ancestors(focused_view_id)
446 .filter_map(|view_id| {
447 self.views_metadata
448 .get(&(handle, view_id))
449 .map(|view| (view_id, view.keymap_context.clone()))
450 })
451 .collect();
452
453 let match_result = self
454 .keystroke_matcher
455 .push_keystroke(keystroke.clone(), dispatch_path);
456 let mut handled_by = None;
457
458 let keystroke_handled = match &match_result {
459 MatchResult::None => false,
460 MatchResult::Pending => true,
461 MatchResult::Matches(matches) => {
462 for (view_id, action) in matches {
463 if self.dispatch_action(Some(*view_id), action.as_ref()) {
464 self.keystroke_matcher.clear_pending();
465 handled_by = Some(action.boxed_clone());
466 break;
467 }
468 }
469 handled_by.is_some()
470 }
471 };
472
473 self.keystroke(handle, keystroke.clone(), handled_by, match_result.clone());
474 keystroke_handled
475 } else {
476 self.keystroke(handle, keystroke.clone(), None, MatchResult::None);
477 false
478 }
479 }
480
481 pub(crate) fn dispatch_event(&mut self, event: Event, event_reused: bool) -> bool {
482 let mut mouse_events = SmallVec::<[_; 2]>::new();
483 let mut notified_views: HashSet<usize> = Default::default();
484 let handle = self.window_handle;
485
486 // 1. Handle platform event. Keyboard events get dispatched immediately, while mouse events
487 // get mapped into the mouse-specific MouseEvent type.
488 // -> These are usually small: [Mouse Down] or [Mouse up, Click] or [Mouse Moved, Mouse Dragged?]
489 // -> Also updates mouse-related state
490 match &event {
491 Event::KeyDown(e) => return self.dispatch_key_down(e),
492
493 Event::KeyUp(e) => return self.dispatch_key_up(e),
494
495 Event::ModifiersChanged(e) => return self.dispatch_modifiers_changed(e),
496
497 Event::MouseDown(e) => {
498 // Click events are weird because they can be fired after a drag event.
499 // MDN says that browsers handle this by starting from 'the most
500 // specific ancestor element that contained both [positions]'
501 // So we need to store the overlapping regions on mouse down.
502
503 // If there is already region being clicked, don't replace it.
504 if self.window.clicked_region.is_none() {
505 self.window.clicked_region_ids = self
506 .window
507 .mouse_regions
508 .iter()
509 .filter_map(|(region, _)| {
510 if region.bounds.contains_point(e.position) {
511 Some(region.id())
512 } else {
513 None
514 }
515 })
516 .collect();
517
518 let mut highest_z_index = 0;
519 let mut clicked_region_id = None;
520 for (region, z_index) in self.window.mouse_regions.iter() {
521 if region.bounds.contains_point(e.position) && *z_index >= highest_z_index {
522 highest_z_index = *z_index;
523 clicked_region_id = Some(region.id());
524 }
525 }
526
527 self.window.clicked_region =
528 clicked_region_id.map(|region_id| (region_id, e.button));
529 }
530
531 mouse_events.push(MouseEvent::Down(MouseDown {
532 region: Default::default(),
533 platform_event: e.clone(),
534 }));
535 mouse_events.push(MouseEvent::DownOut(MouseDownOut {
536 region: Default::default(),
537 platform_event: e.clone(),
538 }));
539 }
540
541 Event::MouseUp(e) => {
542 // NOTE: The order of event pushes is important! MouseUp events MUST be fired
543 // before click events, and so the MouseUp events need to be pushed before
544 // MouseClick events.
545
546 // Synthesize one last drag event to end the drag
547 mouse_events.push(MouseEvent::Drag(MouseDrag {
548 region: Default::default(),
549 prev_mouse_position: self.window.mouse_position,
550 platform_event: MouseMovedEvent {
551 position: e.position,
552 pressed_button: Some(e.button),
553 modifiers: e.modifiers,
554 },
555 end: true,
556 }));
557 mouse_events.push(MouseEvent::Up(MouseUp {
558 region: Default::default(),
559 platform_event: e.clone(),
560 }));
561 mouse_events.push(MouseEvent::UpOut(MouseUpOut {
562 region: Default::default(),
563 platform_event: e.clone(),
564 }));
565 mouse_events.push(MouseEvent::Click(MouseClick {
566 region: Default::default(),
567 platform_event: e.clone(),
568 }));
569 mouse_events.push(MouseEvent::ClickOut(MouseClickOut {
570 region: Default::default(),
571 platform_event: e.clone(),
572 }));
573 }
574
575 Event::MouseMoved(
576 e @ MouseMovedEvent {
577 position,
578 pressed_button,
579 ..
580 },
581 ) => {
582 let mut style_to_assign = CursorStyle::Arrow;
583 for region in self.window.cursor_regions.iter().rev() {
584 if region.bounds.contains_point(*position) {
585 style_to_assign = region.style;
586 break;
587 }
588 }
589
590 if self
591 .window
592 .platform_window
593 .is_topmost_for_position(*position)
594 {
595 self.platform().set_cursor_style(style_to_assign);
596 }
597
598 if !event_reused {
599 if pressed_button.is_some() {
600 mouse_events.push(MouseEvent::Drag(MouseDrag {
601 region: Default::default(),
602 prev_mouse_position: self.window.mouse_position,
603 platform_event: e.clone(),
604 end: false,
605 }));
606 } else if let Some((_, clicked_button)) = self.window.clicked_region {
607 mouse_events.push(MouseEvent::Drag(MouseDrag {
608 region: Default::default(),
609 prev_mouse_position: self.window.mouse_position,
610 platform_event: e.clone(),
611 end: true,
612 }));
613
614 // Mouse up event happened outside the current window. Simulate mouse up button event
615 let button_event = e.to_button_event(clicked_button);
616 mouse_events.push(MouseEvent::Up(MouseUp {
617 region: Default::default(),
618 platform_event: button_event.clone(),
619 }));
620 mouse_events.push(MouseEvent::UpOut(MouseUpOut {
621 region: Default::default(),
622 platform_event: button_event.clone(),
623 }));
624 mouse_events.push(MouseEvent::Click(MouseClick {
625 region: Default::default(),
626 platform_event: button_event.clone(),
627 }));
628 }
629
630 mouse_events.push(MouseEvent::Move(MouseMove {
631 region: Default::default(),
632 platform_event: e.clone(),
633 }));
634 }
635
636 mouse_events.push(MouseEvent::Hover(MouseHover {
637 region: Default::default(),
638 platform_event: e.clone(),
639 started: false,
640 }));
641 mouse_events.push(MouseEvent::MoveOut(MouseMoveOut {
642 region: Default::default(),
643 }));
644
645 self.window.last_mouse_moved_event = Some(event.clone());
646 }
647
648 Event::MouseExited(event) => {
649 // When the platform sends a MouseExited event, synthesize
650 // a MouseMoved event whose position is outside the window's
651 // bounds so that hover and cursor state can be updated.
652 return self.dispatch_event(
653 Event::MouseMoved(MouseMovedEvent {
654 position: event.position,
655 pressed_button: event.pressed_button,
656 modifiers: event.modifiers,
657 }),
658 event_reused,
659 );
660 }
661
662 Event::ScrollWheel(e) => mouse_events.push(MouseEvent::ScrollWheel(MouseScrollWheel {
663 region: Default::default(),
664 platform_event: e.clone(),
665 })),
666 }
667
668 if let Some(position) = event.position() {
669 self.window.mouse_position = position;
670 }
671
672 // 2. Dispatch mouse events on regions
673 let mut any_event_handled = false;
674 for mut mouse_event in mouse_events {
675 let mut valid_regions = Vec::new();
676
677 // GPUI elements are arranged by z_index but sibling elements can register overlapping
678 // mouse regions. As such, hover events are only fired on overlapping elements which
679 // are at the same z-index as the topmost element which overlaps with the mouse.
680 match &mouse_event {
681 MouseEvent::Hover(_) => {
682 let mut highest_z_index = None;
683 let mouse_position = self.window.mouse_position.clone();
684 let window = &mut *self.window;
685 for (region, z_index) in window.mouse_regions.iter().rev() {
686 // Allow mouse regions to appear transparent to hovers
687 if !region.hoverable {
688 continue;
689 }
690
691 let contains_mouse = region.bounds.contains_point(mouse_position);
692
693 if contains_mouse && highest_z_index.is_none() {
694 highest_z_index = Some(z_index);
695 }
696
697 // This unwrap relies on short circuiting boolean expressions
698 // The right side of the && is only executed when contains_mouse
699 // is true, and we know above that when contains_mouse is true
700 // highest_z_index is set.
701 if contains_mouse && z_index == highest_z_index.unwrap() {
702 //Ensure that hover entrance events aren't sent twice
703 if window.hovered_region_ids.insert(region.id()) {
704 valid_regions.push(region.clone());
705 if region.notify_on_hover {
706 notified_views.insert(region.id().view_id());
707 }
708 }
709 } else {
710 // Ensure that hover exit events aren't sent twice
711 if window.hovered_region_ids.remove(®ion.id()) {
712 valid_regions.push(region.clone());
713 if region.notify_on_hover {
714 notified_views.insert(region.id().view_id());
715 }
716 }
717 }
718 }
719 }
720
721 MouseEvent::Down(_) | MouseEvent::Up(_) => {
722 for (region, _) in self.window.mouse_regions.iter().rev() {
723 if region.bounds.contains_point(self.window.mouse_position) {
724 valid_regions.push(region.clone());
725 if region.notify_on_click {
726 notified_views.insert(region.id().view_id());
727 }
728 }
729 }
730 }
731
732 MouseEvent::Click(e) => {
733 // Only raise click events if the released button is the same as the one stored
734 if self
735 .window
736 .clicked_region
737 .map(|(_, clicked_button)| clicked_button == e.button)
738 .unwrap_or(false)
739 {
740 // Clear clicked regions and clicked button
741 let clicked_region_ids = std::mem::replace(
742 &mut self.window.clicked_region_ids,
743 Default::default(),
744 );
745 self.window.clicked_region = None;
746
747 // Find regions which still overlap with the mouse since the last MouseDown happened
748 for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
749 if clicked_region_ids.contains(&mouse_region.id()) {
750 if mouse_region
751 .bounds
752 .contains_point(self.window.mouse_position)
753 {
754 valid_regions.push(mouse_region.clone());
755 }
756 }
757 }
758 }
759 }
760
761 MouseEvent::Drag(_) => {
762 for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
763 if self.window.clicked_region_ids.contains(&mouse_region.id()) {
764 valid_regions.push(mouse_region.clone());
765 }
766 }
767 }
768
769 MouseEvent::MoveOut(_)
770 | MouseEvent::UpOut(_)
771 | MouseEvent::DownOut(_)
772 | MouseEvent::ClickOut(_) => {
773 for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
774 // NOT contains
775 if !mouse_region
776 .bounds
777 .contains_point(self.window.mouse_position)
778 {
779 valid_regions.push(mouse_region.clone());
780 }
781 }
782 }
783
784 _ => {
785 for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
786 // Contains
787 if mouse_region
788 .bounds
789 .contains_point(self.window.mouse_position)
790 {
791 valid_regions.push(mouse_region.clone());
792 }
793 }
794 }
795 }
796
797 //3. Fire region events
798 let hovered_region_ids = self.window.hovered_region_ids.clone();
799 for valid_region in valid_regions.into_iter() {
800 let mut handled = false;
801 mouse_event.set_region(valid_region.bounds);
802 if let MouseEvent::Hover(e) = &mut mouse_event {
803 e.started = hovered_region_ids.contains(&valid_region.id())
804 }
805 // Handle Down events if the MouseRegion has a Click or Drag handler. This makes the api more intuitive as you would
806 // not expect a MouseRegion to be transparent to Down events if it also has a Click handler.
807 // This behavior can be overridden by adding a Down handler
808 if let MouseEvent::Down(e) = &mouse_event {
809 let has_click = valid_region
810 .handlers
811 .contains(MouseEvent::click_disc(), Some(e.button));
812 let has_drag = valid_region
813 .handlers
814 .contains(MouseEvent::drag_disc(), Some(e.button));
815 let has_down = valid_region
816 .handlers
817 .contains(MouseEvent::down_disc(), Some(e.button));
818 if !has_down && (has_click || has_drag) {
819 handled = true;
820 }
821 }
822
823 // `event_consumed` should only be true if there are any handlers for this event.
824 let mut event_consumed = handled;
825 if let Some(callbacks) = valid_region.handlers.get(&mouse_event.handler_key()) {
826 for callback in callbacks {
827 handled = true;
828 let view_id = valid_region.id().view_id();
829 self.update_any_view(view_id, |view, cx| {
830 handled = callback(mouse_event.clone(), view.as_any_mut(), cx, view_id);
831 });
832 event_consumed |= handled;
833 any_event_handled |= handled;
834 }
835 }
836
837 any_event_handled |= handled;
838
839 // For bubbling events, if the event was handled, don't continue dispatching.
840 // This only makes sense for local events which return false from is_capturable.
841 if event_consumed && mouse_event.is_capturable() {
842 break;
843 }
844 }
845 }
846
847 for view_id in notified_views {
848 self.notify_view(handle, view_id);
849 }
850
851 any_event_handled
852 }
853
854 pub(crate) fn dispatch_key_down(&mut self, event: &KeyDownEvent) -> bool {
855 let handle = self.window_handle;
856 if let Some(focused_view_id) = self.window.focused_view_id {
857 for view_id in self.ancestors(focused_view_id).collect::<Vec<_>>() {
858 if let Some(mut view) = self.views.remove(&(handle, view_id)) {
859 let handled = view.key_down(event, self, view_id);
860 self.views.insert((handle, view_id), view);
861 if handled {
862 return true;
863 }
864 } else {
865 log::error!("view {} does not exist", view_id)
866 }
867 }
868 }
869
870 false
871 }
872
873 pub(crate) fn dispatch_key_up(&mut self, event: &KeyUpEvent) -> bool {
874 let handle = self.window_handle;
875 if let Some(focused_view_id) = self.window.focused_view_id {
876 for view_id in self.ancestors(focused_view_id).collect::<Vec<_>>() {
877 if let Some(mut view) = self.views.remove(&(handle, view_id)) {
878 let handled = view.key_up(event, self, view_id);
879 self.views.insert((handle, view_id), view);
880 if handled {
881 return true;
882 }
883 } else {
884 log::error!("view {} does not exist", view_id)
885 }
886 }
887 }
888
889 false
890 }
891
892 pub(crate) fn dispatch_modifiers_changed(&mut self, event: &ModifiersChangedEvent) -> bool {
893 let handle = self.window_handle;
894 if let Some(focused_view_id) = self.window.focused_view_id {
895 for view_id in self.ancestors(focused_view_id).collect::<Vec<_>>() {
896 if let Some(mut view) = self.views.remove(&(handle, view_id)) {
897 let handled = view.modifiers_changed(event, self, view_id);
898 self.views.insert((handle, view_id), view);
899 if handled {
900 return true;
901 }
902 } else {
903 log::error!("view {} does not exist", view_id)
904 }
905 }
906 }
907
908 false
909 }
910
911 pub fn invalidate(&mut self, mut invalidation: WindowInvalidation, appearance: Appearance) {
912 self.start_frame();
913 self.window.appearance = appearance;
914 for view_id in &invalidation.removed {
915 invalidation.updated.remove(view_id);
916 self.window.rendered_views.remove(view_id);
917 }
918 for view_id in &invalidation.updated {
919 let titlebar_height = self.window.titlebar_height;
920 let element = self
921 .render_view(RenderParams {
922 view_id: *view_id,
923 titlebar_height,
924 refreshing: false,
925 appearance,
926 })
927 .unwrap();
928 self.window.rendered_views.insert(*view_id, element);
929 }
930 }
931
932 pub fn render_view(&mut self, params: RenderParams) -> Result<Box<dyn AnyRootElement>> {
933 let handle = self.window_handle;
934 let view_id = params.view_id;
935 let mut view = self
936 .views
937 .remove(&(handle, view_id))
938 .ok_or_else(|| anyhow!("view not found"))?;
939 let element = view.render(self, view_id);
940 self.views.insert((handle, view_id), view);
941 Ok(element)
942 }
943
944 pub fn layout(&mut self, refreshing: bool) -> Result<HashMap<usize, usize>> {
945 let window_size = self.window.platform_window.content_size();
946 let root_view_id = self.window.root_view().id();
947
948 let mut rendered_root = self.window.rendered_views.remove(&root_view_id).unwrap();
949
950 let mut new_parents = HashMap::default();
951 let mut views_to_notify_if_ancestors_change = HashMap::default();
952 rendered_root.layout(
953 SizeConstraint::new(window_size, window_size),
954 &mut new_parents,
955 &mut views_to_notify_if_ancestors_change,
956 refreshing,
957 self,
958 )?;
959
960 for (view_id, view_ids_to_notify) in views_to_notify_if_ancestors_change {
961 let mut current_view_id = view_id;
962 loop {
963 let old_parent_id = self.window.parents.get(¤t_view_id);
964 let new_parent_id = new_parents.get(¤t_view_id);
965 if old_parent_id.is_none() && new_parent_id.is_none() {
966 break;
967 } else if old_parent_id == new_parent_id {
968 current_view_id = *old_parent_id.unwrap();
969 } else {
970 let handle = self.window_handle;
971 for view_id_to_notify in view_ids_to_notify {
972 self.notify_view(handle, view_id_to_notify);
973 }
974 break;
975 }
976 }
977 }
978
979 let old_parents = mem::replace(&mut self.window.parents, new_parents);
980 self.window
981 .rendered_views
982 .insert(root_view_id, rendered_root);
983 Ok(old_parents)
984 }
985
986 pub fn paint(&mut self) -> Result<Scene> {
987 let window_size = self.window.platform_window.content_size();
988 let scale_factor = self.window.platform_window.scale_factor();
989
990 let root_view_id = self.window.root_view().id();
991 let mut rendered_root = self.window.rendered_views.remove(&root_view_id).unwrap();
992
993 let mut scene_builder = SceneBuilder::new(scale_factor);
994 rendered_root.paint(
995 &mut scene_builder,
996 Vector2F::zero(),
997 RectF::from_points(Vector2F::zero(), window_size),
998 self,
999 )?;
1000 self.window
1001 .rendered_views
1002 .insert(root_view_id, rendered_root);
1003
1004 self.window.text_layout_cache.finish_frame();
1005 let scene = scene_builder.build();
1006 self.window.cursor_regions = scene.cursor_regions();
1007 self.window.mouse_regions = scene.mouse_regions();
1008
1009 if self.window_is_active() {
1010 if let Some(event) = self.window.last_mouse_moved_event.clone() {
1011 self.dispatch_event(event, true);
1012 }
1013 }
1014
1015 Ok(scene)
1016 }
1017
1018 pub fn root_element(&self) -> &Box<dyn AnyRootElement> {
1019 let view_id = self.window.root_view().id();
1020 self.window.rendered_views.get(&view_id).unwrap()
1021 }
1022
1023 pub fn rect_for_text_range(&self, range_utf16: Range<usize>) -> Option<RectF> {
1024 let focused_view_id = self.window.focused_view_id?;
1025 self.window
1026 .rendered_views
1027 .get(&focused_view_id)?
1028 .rect_for_text_range(range_utf16, self)
1029 .log_err()
1030 .flatten()
1031 }
1032
1033 pub fn set_window_title(&mut self, title: &str) {
1034 self.window.platform_window.set_title(title);
1035 }
1036
1037 pub fn set_window_edited(&mut self, edited: bool) {
1038 self.window.platform_window.set_edited(edited);
1039 }
1040
1041 pub fn is_topmost_window_for_position(&self, position: Vector2F) -> bool {
1042 self.window
1043 .platform_window
1044 .is_topmost_for_position(position)
1045 }
1046
1047 pub fn activate_window(&self) {
1048 self.window.platform_window.activate();
1049 }
1050
1051 pub fn window_is_active(&self) -> bool {
1052 self.window.is_active
1053 }
1054
1055 pub fn window_is_fullscreen(&self) -> bool {
1056 self.window.is_fullscreen
1057 }
1058
1059 pub(crate) fn dispatch_action(&mut self, view_id: Option<usize>, action: &dyn Action) -> bool {
1060 if let Some(view_id) = view_id {
1061 self.halt_action_dispatch = false;
1062 self.visit_dispatch_path(view_id, |view_id, capture_phase, cx| {
1063 cx.update_any_view(view_id, |view, cx| {
1064 let type_id = view.as_any().type_id();
1065 if let Some((name, mut handlers)) = cx
1066 .actions_mut(capture_phase)
1067 .get_mut(&type_id)
1068 .and_then(|h| h.remove_entry(&action.id()))
1069 {
1070 for handler in handlers.iter_mut().rev() {
1071 cx.halt_action_dispatch = true;
1072 handler(view, action, cx, view_id);
1073 if cx.halt_action_dispatch {
1074 break;
1075 }
1076 }
1077 cx.actions_mut(capture_phase)
1078 .get_mut(&type_id)
1079 .unwrap()
1080 .insert(name, handlers);
1081 }
1082 });
1083
1084 !cx.halt_action_dispatch
1085 });
1086 }
1087
1088 if !self.halt_action_dispatch {
1089 self.halt_action_dispatch = self.dispatch_global_action_any(action);
1090 }
1091
1092 self.pending_effects
1093 .push_back(Effect::ActionDispatchNotification {
1094 action_id: action.id(),
1095 });
1096 self.halt_action_dispatch
1097 }
1098
1099 /// Returns an iterator over all of the view ids from the passed view up to the root of the window
1100 /// Includes the passed view itself
1101 pub(crate) fn ancestors(&self, mut view_id: usize) -> impl Iterator<Item = usize> + '_ {
1102 std::iter::once(view_id)
1103 .into_iter()
1104 .chain(std::iter::from_fn(move || {
1105 if let Some(parent_id) = self.window.parents.get(&view_id) {
1106 view_id = *parent_id;
1107 Some(view_id)
1108 } else {
1109 None
1110 }
1111 }))
1112 }
1113
1114 // Traverses the parent tree. Walks down the tree toward the passed
1115 // view calling visit with true. Then walks back up the tree calling visit with false.
1116 // If `visit` returns false this function will immediately return.
1117 fn visit_dispatch_path(
1118 &mut self,
1119 view_id: usize,
1120 mut visit: impl FnMut(usize, bool, &mut WindowContext) -> bool,
1121 ) {
1122 // List of view ids from the leaf to the root of the window
1123 let path = self.ancestors(view_id).collect::<Vec<_>>();
1124
1125 // Walk down from the root to the leaf calling visit with capture_phase = true
1126 for view_id in path.iter().rev() {
1127 if !visit(*view_id, true, self) {
1128 return;
1129 }
1130 }
1131
1132 // Walk up from the leaf to the root calling visit with capture_phase = false
1133 for view_id in path.iter() {
1134 if !visit(*view_id, false, self) {
1135 return;
1136 }
1137 }
1138 }
1139
1140 pub fn focused_view_id(&self) -> Option<usize> {
1141 self.window.focused_view_id
1142 }
1143
1144 pub fn focus(&mut self, view_id: Option<usize>) {
1145 self.app_context.focus(self.window_handle, view_id);
1146 }
1147
1148 pub fn window_bounds(&self) -> WindowBounds {
1149 self.window.platform_window.bounds()
1150 }
1151
1152 pub fn window_appearance(&self) -> Appearance {
1153 self.window.appearance
1154 }
1155
1156 pub fn window_display_uuid(&self) -> Option<Uuid> {
1157 self.window.platform_window.screen().display_uuid()
1158 }
1159
1160 pub fn show_character_palette(&self) {
1161 self.window.platform_window.show_character_palette();
1162 }
1163
1164 pub fn minimize_window(&self) {
1165 self.window.platform_window.minimize();
1166 }
1167
1168 pub fn zoom_window(&self) {
1169 self.window.platform_window.zoom();
1170 }
1171
1172 pub fn toggle_full_screen(&self) {
1173 self.window.platform_window.toggle_full_screen();
1174 }
1175
1176 pub fn prompt(
1177 &self,
1178 level: PromptLevel,
1179 msg: &str,
1180 answers: &[&str],
1181 ) -> oneshot::Receiver<usize> {
1182 self.window.platform_window.prompt(level, msg, answers)
1183 }
1184
1185 pub fn add_view<T, F>(&mut self, build_view: F) -> ViewHandle<T>
1186 where
1187 T: View,
1188 F: FnOnce(&mut ViewContext<T>) -> T,
1189 {
1190 self.add_option_view(|cx| Some(build_view(cx))).unwrap()
1191 }
1192
1193 pub fn add_option_view<T, F>(&mut self, build_view: F) -> Option<ViewHandle<T>>
1194 where
1195 T: View,
1196 F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1197 {
1198 let handle = self.window_handle;
1199 let view_id = post_inc(&mut self.next_id);
1200 let mut cx = ViewContext::mutable(self, view_id);
1201 let handle = if let Some(view) = build_view(&mut cx) {
1202 let mut keymap_context = KeymapContext::default();
1203 view.update_keymap_context(&mut keymap_context, cx.app_context());
1204 self.views_metadata.insert(
1205 (handle, view_id),
1206 ViewMetadata {
1207 type_id: TypeId::of::<T>(),
1208 keymap_context,
1209 },
1210 );
1211 self.views.insert((handle, view_id), Box::new(view));
1212 self.window
1213 .invalidation
1214 .get_or_insert_with(Default::default)
1215 .updated
1216 .insert(view_id);
1217 Some(ViewHandle::new(handle, view_id, &self.ref_counts))
1218 } else {
1219 None
1220 };
1221 handle
1222 }
1223}
1224
1225pub struct RenderParams {
1226 pub view_id: usize,
1227 pub titlebar_height: f32,
1228 pub refreshing: bool,
1229 pub appearance: Appearance,
1230}
1231
1232#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1233pub enum Axis {
1234 #[default]
1235 Horizontal,
1236 Vertical,
1237}
1238
1239impl Axis {
1240 pub fn invert(self) -> Self {
1241 match self {
1242 Self::Horizontal => Self::Vertical,
1243 Self::Vertical => Self::Horizontal,
1244 }
1245 }
1246
1247 pub fn component(&self, point: Vector2F) -> f32 {
1248 match self {
1249 Self::Horizontal => point.x(),
1250 Self::Vertical => point.y(),
1251 }
1252 }
1253}
1254
1255impl ToJson for Axis {
1256 fn to_json(&self) -> serde_json::Value {
1257 match self {
1258 Axis::Horizontal => json!("horizontal"),
1259 Axis::Vertical => json!("vertical"),
1260 }
1261 }
1262}
1263
1264impl StaticColumnCount for Axis {}
1265impl Bind for Axis {
1266 fn bind(&self, statement: &Statement, start_index: i32) -> anyhow::Result<i32> {
1267 match self {
1268 Axis::Horizontal => "Horizontal",
1269 Axis::Vertical => "Vertical",
1270 }
1271 .bind(statement, start_index)
1272 }
1273}
1274
1275impl Column for Axis {
1276 fn column(statement: &mut Statement, start_index: i32) -> anyhow::Result<(Self, i32)> {
1277 String::column(statement, start_index).and_then(|(axis_text, next_index)| {
1278 Ok((
1279 match axis_text.as_str() {
1280 "Horizontal" => Axis::Horizontal,
1281 "Vertical" => Axis::Vertical,
1282 _ => bail!("Stored serialized item kind is incorrect"),
1283 },
1284 next_index,
1285 ))
1286 })
1287 }
1288}
1289
1290pub trait Vector2FExt {
1291 fn along(self, axis: Axis) -> f32;
1292}
1293
1294impl Vector2FExt for Vector2F {
1295 fn along(self, axis: Axis) -> f32 {
1296 match axis {
1297 Axis::Horizontal => self.x(),
1298 Axis::Vertical => self.y(),
1299 }
1300 }
1301}
1302
1303pub trait RectFExt {
1304 fn length_along(self, axis: Axis) -> f32;
1305}
1306
1307impl RectFExt for RectF {
1308 fn length_along(self, axis: Axis) -> f32 {
1309 match axis {
1310 Axis::Horizontal => self.width(),
1311 Axis::Vertical => self.height(),
1312 }
1313 }
1314}
1315
1316#[derive(Copy, Clone, Debug)]
1317pub struct SizeConstraint {
1318 pub min: Vector2F,
1319 pub max: Vector2F,
1320}
1321
1322impl SizeConstraint {
1323 pub fn new(min: Vector2F, max: Vector2F) -> Self {
1324 Self { min, max }
1325 }
1326
1327 pub fn strict(size: Vector2F) -> Self {
1328 Self {
1329 min: size,
1330 max: size,
1331 }
1332 }
1333 pub fn loose(max: Vector2F) -> Self {
1334 Self {
1335 min: Vector2F::zero(),
1336 max,
1337 }
1338 }
1339
1340 pub fn strict_along(axis: Axis, max: f32) -> Self {
1341 match axis {
1342 Axis::Horizontal => Self {
1343 min: vec2f(max, 0.0),
1344 max: vec2f(max, f32::INFINITY),
1345 },
1346 Axis::Vertical => Self {
1347 min: vec2f(0.0, max),
1348 max: vec2f(f32::INFINITY, max),
1349 },
1350 }
1351 }
1352
1353 pub fn max_along(&self, axis: Axis) -> f32 {
1354 match axis {
1355 Axis::Horizontal => self.max.x(),
1356 Axis::Vertical => self.max.y(),
1357 }
1358 }
1359
1360 pub fn min_along(&self, axis: Axis) -> f32 {
1361 match axis {
1362 Axis::Horizontal => self.min.x(),
1363 Axis::Vertical => self.min.y(),
1364 }
1365 }
1366
1367 pub fn constrain(&self, size: Vector2F) -> Vector2F {
1368 vec2f(
1369 size.x().min(self.max.x()).max(self.min.x()),
1370 size.y().min(self.max.y()).max(self.min.y()),
1371 )
1372 }
1373}
1374
1375impl Sub<Vector2F> for SizeConstraint {
1376 type Output = SizeConstraint;
1377
1378 fn sub(self, rhs: Vector2F) -> SizeConstraint {
1379 SizeConstraint {
1380 min: self.min - rhs,
1381 max: self.max - rhs,
1382 }
1383 }
1384}
1385
1386impl Default for SizeConstraint {
1387 fn default() -> Self {
1388 SizeConstraint {
1389 min: Vector2F::zero(),
1390 max: Vector2F::splat(f32::INFINITY),
1391 }
1392 }
1393}
1394
1395impl ToJson for SizeConstraint {
1396 fn to_json(&self) -> serde_json::Value {
1397 json!({
1398 "min": self.min.to_json(),
1399 "max": self.max.to_json(),
1400 })
1401 }
1402}
1403
1404pub struct ChildView {
1405 view_id: usize,
1406 view_name: &'static str,
1407}
1408
1409impl ChildView {
1410 pub fn new(view: &AnyViewHandle, cx: &AppContext) -> Self {
1411 let view_name = cx.view_ui_name(view.window, view.id()).unwrap();
1412 Self {
1413 view_id: view.id(),
1414 view_name,
1415 }
1416 }
1417}
1418
1419impl<V: 'static> Element<V> for ChildView {
1420 type LayoutState = ();
1421 type PaintState = ();
1422
1423 fn layout(
1424 &mut self,
1425 constraint: SizeConstraint,
1426 _: &mut V,
1427 cx: &mut LayoutContext<V>,
1428 ) -> (Vector2F, Self::LayoutState) {
1429 if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1430 cx.new_parents.insert(self.view_id, cx.view_id());
1431 let size = rendered_view
1432 .layout(
1433 constraint,
1434 cx.new_parents,
1435 cx.views_to_notify_if_ancestors_change,
1436 cx.refreshing,
1437 cx.view_context,
1438 )
1439 .log_err()
1440 .unwrap_or(Vector2F::zero());
1441 cx.window.rendered_views.insert(self.view_id, rendered_view);
1442 (size, ())
1443 } else {
1444 log::error!(
1445 "layout called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1446 self.view_id,
1447 self.view_name
1448 );
1449 (Vector2F::zero(), ())
1450 }
1451 }
1452
1453 fn paint(
1454 &mut self,
1455 scene: &mut SceneBuilder,
1456 bounds: RectF,
1457 visible_bounds: RectF,
1458 _: &mut Self::LayoutState,
1459 _: &mut V,
1460 cx: &mut PaintContext<V>,
1461 ) {
1462 if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1463 rendered_view
1464 .paint(scene, bounds.origin(), visible_bounds, cx)
1465 .log_err();
1466 cx.window.rendered_views.insert(self.view_id, rendered_view);
1467 } else {
1468 log::error!(
1469 "paint called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1470 self.view_id,
1471 self.view_name
1472 );
1473 }
1474 }
1475
1476 fn rect_for_text_range(
1477 &self,
1478 range_utf16: Range<usize>,
1479 _: RectF,
1480 _: RectF,
1481 _: &Self::LayoutState,
1482 _: &Self::PaintState,
1483 _: &V,
1484 cx: &ViewContext<V>,
1485 ) -> Option<RectF> {
1486 if let Some(rendered_view) = cx.window.rendered_views.get(&self.view_id) {
1487 rendered_view
1488 .rect_for_text_range(range_utf16, &cx.window_context)
1489 .log_err()
1490 .flatten()
1491 } else {
1492 log::error!(
1493 "rect_for_text_range called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1494 self.view_id,
1495 self.view_name
1496 );
1497 None
1498 }
1499 }
1500
1501 fn debug(
1502 &self,
1503 bounds: RectF,
1504 _: &Self::LayoutState,
1505 _: &Self::PaintState,
1506 _: &V,
1507 cx: &ViewContext<V>,
1508 ) -> serde_json::Value {
1509 json!({
1510 "type": "ChildView",
1511 "bounds": bounds.to_json(),
1512 "child": if let Some(element) = cx.window.rendered_views.get(&self.view_id) {
1513 element.debug(&cx.window_context).log_err().unwrap_or_else(|| json!(null))
1514 } else {
1515 json!(null)
1516 }
1517 })
1518 }
1519}