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