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