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