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 titlebar_height(&self) -> f32 {
1194 self.window.titlebar_height
1195 }
1196
1197 pub fn window_appearance(&self) -> Appearance {
1198 self.window.appearance
1199 }
1200
1201 pub fn window_display_uuid(&self) -> Option<Uuid> {
1202 self.window.platform_window.screen().display_uuid()
1203 }
1204
1205 pub fn show_character_palette(&self) {
1206 self.window.platform_window.show_character_palette();
1207 }
1208
1209 pub fn minimize_window(&self) {
1210 self.window.platform_window.minimize();
1211 }
1212
1213 pub fn zoom_window(&self) {
1214 self.window.platform_window.zoom();
1215 }
1216
1217 pub fn toggle_full_screen(&self) {
1218 self.window.platform_window.toggle_full_screen();
1219 }
1220
1221 pub fn prompt(
1222 &self,
1223 level: PromptLevel,
1224 msg: &str,
1225 answers: &[&str],
1226 ) -> oneshot::Receiver<usize> {
1227 self.window.platform_window.prompt(level, msg, answers)
1228 }
1229
1230 pub fn add_view<T, F>(&mut self, build_view: F) -> ViewHandle<T>
1231 where
1232 T: View,
1233 F: FnOnce(&mut ViewContext<T>) -> T,
1234 {
1235 self.add_option_view(|cx| Some(build_view(cx))).unwrap()
1236 }
1237
1238 pub fn add_option_view<T, F>(&mut self, build_view: F) -> Option<ViewHandle<T>>
1239 where
1240 T: View,
1241 F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1242 {
1243 let handle = self.window_handle;
1244 let view_id = post_inc(&mut self.next_id);
1245 let mut cx = ViewContext::mutable(self, view_id);
1246 let handle = if let Some(view) = build_view(&mut cx) {
1247 let mut keymap_context = KeymapContext::default();
1248 view.update_keymap_context(&mut keymap_context, cx.app_context());
1249 self.views_metadata.insert(
1250 (handle, view_id),
1251 ViewMetadata {
1252 type_id: TypeId::of::<T>(),
1253 keymap_context,
1254 },
1255 );
1256 self.views.insert((handle, view_id), Box::new(view));
1257 self.window
1258 .invalidation
1259 .get_or_insert_with(Default::default)
1260 .updated
1261 .insert(view_id);
1262 Some(ViewHandle::new(handle, view_id, &self.ref_counts))
1263 } else {
1264 None
1265 };
1266 handle
1267 }
1268}
1269
1270#[derive(Default)]
1271pub struct LayoutEngine(Taffy);
1272pub use taffy::style::Style as LayoutStyle;
1273
1274impl LayoutEngine {
1275 pub fn new() -> Self {
1276 Default::default()
1277 }
1278
1279 pub fn add_node<C>(&mut self, style: LayoutStyle, children: C) -> Result<LayoutId>
1280 where
1281 C: IntoIterator<Item = LayoutId>,
1282 {
1283 let children = children.into_iter().collect::<Vec<_>>();
1284 if children.is_empty() {
1285 Ok(self.0.new_leaf(style)?)
1286 } else {
1287 Ok(self.0.new_with_children(style, &children)?)
1288 }
1289 }
1290
1291 pub fn add_measured_node<F>(&mut self, style: LayoutStyle, measure: F) -> Result<LayoutId>
1292 where
1293 F: Fn(MeasureParams) -> Size<f32> + Sync + Send + 'static,
1294 {
1295 Ok(self
1296 .0
1297 .new_leaf_with_measure(style, MeasureFunc::Boxed(Box::new(MeasureFn(measure))))?)
1298 }
1299
1300 pub fn compute_layout(&mut self, root: LayoutId, available_space: Vector2F) -> Result<()> {
1301 self.0.compute_layout(
1302 root,
1303 taffy::geometry::Size {
1304 width: available_space.x().into(),
1305 height: available_space.y().into(),
1306 },
1307 )?;
1308 Ok(())
1309 }
1310
1311 pub fn computed_layout(&mut self, node: LayoutId) -> Result<Layout> {
1312 Ok(Layout::from(self.0.layout(node)?))
1313 }
1314}
1315
1316pub struct MeasureFn<F>(F);
1317
1318impl<F: Send + Sync> Measurable for MeasureFn<F>
1319where
1320 F: Fn(MeasureParams) -> Size<f32>,
1321{
1322 fn measure(
1323 &self,
1324 known_dimensions: taffy::prelude::Size<Option<f32>>,
1325 available_space: taffy::prelude::Size<taffy::style::AvailableSpace>,
1326 ) -> taffy::prelude::Size<f32> {
1327 (self.0)(MeasureParams {
1328 known_dimensions: known_dimensions.into(),
1329 available_space: available_space.into(),
1330 })
1331 .into()
1332 }
1333}
1334
1335#[derive(Debug, Clone, Default)]
1336pub struct Layout {
1337 pub bounds: RectF,
1338 pub order: u32,
1339}
1340
1341pub struct MeasureParams {
1342 pub known_dimensions: Size<Option<f32>>,
1343 pub available_space: Size<AvailableSpace>,
1344}
1345
1346#[derive(Clone)]
1347pub enum AvailableSpace {
1348 /// The amount of space available is the specified number of pixels
1349 Pixels(f32),
1350 /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
1351 MinContent,
1352 /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
1353 MaxContent,
1354}
1355
1356impl Default for AvailableSpace {
1357 fn default() -> Self {
1358 Self::Pixels(0.)
1359 }
1360}
1361
1362impl From<taffy::prelude::AvailableSpace> for AvailableSpace {
1363 fn from(value: taffy::prelude::AvailableSpace) -> Self {
1364 match value {
1365 taffy::prelude::AvailableSpace::Definite(pixels) => Self::Pixels(pixels),
1366 taffy::prelude::AvailableSpace::MinContent => Self::MinContent,
1367 taffy::prelude::AvailableSpace::MaxContent => Self::MaxContent,
1368 }
1369 }
1370}
1371
1372impl From<&taffy::tree::Layout> for Layout {
1373 fn from(value: &taffy::tree::Layout) -> Self {
1374 Self {
1375 bounds: RectF::new(
1376 vec2f(value.location.x, value.location.y),
1377 vec2f(value.size.width, value.size.height),
1378 ),
1379 order: value.order,
1380 }
1381 }
1382}
1383
1384pub type LayoutId = taffy::prelude::NodeId;
1385
1386pub struct RenderParams {
1387 pub view_id: usize,
1388 pub titlebar_height: f32,
1389 pub refreshing: bool,
1390 pub appearance: Appearance,
1391}
1392
1393#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1394pub enum Axis {
1395 #[default]
1396 Horizontal,
1397 Vertical,
1398}
1399
1400impl Axis {
1401 pub fn invert(self) -> Self {
1402 match self {
1403 Self::Horizontal => Self::Vertical,
1404 Self::Vertical => Self::Horizontal,
1405 }
1406 }
1407
1408 pub fn component(&self, point: Vector2F) -> f32 {
1409 match self {
1410 Self::Horizontal => point.x(),
1411 Self::Vertical => point.y(),
1412 }
1413 }
1414}
1415
1416impl ToJson for Axis {
1417 fn to_json(&self) -> serde_json::Value {
1418 match self {
1419 Axis::Horizontal => json!("horizontal"),
1420 Axis::Vertical => json!("vertical"),
1421 }
1422 }
1423}
1424
1425impl StaticColumnCount for Axis {}
1426impl Bind for Axis {
1427 fn bind(&self, statement: &Statement, start_index: i32) -> anyhow::Result<i32> {
1428 match self {
1429 Axis::Horizontal => "Horizontal",
1430 Axis::Vertical => "Vertical",
1431 }
1432 .bind(statement, start_index)
1433 }
1434}
1435
1436impl Column for Axis {
1437 fn column(statement: &mut Statement, start_index: i32) -> anyhow::Result<(Self, i32)> {
1438 String::column(statement, start_index).and_then(|(axis_text, next_index)| {
1439 Ok((
1440 match axis_text.as_str() {
1441 "Horizontal" => Axis::Horizontal,
1442 "Vertical" => Axis::Vertical,
1443 _ => bail!("Stored serialized item kind is incorrect"),
1444 },
1445 next_index,
1446 ))
1447 })
1448 }
1449}
1450
1451pub trait Vector2FExt {
1452 fn along(self, axis: Axis) -> f32;
1453}
1454
1455impl Vector2FExt for Vector2F {
1456 fn along(self, axis: Axis) -> f32 {
1457 match axis {
1458 Axis::Horizontal => self.x(),
1459 Axis::Vertical => self.y(),
1460 }
1461 }
1462}
1463
1464pub trait RectFExt {
1465 fn length_along(self, axis: Axis) -> f32;
1466}
1467
1468impl RectFExt for RectF {
1469 fn length_along(self, axis: Axis) -> f32 {
1470 match axis {
1471 Axis::Horizontal => self.width(),
1472 Axis::Vertical => self.height(),
1473 }
1474 }
1475}
1476
1477#[derive(Copy, Clone, Debug)]
1478pub struct SizeConstraint {
1479 pub min: Vector2F,
1480 pub max: Vector2F,
1481}
1482
1483impl SizeConstraint {
1484 pub fn new(min: Vector2F, max: Vector2F) -> Self {
1485 Self { min, max }
1486 }
1487
1488 pub fn strict(size: Vector2F) -> Self {
1489 Self {
1490 min: size,
1491 max: size,
1492 }
1493 }
1494 pub fn loose(max: Vector2F) -> Self {
1495 Self {
1496 min: Vector2F::zero(),
1497 max,
1498 }
1499 }
1500
1501 pub fn strict_along(axis: Axis, max: f32) -> Self {
1502 match axis {
1503 Axis::Horizontal => Self {
1504 min: vec2f(max, 0.0),
1505 max: vec2f(max, f32::INFINITY),
1506 },
1507 Axis::Vertical => Self {
1508 min: vec2f(0.0, max),
1509 max: vec2f(f32::INFINITY, max),
1510 },
1511 }
1512 }
1513
1514 pub fn max_along(&self, axis: Axis) -> f32 {
1515 match axis {
1516 Axis::Horizontal => self.max.x(),
1517 Axis::Vertical => self.max.y(),
1518 }
1519 }
1520
1521 pub fn min_along(&self, axis: Axis) -> f32 {
1522 match axis {
1523 Axis::Horizontal => self.min.x(),
1524 Axis::Vertical => self.min.y(),
1525 }
1526 }
1527
1528 pub fn constrain(&self, size: Vector2F) -> Vector2F {
1529 vec2f(
1530 size.x().min(self.max.x()).max(self.min.x()),
1531 size.y().min(self.max.y()).max(self.min.y()),
1532 )
1533 }
1534}
1535
1536impl Sub<Vector2F> for SizeConstraint {
1537 type Output = SizeConstraint;
1538
1539 fn sub(self, rhs: Vector2F) -> SizeConstraint {
1540 SizeConstraint {
1541 min: self.min - rhs,
1542 max: self.max - rhs,
1543 }
1544 }
1545}
1546
1547impl Default for SizeConstraint {
1548 fn default() -> Self {
1549 SizeConstraint {
1550 min: Vector2F::zero(),
1551 max: Vector2F::splat(f32::INFINITY),
1552 }
1553 }
1554}
1555
1556impl ToJson for SizeConstraint {
1557 fn to_json(&self) -> serde_json::Value {
1558 json!({
1559 "min": self.min.to_json(),
1560 "max": self.max.to_json(),
1561 })
1562 }
1563}
1564
1565#[derive(Clone)]
1566pub struct ChildView {
1567 view_id: usize,
1568 view_name: &'static str,
1569}
1570
1571impl ChildView {
1572 pub fn new(view: &AnyViewHandle, cx: &AppContext) -> Self {
1573 let view_name = cx.view_ui_name(view.window, view.id()).unwrap();
1574 Self {
1575 view_id: view.id(),
1576 view_name,
1577 }
1578 }
1579}
1580
1581impl<V: 'static> Element<V> for ChildView {
1582 type LayoutState = ();
1583 type PaintState = ();
1584
1585 fn layout(
1586 &mut self,
1587 constraint: SizeConstraint,
1588 _: &mut V,
1589 cx: &mut LayoutContext<V>,
1590 ) -> (Vector2F, Self::LayoutState) {
1591 if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1592 cx.new_parents.insert(self.view_id, cx.view_id());
1593 let size = rendered_view
1594 .layout(
1595 constraint,
1596 cx.new_parents,
1597 cx.views_to_notify_if_ancestors_change,
1598 cx.refreshing,
1599 cx.view_context,
1600 )
1601 .log_err()
1602 .unwrap_or(Vector2F::zero());
1603 cx.window.rendered_views.insert(self.view_id, rendered_view);
1604 (size, ())
1605 } else {
1606 log::error!(
1607 "layout called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1608 self.view_id,
1609 self.view_name
1610 );
1611 (Vector2F::zero(), ())
1612 }
1613 }
1614
1615 fn paint(
1616 &mut self,
1617 scene: &mut SceneBuilder,
1618 bounds: RectF,
1619 visible_bounds: RectF,
1620 _: &mut Self::LayoutState,
1621 _: &mut V,
1622 cx: &mut PaintContext<V>,
1623 ) {
1624 if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1625 rendered_view
1626 .paint(scene, bounds.origin(), visible_bounds, cx)
1627 .log_err();
1628 cx.window.rendered_views.insert(self.view_id, rendered_view);
1629 } else {
1630 log::error!(
1631 "paint called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1632 self.view_id,
1633 self.view_name
1634 );
1635 }
1636 }
1637
1638 fn rect_for_text_range(
1639 &self,
1640 range_utf16: Range<usize>,
1641 _: RectF,
1642 _: RectF,
1643 _: &Self::LayoutState,
1644 _: &Self::PaintState,
1645 _: &V,
1646 cx: &ViewContext<V>,
1647 ) -> Option<RectF> {
1648 if let Some(rendered_view) = cx.window.rendered_views.get(&self.view_id) {
1649 rendered_view
1650 .rect_for_text_range(range_utf16, &cx.window_context)
1651 .log_err()
1652 .flatten()
1653 } else {
1654 log::error!(
1655 "rect_for_text_range called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1656 self.view_id,
1657 self.view_name
1658 );
1659 None
1660 }
1661 }
1662
1663 fn debug(
1664 &self,
1665 bounds: RectF,
1666 _: &Self::LayoutState,
1667 _: &Self::PaintState,
1668 _: &V,
1669 cx: &ViewContext<V>,
1670 ) -> serde_json::Value {
1671 json!({
1672 "type": "ChildView",
1673 "bounds": bounds.to_json(),
1674 "child": if let Some(element) = cx.window.rendered_views.get(&self.view_id) {
1675 element.debug(&cx.window_context).log_err().unwrap_or_else(|| json!(null))
1676 } else {
1677 json!(null)
1678 }
1679 })
1680 }
1681}