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