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