1use gpui::{
8 Anchor, AnyElement, App, Bounds, Decorations, Display, Edges, Element, GlobalElementId,
9 Half as _, HitboxBehavior, InspectorElementId, LayoutId, ParentElement, Pixels, Point,
10 Position, Size, Style, Window, point, px,
11};
12
13use crate::{LayoutDirection, Placement};
14use std::{cell::Cell, rc::Rc};
15
16#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
18pub enum Align {
19 Start,
21 #[default]
23 Center,
24 End,
26}
27
28#[derive(Clone, Copy, Debug, PartialEq)]
30enum Strategy {
31 Corner {
35 anchor: Anchor,
36 position: Point<Pixels>,
37 },
38 Side {
41 trigger_bounds: Bounds<Pixels>,
42 placement: Option<Placement>,
43 align: Align,
44 offset: Pixels,
45 },
46}
47
48impl Align {
49 fn horizontal(self, direction: LayoutDirection) -> Self {
52 match (self, direction) {
53 (Align::Start, LayoutDirection::Rtl) => Align::End,
54 (Align::End, LayoutDirection::Rtl) => Align::Start,
55 (align, _) => align,
56 }
57 }
58}
59
60#[derive(Clone, Copy, Debug, PartialEq)]
62pub struct ResolvedPosition {
63 pub bounds: Bounds<Pixels>,
65 pub placement: Option<Placement>,
68}
69
70pub struct Positioner {
76 strategy: Strategy,
77 corner_position: Option<Rc<Cell<Point<Pixels>>>>,
78 on_position: Option<Box<dyn Fn(ResolvedPosition)>>,
79 margin: Pixels,
80 occlude: bool,
81 children: Vec<AnyElement>,
82}
83
84#[doc(hidden)]
85pub struct PositionerState {
86 child_layout_ids: Vec<LayoutId>,
87}
88
89impl Positioner {
90 pub fn side(trigger_bounds: Bounds<Pixels>) -> Self {
92 Self {
93 strategy: Strategy::Side {
94 trigger_bounds,
95 placement: None,
96 align: Align::Center,
97 offset: px(0.),
98 },
99 corner_position: None,
100 on_position: None,
101 margin: px(4.),
102 occlude: false,
103 children: Vec::new(),
104 }
105 }
106
107 pub fn corner(anchor: Anchor, position: Point<Pixels>) -> Self {
113 Self {
114 strategy: Strategy::Corner { anchor, position },
115 corner_position: None,
116 on_position: None,
117 margin: px(4.),
118 occlude: false,
119 children: Vec::new(),
120 }
121 }
122
123 pub fn position(mut self, position: Point<Pixels>) -> Self {
128 if let Strategy::Corner {
129 position: current, ..
130 } = &mut self.strategy
131 {
132 *current = position;
133 }
134 self
135 }
136
137 pub fn placement(mut self, placement: Placement) -> Self {
139 if let Strategy::Side {
140 placement: slot, ..
141 } = &mut self.strategy
142 {
143 *slot = Some(placement);
144 }
145 self
146 }
147
148 pub fn align(mut self, align: Align) -> Self {
151 if let Strategy::Side { align: slot, .. } = &mut self.strategy {
152 *slot = align;
153 }
154 self
155 }
156
157 pub fn offset(mut self, offset: Pixels) -> Self {
160 if let Strategy::Side { offset: slot, .. } = &mut self.strategy {
161 *slot = offset;
162 }
163 self
164 }
165
166 pub(crate) fn tracked_corner_position(mut self, position: Rc<Cell<Point<Pixels>>>) -> Self {
168 self.corner_position = Some(position);
169 self
170 }
171
172 pub fn on_position(mut self, callback: impl Fn(ResolvedPosition) + 'static) -> Self {
174 self.on_position = Some(Box::new(callback));
175 self
176 }
177
178 pub fn occlude(mut self) -> Self {
185 self.occlude = true;
186 self
187 }
188
189 pub fn margin(mut self, margin: Pixels) -> Self {
191 self.margin = margin;
192 self
193 }
194}
195
196fn frame_insets(decorations: Decorations, client_inset: Pixels) -> Edges<Pixels> {
207 match decorations {
208 Decorations::Server => Edges::default(),
209 Decorations::Client { tiling } => Edges {
210 top: if tiling.top { px(0.) } else { client_inset },
211 right: if tiling.right { px(0.) } else { client_inset },
212 bottom: if tiling.bottom { px(0.) } else { client_inset },
213 left: if tiling.left { px(0.) } else { client_inset },
214 },
215 }
216}
217
218#[cfg(test)]
224fn resolve(
225 strategy: Strategy,
226 popup_size: Size<Pixels>,
227 viewport_size: Size<Pixels>,
228 margin: Edges<Pixels>,
229) -> ResolvedPosition {
230 resolve_in(
231 strategy,
232 popup_size,
233 viewport_size,
234 margin,
235 LayoutDirection::Ltr,
236 )
237}
238
239fn resolve_in(
242 strategy: Strategy,
243 popup_size: Size<Pixels>,
244 viewport_size: Size<Pixels>,
245 margin: Edges<Pixels>,
246 direction: LayoutDirection,
247) -> ResolvedPosition {
248 match strategy {
249 Strategy::Corner { anchor, position } => ResolvedPosition {
250 bounds: clamp(
251 Bounds::from_anchor_and_size(anchor, position, popup_size),
252 viewport_size,
253 margin,
254 ),
255 placement: None,
256 },
257 Strategy::Side {
258 trigger_bounds,
259 placement,
260 align,
261 offset,
262 } => {
263 let placement =
264 resolve_placement(trigger_bounds, popup_size, viewport_size, margin, placement);
265 let origin = side_origin(
266 trigger_bounds,
267 popup_size,
268 placement,
269 align,
270 offset,
271 direction,
272 );
273 ResolvedPosition {
274 bounds: clamp(Bounds::new(origin, popup_size), viewport_size, margin),
275 placement: Some(placement),
276 }
277 }
278 }
279}
280
281fn resolve_placement(
282 trigger_bounds: Bounds<Pixels>,
283 popup_size: Size<Pixels>,
284 viewport_size: Size<Pixels>,
285 margin: Edges<Pixels>,
286 preferred: Option<Placement>,
287) -> Placement {
288 let right_limit = (viewport_size.width - margin.right).max(margin.left);
289 let bottom_limit = (viewport_size.height - margin.bottom).max(margin.top);
290 let available_left = (trigger_bounds.left() - margin.left).max(px(0.));
291 let available_right = (right_limit - trigger_bounds.right()).max(px(0.));
292 let available_above = (trigger_bounds.top() - margin.top).max(px(0.));
293 let available_below = (bottom_limit - trigger_bounds.bottom()).max(px(0.));
294
295 match preferred {
296 Some(Placement::Right) if popup_size.width <= available_right => Placement::Right,
297 Some(Placement::Right) if popup_size.width <= available_left => Placement::Left,
298 Some(Placement::Right) if available_right >= available_left => Placement::Right,
299 Some(Placement::Right) => Placement::Left,
300 Some(Placement::Left) if popup_size.width <= available_left => Placement::Left,
301 Some(Placement::Left) if popup_size.width <= available_right => Placement::Right,
302 Some(Placement::Left) if available_left >= available_right => Placement::Left,
303 Some(Placement::Left) => Placement::Right,
304 Some(Placement::Bottom) if popup_size.height <= available_below => Placement::Bottom,
305 Some(Placement::Bottom) if popup_size.height <= available_above => Placement::Top,
306 Some(Placement::Bottom) if available_below >= available_above => Placement::Bottom,
307 Some(Placement::Bottom) => Placement::Top,
308 Some(Placement::Top) | None if popup_size.height <= available_above => Placement::Top,
309 Some(Placement::Top) | None if popup_size.height <= available_below => Placement::Bottom,
310 Some(Placement::Top) | None if available_below >= available_above => Placement::Bottom,
311 Some(Placement::Top) | None => Placement::Top,
312 }
313}
314
315fn side_origin(
316 trigger_bounds: Bounds<Pixels>,
317 popup_size: Size<Pixels>,
318 placement: Placement,
319 align: Align,
320 offset: Pixels,
321 direction: LayoutDirection,
322) -> Point<Pixels> {
323 let aligned_x = match align.horizontal(direction) {
324 Align::Start => trigger_bounds.left(),
325 Align::Center => trigger_bounds.center().x - popup_size.width.half(),
326 Align::End => trigger_bounds.right() - popup_size.width,
327 };
328 let aligned_y = match align {
329 Align::Start => trigger_bounds.top(),
330 Align::Center => trigger_bounds.center().y - popup_size.height.half(),
331 Align::End => trigger_bounds.bottom() - popup_size.height,
332 };
333
334 match placement {
335 Placement::Top => point(aligned_x, trigger_bounds.top() - popup_size.height - offset),
336 Placement::Bottom => point(aligned_x, trigger_bounds.bottom() + offset),
337 Placement::Left => point(trigger_bounds.left() - popup_size.width - offset, aligned_y),
338 Placement::Right => point(trigger_bounds.right() + offset, aligned_y),
339 }
340}
341
342fn clamp(
343 mut bounds: Bounds<Pixels>,
344 viewport_size: Size<Pixels>,
345 margin: Edges<Pixels>,
346) -> Bounds<Pixels> {
347 let right_limit = (viewport_size.width - margin.right).max(margin.left);
348 let bottom_limit = (viewport_size.height - margin.bottom).max(margin.top);
349
350 if bounds.right() > right_limit {
351 bounds.origin.x -= bounds.right() - right_limit;
352 }
353 if bounds.left() < margin.left {
354 bounds.origin.x = margin.left;
355 }
356 if bounds.bottom() > bottom_limit {
357 bounds.origin.y -= bounds.bottom() - bottom_limit;
358 }
359 if bounds.top() < margin.top {
360 bounds.origin.y = margin.top;
361 }
362
363 bounds
364}
365
366impl ParentElement for Positioner {
367 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
368 self.children.extend(elements);
369 }
370}
371
372impl Element for Positioner {
373 type RequestLayoutState = PositionerState;
374 type PrepaintState = ();
375
376 fn id(&self) -> Option<gpui::ElementId> {
377 None
378 }
379
380 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
381 None
382 }
383
384 fn request_layout(
385 &mut self,
386 _: Option<&GlobalElementId>,
387 _: Option<&InspectorElementId>,
388 window: &mut Window,
389 cx: &mut App,
390 ) -> (LayoutId, Self::RequestLayoutState) {
391 let child_layout_ids = self
392 .children
393 .iter_mut()
394 .map(|child| child.request_layout(window, cx))
395 .collect::<Vec<_>>();
396 let layout_id = window.request_layout(
397 Style {
398 position: Position::Absolute,
399 display: Display::Flex,
400 ..Style::default()
401 },
402 child_layout_ids.iter().copied(),
403 cx,
404 );
405
406 (layout_id, PositionerState { child_layout_ids })
407 }
408
409 fn prepaint(
410 &mut self,
411 _: Option<&GlobalElementId>,
412 _: Option<&InspectorElementId>,
413 bounds: Bounds<Pixels>,
414 request_layout: &mut Self::RequestLayoutState,
415 window: &mut Window,
416 cx: &mut App,
417 ) {
418 if request_layout.child_layout_ids.is_empty() {
419 return;
420 }
421
422 let mut child_min = point(Pixels::MAX, Pixels::MAX);
423 let mut child_max = Point::default();
424 for child_layout_id in &request_layout.child_layout_ids {
425 let child_bounds = window.layout_bounds(*child_layout_id);
426 child_min = child_min.min(&child_bounds.origin);
427 child_max = child_max.max(&child_bounds.bottom_right());
428 }
429
430 let popup_size = (child_max - child_min).into();
431 let frame = frame_insets(
432 window.window_decorations(),
433 window.client_inset().unwrap_or(px(0.)),
434 );
435 let mut strategy = self.strategy;
436 if let (Strategy::Corner { position, .. }, Some(tracked)) =
437 (&mut strategy, &self.corner_position)
438 {
439 *position = tracked.get();
440 }
441 let position = resolve_in(
442 strategy,
443 popup_size,
444 window.viewport_size(),
445 frame.map(|inset| *inset + self.margin),
446 LayoutDirection::global(cx),
447 );
448 if let Some(callback) = &self.on_position {
449 callback(position);
450 }
451 if self.occlude {
454 window.insert_hitbox(position.bounds, HitboxBehavior::BlockMouse);
455 }
456
457 let offset = position.bounds.origin - bounds.origin;
458 let offset = point(offset.x.round(), offset.y.round());
459
460 window.with_element_offset(offset, |window| {
461 for child in &mut self.children {
462 child.prepaint(window, cx);
463 }
464 });
465 }
466
467 fn paint(
468 &mut self,
469 _: Option<&GlobalElementId>,
470 _: Option<&InspectorElementId>,
471 _: Bounds<Pixels>,
472 _: &mut Self::RequestLayoutState,
473 _: &mut Self::PrepaintState,
474 window: &mut Window,
475 cx: &mut App,
476 ) {
477 for child in &mut self.children {
478 child.paint(window, cx);
479 }
480 }
481}
482
483#[cfg(not(feature = "gpui-fast"))]
484impl gpui::IntoElement for Positioner {
485 type Element = Self;
486
487 fn into_element(self) -> Self::Element {
488 self
489 }
490}
491
492#[cfg(test)]
493mod tests {
494 use super::*;
495 use gpui::Tiling;
496
497 const MARGIN: Pixels = px(4.);
498
499 fn trigger(x: f32, y: f32, w: f32, h: f32) -> Bounds<Pixels> {
500 Bounds::new(point(px(x), px(y)), Size::new(px(w), px(h)))
501 }
502
503 fn viewport() -> Size<Pixels> {
504 Size::new(px(500.), px(400.))
505 }
506
507 fn side(
508 trigger_bounds: Bounds<Pixels>,
509 placement: Option<Placement>,
510 align: Align,
511 popup: Size<Pixels>,
512 ) -> ResolvedPosition {
513 resolve(
514 Strategy::Side {
515 trigger_bounds,
516 placement,
517 align,
518 offset: px(0.),
519 },
520 popup,
521 viewport(),
522 Edges::all(MARGIN),
523 )
524 }
525
526 #[test]
527 fn prefers_the_requested_side_when_it_fits() {
528 let position = side(
529 trigger(200., 200., 40., 20.),
530 Some(Placement::Top),
531 Align::Center,
532 Size::new(px(80.), px(30.)),
533 );
534
535 assert_eq!(position.placement, Some(Placement::Top));
536 assert_eq!(position.bounds.bottom(), px(200.));
537 }
538
539 #[test]
540 fn flips_to_the_opposite_side_when_the_preferred_side_does_not_fit() {
541 let position = side(
542 trigger(200., 10., 40., 20.),
543 Some(Placement::Top),
544 Align::Center,
545 Size::new(px(80.), px(60.)),
546 );
547
548 assert_eq!(position.placement, Some(Placement::Bottom));
549 assert_eq!(position.bounds.top(), px(30.));
550 }
551
552 #[test]
553 fn clamps_into_the_viewport_while_keeping_the_flipped_side() {
554 let position = side(
555 trigger(480., 200., 40., 20.),
556 Some(Placement::Bottom),
557 Align::Center,
558 Size::new(px(120.), px(30.)),
559 );
560
561 assert_eq!(position.placement, Some(Placement::Bottom));
562 assert_eq!(position.bounds.right(), viewport().width - MARGIN);
563 }
564
565 #[test]
566 fn alignment_selects_the_leading_center_or_trailing_edge() {
567 let trigger_bounds = trigger(200., 200., 100., 20.);
568 let popup = Size::new(px(40.), px(30.));
569
570 let start = side(trigger_bounds, Some(Placement::Bottom), Align::Start, popup);
571 let center = side(
572 trigger_bounds,
573 Some(Placement::Bottom),
574 Align::Center,
575 popup,
576 );
577 let end = side(trigger_bounds, Some(Placement::Bottom), Align::End, popup);
578
579 assert_eq!(start.bounds.left(), px(200.));
580 assert_eq!(center.bounds.left(), px(230.));
581 assert_eq!(end.bounds.left(), px(260.));
582 }
583
584 #[test]
585 fn rtl_aligns_start_with_the_right_edge_of_the_trigger() {
586 let strategy = |align| Strategy::Side {
587 trigger_bounds: trigger(200., 200., 100., 20.),
588 placement: Some(Placement::Bottom),
589 align,
590 offset: px(0.),
591 };
592 let popup = Size::new(px(40.), px(30.));
593 let resolve_rtl = |align| {
594 resolve_in(
595 strategy(align),
596 popup,
597 viewport(),
598 Edges::all(MARGIN),
599 LayoutDirection::Rtl,
600 )
601 };
602
603 assert_eq!(resolve_rtl(Align::Start).bounds.right(), px(300.));
604 assert_eq!(resolve_rtl(Align::Center).bounds.left(), px(230.));
605 assert_eq!(resolve_rtl(Align::End).bounds.left(), px(200.));
606 }
607
608 #[test]
609 fn side_offset_adds_a_gap_between_trigger_and_popup() {
610 let position = resolve(
611 Strategy::Side {
612 trigger_bounds: trigger(200., 200., 40., 20.),
613 placement: Some(Placement::Bottom),
614 align: Align::Center,
615 offset: px(8.),
616 },
617 Size::new(px(40.), px(30.)),
618 viewport(),
619 Edges::all(MARGIN),
620 );
621
622 assert_eq!(position.bounds.top(), px(228.));
623 }
624
625 #[test]
626 fn corner_positioning_places_the_named_corner_and_never_reports_a_side() {
627 let position = resolve(
628 Strategy::Corner {
629 anchor: Anchor::TopLeft,
630 position: point(px(100.), px(100.)),
631 },
632 Size::new(px(40.), px(30.)),
633 viewport(),
634 Edges::all(MARGIN),
635 );
636
637 assert_eq!(position.placement, None);
638 assert_eq!(position.bounds.origin, point(px(100.), px(100.)));
639 }
640
641 #[test]
642 fn corner_positioning_clamps_but_does_not_flip() {
643 let position = resolve(
644 Strategy::Corner {
645 anchor: Anchor::TopLeft,
646 position: point(px(480.), px(390.)),
647 },
648 Size::new(px(40.), px(30.)),
649 viewport(),
650 Edges::all(MARGIN),
651 );
652
653 assert_eq!(position.placement, None);
654 assert_eq!(position.bounds.right(), viewport().width - MARGIN);
655 assert_eq!(position.bounds.bottom(), viewport().height - MARGIN);
656 }
657
658 #[test]
659 fn corner_position_can_be_updated_without_rebuilding_the_positioner() {
660 let positioner = Positioner::corner(Anchor::TopLeft, point(px(10.), px(20.)))
661 .position(point(px(30.), px(40.)));
662
663 assert!(matches!(
664 positioner.strategy,
665 Strategy::Corner {
666 position,
667 ..
668 } if position == point(px(30.), px(40.))
669 ));
670 }
671
672 #[test]
675 fn frame_insets_apply_the_client_inset_only_on_untiled_edges() {
676 let inset = px(20.);
677
678 assert_eq!(
679 frame_insets(Decorations::Server, inset),
680 Edges::default(),
681 "a server-decorated window has no frame to keep clear of"
682 );
683 assert_eq!(
684 frame_insets(
685 Decorations::Client {
686 tiling: Tiling::tiled()
687 },
688 inset
689 ),
690 Edges::default(),
691 "a window tiled on every side draws no shadow padding"
692 );
693 assert_eq!(
694 frame_insets(
695 Decorations::Client {
696 tiling: Tiling {
697 top: false,
698 left: true,
699 right: false,
700 bottom: true,
701 }
702 },
703 inset
704 ),
705 Edges {
706 top: inset,
707 right: inset,
708 bottom: px(0.),
709 left: px(0.),
710 }
711 );
712 }
713
714 #[test]
718 fn clamping_keeps_only_the_margin_on_a_tiled_edge() {
719 let popup = Size::new(px(120.), px(30.));
720 let corner = Strategy::Corner {
722 anchor: Anchor::TopRight,
723 position: point(viewport().width - px(10.), px(100.)),
724 };
725 let margin = Edges::all(MARGIN);
726 let inset = px(20.);
727
728 let tiled = resolve(corner, popup, viewport(), margin);
729 assert_eq!(tiled.bounds.right(), viewport().width - px(10.));
730
731 let untiled = resolve(
732 corner,
733 popup,
734 viewport(),
735 margin.map(|margin| *margin + inset),
736 );
737 assert_eq!(untiled.bounds.right(), viewport().width - MARGIN - inset);
738 }
739
740 const WINDOW_MARGIN: Pixels = px(4.);
744
745 fn tooltip_placement(
746 trigger_bounds: Bounds<Pixels>,
747 popup: Size<Pixels>,
748 viewport: Size<Pixels>,
749 margin: Pixels,
750 placement: Option<Placement>,
751 ) -> (Bounds<Pixels>, Placement) {
752 let resolved = resolve(
753 Strategy::Side {
754 trigger_bounds,
755 placement,
756 align: Align::Center,
757 offset: px(0.),
758 },
759 popup,
760 viewport,
761 Edges::all(margin),
762 );
763 (resolved.bounds, resolved.placement.unwrap())
764 }
765
766 fn bounds(x: f32, y: f32, width: f32, height: f32) -> Bounds<Pixels> {
767 Bounds::new(point(px(x), px(y)), Size::new(px(width), px(height)))
768 }
769
770 fn size_px(width: f32, height: f32) -> Size<Pixels> {
771 Size::new(px(width), px(height))
772 }
773
774 #[test]
775 fn prefers_above_when_space_allows() {
776 let trigger = bounds(100., 80., 80., 24.);
777 let position = tooltip_placement(
778 trigger,
779 size_px(120., 30.),
780 size_px(300., 200.),
781 WINDOW_MARGIN,
782 None,
783 );
784 assert_eq!(position.1, Placement::Top);
785 assert_eq!(position.0.origin, point(px(80.), px(50.)));
786 }
787 #[test]
788 fn flips_and_clamps_on_each_axis() {
789 let top = tooltip_placement(
790 bounds(24., 4., 120., 32.),
791 size_px(240., 32.),
792 size_px(520., 260.),
793 WINDOW_MARGIN,
794 None,
795 );
796 assert_eq!(top.1, Placement::Bottom);
797
798 let right = tooltip_placement(
799 bounds(260., 60., 32., 32.),
800 size_px(120., 30.),
801 size_px(300., 200.),
802 WINDOW_MARGIN,
803 Some(Placement::Right),
804 );
805 assert_eq!(right.1, Placement::Left);
806
807 let left_edge = tooltip_placement(
808 bounds(4., 80., 24., 24.),
809 size_px(120., 30.),
810 size_px(300., 200.),
811 WINDOW_MARGIN,
812 None,
813 );
814 assert_eq!(left_edge.0.left(), WINDOW_MARGIN);
815 }
816 #[test]
817 fn places_tooltip_to_the_right() {
818 let trigger = bounds(20., 60., 32., 32.);
819 let position = tooltip_placement(
820 trigger,
821 size_px(120., 30.),
822 size_px(300., 200.),
823 WINDOW_MARGIN,
824 Some(Placement::Right),
825 );
826 assert_eq!(position.1, Placement::Right);
827 assert_eq!(position.0.left(), trigger.right());
828 assert_eq!(position.0.center().y, trigger.center().y);
829 }
830 #[test]
831 fn right_placement_clamps_vertical_edges() {
832 let trigger = bounds(20., 2., 32., 20.);
833 let position = tooltip_placement(
834 trigger,
835 size_px(120., 40.),
836 size_px(300., 200.),
837 WINDOW_MARGIN,
838 Some(Placement::Right),
839 );
840 assert_eq!(position.1, Placement::Right);
841 assert_eq!(position.0.top(), WINDOW_MARGIN);
842 assert_eq!(position.0.left(), trigger.right());
843 }
844 #[test]
845 fn uses_larger_side_when_neither_vertical_side_fits() {
846 let position = tooltip_placement(
847 bounds(120., 20., 40., 20.),
848 size_px(160., 120.),
849 size_px(300., 100.),
850 WINDOW_MARGIN,
851 None,
852 );
853 assert_eq!(position.1, Placement::Bottom);
854 assert_eq!(position.0.top(), WINDOW_MARGIN);
855 assert_eq!(position.0.left(), px(60.));
856 }
857}