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