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