1pub mod flow;
12pub mod layout;
13pub mod meters;
14pub mod minimap;
15pub mod notices;
16pub mod scroll;
17pub mod theme;
18pub use layout::{CanvasFit, HUD_REGION_CAPACITY, HudEdge, HudLayoutError, HudRegion, HudRegions};
19
20#[derive(Clone, Copy, Debug, PartialEq)]
21pub struct Rect {
22 pub min: [f32; 2],
23 pub size: [f32; 2],
24}
25impl Rect {
26 pub fn valid(self) -> bool {
27 self.min.into_iter().chain(self.size).all(f32::is_finite)
28 && self.size.into_iter().all(|n| n >= 0.0)
29 && (0..2).all(|i| (self.min[i] + self.size[i]).is_finite())
30 }
31 pub fn contains(self, p: [f32; 2]) -> bool {
33 self.valid()
34 && (0..2).all(|i| {
35 p[i].is_finite() && p[i] >= self.min[i] && p[i] < self.min[i] + self.size[i]
36 })
37 }
38 pub fn intersect(self, other: Self) -> Option<Self> {
39 if !self.valid() || !other.valid() {
40 return None;
41 }
42 let min = std::array::from_fn(|i| self.min[i].max(other.min[i]));
43 let max: [f32; 2] =
44 std::array::from_fn(|i| (self.min[i] + self.size[i]).min(other.min[i] + other.size[i]));
45 (max[0] > min[0] && max[1] > min[1]).then_some(Self {
46 min,
47 size: [max[0] - min[0], max[1] - min[1]],
48 })
49 }
50 pub fn inset(self, insets: [f32; 4]) -> Result<Self, UiError> {
62 if !self.valid() || !insets.into_iter().all(|v| v.is_finite() && v >= 0.) {
63 return Err(UiError::InvalidLayout);
64 }
65 let mut rect = self;
66 for axis in 0..2 {
67 let leading = insets[axis] as f64;
69 let total = leading + insets[axis + 2] as f64;
70 let extent = self.size[axis] as f64;
71 let offset = if total > extent {
72 extent * (leading / total)
73 } else {
74 leading
75 };
76 rect.min[axis] += offset as f32;
77 rect.size[axis] = (extent - total).max(0.) as f32;
78 }
79 Ok(rect)
80 }
81}
82
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub enum Anchor {
87 TopLeft,
88 TopCenter,
89 TopRight,
90 CenterLeft,
91 Center,
92 CenterRight,
93 BottomLeft,
94 BottomCenter,
95 BottomRight,
96}
97impl Anchor {
98 pub fn place(self, parent: Rect, size: [f32; 2]) -> Result<Rect, UiError> {
109 if !parent.valid() || !size.into_iter().all(|v| v.is_finite() && v >= 0.) {
110 return Err(UiError::InvalidLayout);
111 }
112 let align = match self {
113 Self::TopLeft => [0., 0.],
114 Self::TopCenter => [0.5, 0.],
115 Self::TopRight => [1., 0.],
116 Self::CenterLeft => [0., 0.5],
117 Self::Center => [0.5, 0.5],
118 Self::CenterRight => [1., 0.5],
119 Self::BottomLeft => [0., 1.],
120 Self::BottomCenter => [0.5, 1.],
121 Self::BottomRight => [1., 1.],
122 };
123 let size = std::array::from_fn(|i| size[i].min(parent.size[i]));
124 Ok(Rect {
125 min: std::array::from_fn(|i| parent.min[i] + (parent.size[i] - size[i]) * align[i]),
126 size,
127 })
128 }
129}
130#[derive(Clone, Copy, Debug)]
131pub struct Anchors {
132 pub min: [f32; 2],
133 pub max: [f32; 2],
134 pub offset_min: [f32; 2],
135 pub offset_max: [f32; 2],
136}
137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138pub enum UiError {
139 InvalidLayout,
140 DuplicateId,
141 Capacity,
142}
143impl Anchors {
144 pub fn resolve(self, parent: Rect) -> Result<Rect, UiError> {
145 if !parent.valid()
146 || !self
147 .min
148 .into_iter()
149 .chain(self.max)
150 .all(|n| n.is_finite() && (0.0..=1.0).contains(&n))
151 || !self
152 .offset_min
153 .into_iter()
154 .chain(self.offset_max)
155 .all(f32::is_finite)
156 || (0..2).any(|i| self.min[i] > self.max[i])
157 {
158 return Err(UiError::InvalidLayout);
159 }
160 let min = std::array::from_fn(|i| {
161 parent.min[i] + parent.size[i] * self.min[i] + self.offset_min[i]
162 });
163 let max: [f32; 2] = std::array::from_fn(|i| {
164 parent.min[i] + parent.size[i] * self.max[i] + self.offset_max[i]
165 });
166 let rect = Rect {
167 min,
168 size: [max[0] - min[0], max[1] - min[1]],
169 };
170 if rect.valid() {
171 Ok(rect)
172 } else {
173 Err(UiError::InvalidLayout)
174 }
175 }
176}
177pub type WidgetId = u64;
178#[derive(Clone, Copy, Debug)]
179pub struct Widget {
180 pub id: WidgetId,
181 pub rect: Rect,
182 pub clip: Option<Rect>,
183 pub enabled: bool,
184 pub focusable: bool,
185}
186impl Widget {
187 fn available(self) -> bool {
188 self.enabled
189 && self.rect.size.into_iter().all(|n| n > 0.)
190 && self.clip.is_none_or(|c| self.rect.intersect(c).is_some())
191 }
192 fn contains(self, point: [f32; 2]) -> bool {
193 self.rect.contains(point) && self.clip.is_none_or(|clip| clip.contains(point))
194 }
195 fn focus_rect(self) -> Option<Rect> {
196 if !self.available() || !self.focusable {
197 return None;
198 }
199 self.clip
200 .map_or(Some(self.rect), |clip| self.rect.intersect(clip))
201 }
202}
203
204#[derive(Clone, Copy, Debug, PartialEq, Eq)]
207pub enum FocusDirection {
208 Left,
209 Right,
210 Up,
211 Down,
212}
213
214#[derive(Clone, Copy, Debug, PartialEq, Eq)]
216pub enum FocusWrap {
217 Clamp,
219 Wrap,
224}
225
226pub struct UiState {
227 widgets: Vec<Widget>,
228 focus: Option<WidgetId>,
229 pressed: Option<WidgetId>,
230 limit: usize,
231}
232impl Default for UiState {
233 fn default() -> Self {
234 Self::with_capacity(256)
235 }
236}
237impl UiState {
238 pub fn with_capacity(limit: usize) -> Self {
240 let limit = limit.min(4096);
241 Self {
242 widgets: Vec::with_capacity(limit),
243 focus: None,
244 pressed: None,
245 limit,
246 }
247 }
248 pub fn new() -> Self {
249 Self::default()
250 }
251 pub fn begin_frame(&mut self) {
253 self.widgets.clear();
254 }
255 pub fn add(&mut self, widget: Widget) -> Result<(), UiError> {
256 if !widget.rect.valid() || widget.clip.is_some_and(|clip| !clip.valid()) {
257 return Err(UiError::InvalidLayout);
258 }
259 if self.widgets.iter().any(|old| old.id == widget.id) {
260 return Err(UiError::DuplicateId);
261 }
262 if self.widgets.len() == self.limit {
263 return Err(UiError::Capacity);
264 }
265 self.widgets.push(widget);
266 Ok(())
267 }
268 pub fn end_frame(&mut self) {
270 if self.focus.is_some_and(|id| {
271 !self
272 .widgets
273 .iter()
274 .any(|w| w.id == id && w.available() && w.focusable)
275 }) {
276 self.focus = None;
277 }
278 if self
279 .pressed
280 .is_some_and(|id| !self.widgets.iter().any(|w| w.id == id && w.available()))
281 {
282 self.pressed = None;
283 }
284 }
285 pub fn capacity(&self) -> usize {
286 self.limit
287 }
288 pub fn focused(&self) -> Option<WidgetId> {
289 self.focus
290 }
291 pub fn captured(&self) -> Option<WidgetId> {
292 self.pressed
293 }
294 pub fn hit_test(&self, point: [f32; 2]) -> Option<WidgetId> {
295 self.widgets
296 .iter()
297 .rev()
298 .find(|w| w.contains(point))
299 .filter(|w| w.available())
300 .map(|w| w.id)
301 }
302 pub fn pointer_down(&mut self, point: [f32; 2]) -> Option<WidgetId> {
303 self.pressed = self.hit_test(point);
304 self.focus = self
305 .pressed
306 .filter(|id| self.widgets.iter().any(|w| w.id == *id && w.focusable));
307 self.pressed
308 }
309 pub fn pointer_up(&mut self, point: [f32; 2]) -> Option<WidgetId> {
311 let pressed = self.pressed.take();
312 pressed.filter(|id| self.hit_test(point) == Some(*id))
313 }
314 pub fn cancel_pointer(&mut self) {
315 self.pressed = None;
316 }
317 pub fn focus_next(&mut self, reverse: bool) -> Option<WidgetId> {
318 let count = self.widgets.len();
319 if count == 0 {
320 self.focus = None;
321 return None;
322 }
323 let current = self
324 .focus
325 .and_then(|id| self.widgets.iter().position(|w| w.id == id));
326 for step in 1..=count {
327 let index = if reverse {
328 (current.unwrap_or(0) + count - step) % count
329 } else {
330 current.map_or(step - 1, |index| (index + step) % count)
331 };
332 let w = self.widgets[index];
333 if w.available() && w.focusable {
334 self.focus = Some(w.id);
335 return self.focus;
336 }
337 }
338 self.focus = None;
339 None
340 }
341 pub fn focus_direction(
378 &mut self,
379 direction: FocusDirection,
380 wrap: FocusWrap,
381 ) -> Option<WidgetId> {
382 let origin = self.focus.and_then(|id| {
383 self.widgets
384 .iter()
385 .find(|w| w.id == id)
386 .and_then(|w| w.focus_rect())
387 });
388 let Some(origin) = origin else {
389 self.focus = self
390 .widgets
391 .iter()
392 .find_map(|w| w.focus_rect().map(|_| w.id));
393 return self.focus;
394 };
395 let (axis, sign) = match direction {
396 FocusDirection::Left => (0, -1.),
397 FocusDirection::Right => (0, 1.),
398 FocusDirection::Up => (1, -1.),
399 FocusDirection::Down => (1, 1.),
400 };
401 let cross = 1 - axis;
402 let center = |rect: Rect| -> [f64; 2] {
403 std::array::from_fn(|i| rect.min[i] as f64 + rect.size[i] as f64 * 0.5)
404 };
405 let origin_center = center(origin);
406 let mut forward: Option<(bool, f64, WidgetId)> = None;
407 let mut wrapped: Option<(bool, f64, f64, WidgetId)> = None;
408 for widget in &self.widgets {
409 if Some(widget.id) == self.focus {
410 continue;
411 }
412 let Some(rect) = widget.focus_rect() else {
413 continue;
414 };
415 let candidate = center(rect);
416 let along = sign * (candidate[axis] - origin_center[axis]);
417 let across = candidate[cross] - origin_center[cross];
418 let aligned = (rect.min[cross] as f64)
419 < origin.min[cross] as f64 + origin.size[cross] as f64
420 && (origin.min[cross] as f64) < rect.min[cross] as f64 + rect.size[cross] as f64;
421 if along > 0. {
422 let score = (!aligned, along * along + across * across, widget.id);
423 if forward.is_none_or(|best| score < best) {
424 forward = Some(score);
425 }
426 } else if along < 0. && wrap == FocusWrap::Wrap {
427 let score = (!aligned, sign * candidate[axis], across.abs(), widget.id);
428 if wrapped.is_none_or(|best| score < best) {
429 wrapped = Some(score);
430 }
431 }
432 }
433 self.focus = forward
434 .map(|score| score.2)
435 .or_else(|| wrapped.map(|score| score.3))
436 .or(self.focus);
437 self.focus
438 }
439 pub fn activate_focused(&self) -> Option<WidgetId> {
440 self.focus.filter(|id| {
441 self.widgets
442 .iter()
443 .any(|w| w.id == *id && w.available() && w.focusable)
444 })
445 }
446}
447#[cfg(test)]
448mod tests {
449 use super::*;
450 fn widget(id: u64) -> Widget {
451 Widget {
452 id,
453 rect: Rect {
454 min: [0.0; 2],
455 size: [100.0; 2],
456 },
457 clip: None,
458 enabled: true,
459 focusable: true,
460 }
461 }
462 #[test]
463 fn anchors_resolve_stretch_and_center_after_resize() {
464 let parent = Rect {
465 min: [10.0, 20.0],
466 size: [400.0, 200.0],
467 };
468 let center = Anchors {
469 min: [0.5; 2],
470 max: [0.5; 2],
471 offset_min: [-50.0, -20.0],
472 offset_max: [50.0, 20.0],
473 }
474 .resolve(parent)
475 .unwrap();
476 assert_eq!(
477 center,
478 Rect {
479 min: [160.0, 100.0],
480 size: [100.0, 40.0]
481 }
482 );
483 let stretch = Anchors {
484 min: [0.0; 2],
485 max: [1.0; 2],
486 offset_min: [5.0; 2],
487 offset_max: [-5.0; 2],
488 }
489 .resolve(parent)
490 .unwrap();
491 assert_eq!(stretch.size, [390.0, 190.0]);
492 }
493 #[test]
494 fn topmost_clipped_widget_captures_click_and_drag_out_cancels() {
495 let mut ui = UiState::new();
496 ui.add(widget(1)).unwrap();
497 ui.add(Widget {
498 clip: Some(Rect {
499 min: [20.0; 2],
500 size: [20.0; 2],
501 }),
502 ..widget(2)
503 })
504 .unwrap();
505 assert_eq!(ui.hit_test([30.0; 2]), Some(2));
506 assert_eq!(ui.hit_test([10.0; 2]), Some(1));
507 ui.pointer_down([30.0; 2]);
508 assert_eq!(ui.pointer_up([90.0; 2]), None);
509 ui.pointer_down([30.0; 2]);
510 assert_eq!(ui.pointer_up([30.0; 2]), Some(2));
511 }
512 #[test]
513 fn keyboard_focus_skips_disabled_and_clears_removed_nodes() {
514 let mut ui = UiState::new();
515 ui.add(widget(1)).unwrap();
516 ui.add(Widget {
517 enabled: false,
518 ..widget(2)
519 })
520 .unwrap();
521 ui.add(widget(3)).unwrap();
522 assert_eq!(ui.focus_next(false), Some(1));
523 assert_eq!(ui.focus_next(false), Some(3));
524 assert_eq!(ui.focus_next(false), Some(1));
525 assert_eq!(ui.focus_next(true), Some(3));
526 ui.begin_frame();
527 ui.add(widget(1)).unwrap();
528 ui.end_frame();
529 assert_eq!(ui.focused(), None);
530 assert_eq!(ui.add(widget(1)), Err(UiError::DuplicateId));
531 }
532}
533
534#[cfg(test)]
535mod directional_focus_tests {
536 use super::*;
537 use FocusDirection::{Down, Left, Right, Up};
538 use FocusWrap::{Clamp, Wrap};
539
540 fn widget(id: WidgetId, min: [f32; 2]) -> Widget {
541 Widget {
542 id,
543 rect: Rect {
544 min,
545 size: [10.; 2],
546 },
547 clip: None,
548 enabled: true,
549 focusable: true,
550 }
551 }
552
553 fn grid() -> UiState {
554 let mut ui = UiState::with_capacity(9);
555 for id in [9, 5, 2, 7, 1, 6, 3, 8, 4] {
556 ui.add(widget(
557 id,
558 [((id - 1) % 3) as f32 * 20., ((id - 1) / 3) as f32 * 20.],
559 ))
560 .unwrap();
561 }
562 ui.end_frame();
563 ui
564 }
565
566 #[test]
567 fn all_four_directions_follow_geometry_instead_of_submission_order() {
568 let mut ui = grid();
569 assert_eq!(ui.pointer_down([25., 25.]), Some(5));
570 for (direction, expected) in [
571 (Right, 6),
572 (Down, 9),
573 (Left, 8),
574 (Up, 5),
575 (Up, 2),
576 (Left, 1),
577 (Down, 4),
578 (Right, 5),
579 ] {
580 assert_eq!(ui.focus_direction(direction, Clamp), Some(expected));
581 }
582 }
583
584 #[test]
585 fn unavailable_widgets_are_skipped_in_both_directions_and_when_wrapping() {
586 let mut ui = UiState::with_capacity(8);
587 ui.add(widget(1, [0., 0.])).unwrap();
588 ui.add(Widget {
589 enabled: false,
590 ..widget(2, [20., 0.])
591 })
592 .unwrap();
593 ui.add(Widget {
594 focusable: false,
595 ..widget(3, [30., 0.])
596 })
597 .unwrap();
598 for (id, size) in [(4, [0., 10.]), (5, [10., 0.])] {
599 ui.add(Widget {
600 rect: Rect {
601 min: [40., 0.],
602 size,
603 },
604 ..widget(id, [0.; 2])
605 })
606 .unwrap();
607 }
608 for (id, clip_x) in [(6, 100.), (7, 60.)] {
609 ui.add(Widget {
610 clip: Some(Rect {
611 min: [clip_x, 0.],
612 size: [10.; 2],
613 }),
614 ..widget(id, [50., 0.])
615 })
616 .unwrap();
617 }
618 ui.add(widget(8, [80., 0.])).unwrap();
619 ui.end_frame();
620 assert_eq!(ui.focus_next(false), Some(1));
621 assert_eq!(ui.focus_direction(Right, Clamp), Some(8));
622 assert_eq!(ui.focus_direction(Left, Clamp), Some(1));
623 assert_eq!(ui.focus_direction(Left, Wrap), Some(8));
624 assert_eq!(ui.focus_direction(Right, Wrap), Some(1));
625 }
626
627 #[test]
628 fn origin_and_candidate_use_their_clipped_geometry() {
629 let mut ui = UiState::with_capacity(3);
630 for (id, x, width, clip_x) in [(1, 0., 200., 0.), (2, -100., 130., 20.)] {
631 ui.add(Widget {
632 rect: Rect {
633 min: [x, 0.],
634 size: [width, 10.],
635 },
636 clip: Some(Rect {
637 min: [clip_x, 0.],
638 size: [10.; 2],
639 }),
640 ..widget(id, [0.; 2])
641 })
642 .unwrap();
643 }
644 ui.add(widget(3, [40., 0.])).unwrap();
645 assert_eq!(ui.pointer_down([5., 5.]), Some(1));
646 assert_eq!(ui.focus_direction(Right, Clamp), Some(2));
647 assert_eq!(ui.focus_direction(Left, Clamp), Some(1));
648 assert_eq!(ui.focus_direction(Left, Wrap), Some(3));
649 }
650
651 #[test]
652 fn overlapping_rows_rank_first_then_distance_with_diagonal_fallback() {
653 let mut ui = UiState::with_capacity(4);
654 for w in [
655 widget(10, [0., 0.]),
656 widget(1, [10., 10.]), widget(2, [80., 0.]),
658 widget(3, [40., 0.]),
659 ] {
660 ui.add(w).unwrap();
661 }
662 ui.focus_next(false);
663 assert_eq!(ui.focus_direction(Right, Clamp), Some(3));
664
665 ui.begin_frame();
666 for w in [
667 widget(10, [0., 0.]),
668 widget(1, [30., 10.]),
669 widget(9, [10., 20.]),
670 ] {
671 ui.add(w).unwrap();
672 }
673 ui.end_frame();
674 ui.focus_next(false);
675 assert_eq!(ui.focus_direction(Right, Clamp), Some(9));
676 }
677
678 #[test]
679 fn distance_ties_use_ids_even_after_paint_order_changes() {
680 let mut ui = UiState::with_capacity(3);
681 for ids in [[9, 3], [3, 9]] {
682 ui.begin_frame();
683 ui.add(widget(99, [0., 20.])).unwrap();
684 for id in ids {
685 ui.add(widget(id, [20., if id == 3 { 10. } else { 30. }]))
686 .unwrap();
687 }
688 ui.end_frame();
689 ui.pointer_down([5., 25.]);
690 assert_eq!(ui.focus_direction(Right, Clamp), Some(3));
691 }
692 }
693
694 #[test]
695 fn wrap_uses_opposite_edges_in_the_same_row_or_column() {
696 let mut ui = grid();
697 for (point, direction, clamped, wrapped) in [
698 ([45., 25.], Right, 6, 4),
699 ([5., 25.], Left, 4, 6),
700 ([25., 5.], Up, 2, 8),
701 ([25., 45.], Down, 8, 2),
702 ] {
703 ui.pointer_down(point);
704 assert_eq!(ui.focus_direction(direction, Clamp), Some(clamped));
705 assert_eq!(ui.focus_direction(direction, Wrap), Some(wrapped));
706 }
707 }
708
709 #[test]
710 fn wrap_ranks_alignment_extreme_edge_perpendicular_distance_then_id() {
711 let mut ui = UiState::with_capacity(6);
712 for reverse in [false, true] {
713 let mut widgets = [
714 widget(99, [100., 20.]),
715 widget(8, [20., 20.]),
716 widget(3, [0., 18.]),
717 widget(2, [0., 22.]),
718 widget(1, [0., 24.]),
719 widget(7, [-100., 100.]),
720 ];
721 if reverse {
722 widgets.reverse();
723 }
724 ui.begin_frame();
725 for w in widgets {
726 ui.add(w).unwrap();
727 }
728 ui.end_frame();
729 ui.pointer_down([105., 25.]);
730 assert_eq!(ui.focus_direction(Right, Wrap), Some(2));
731 }
732 }
733
734 #[test]
735 fn forward_candidate_prevents_wrap_even_when_it_is_not_aligned() {
736 let mut ui = UiState::with_capacity(3);
737 for w in [
738 widget(1, [0., 0.]),
739 widget(2, [20., 30.]),
740 widget(3, [-30., 0.]),
741 ] {
742 ui.add(w).unwrap();
743 }
744 ui.focus_next(false);
745 assert_eq!(ui.focus_direction(Right, Wrap), Some(2));
746 }
747
748 #[test]
749 fn empty_singleton_equal_centers_and_missing_focus_are_well_defined() {
750 for capacity in [0, 3] {
751 let mut empty = UiState::with_capacity(capacity);
752 for direction in [Left, Right, Up, Down] {
753 for wrap in [Clamp, Wrap] {
754 assert_eq!(empty.focus_direction(direction, wrap), None);
755 }
756 }
757 }
758 let mut ui = UiState::with_capacity(3);
759 ui.add(Widget {
760 enabled: false,
761 ..widget(1, [-20.; 2])
762 })
763 .unwrap();
764 assert_eq!(ui.focus_direction(Down, Wrap), None);
765 ui.add(widget(3, [0.; 2])).unwrap();
766 assert_eq!(ui.focus_direction(Up, Wrap), Some(3));
768 for direction in [Left, Right, Up, Down] {
769 for wrap in [Clamp, Wrap] {
770 assert_eq!(ui.focus_direction(direction, wrap), Some(3));
771 }
772 }
773 ui.add(widget(2, [0.; 2])).unwrap();
774 for direction in [Left, Right, Up, Down] {
775 assert_eq!(ui.focus_direction(direction, Wrap), Some(3));
776 }
777 assert_eq!(ui.focus_next(false), Some(2)); }
779
780 #[test]
781 fn rebuilds_use_new_positions_and_clear_or_recover_unavailable_focus() {
782 let mut ui = UiState::with_capacity(2);
783 ui.add(widget(1, [0.; 2])).unwrap();
784 ui.add(widget(2, [20., 0.])).unwrap();
785 ui.pointer_down([5.; 2]);
786 ui.begin_frame();
787 ui.add(widget(2, [0., 20.])).unwrap();
788 ui.add(widget(1, [0.; 2])).unwrap();
789 ui.end_frame();
790 assert_eq!(ui.focused(), Some(1));
791 assert_eq!(ui.focus_direction(Right, Wrap), Some(1));
792 assert_eq!(ui.focus_direction(Down, Clamp), Some(2));
793 for unavailable in [
794 Widget {
795 enabled: false,
796 ..widget(2, [20., 0.])
797 },
798 Widget {
799 focusable: false,
800 ..widget(2, [20., 0.])
801 },
802 Widget {
803 clip: Some(Rect {
804 min: [100.; 2],
805 size: [10.; 2],
806 }),
807 ..widget(2, [20., 0.])
808 },
809 ] {
810 ui.begin_frame();
811 ui.add(unavailable).unwrap();
812 ui.add(widget(1, [0.; 2])).unwrap();
813 assert_eq!(ui.focus_direction(Left, Clamp), Some(1));
815 ui.end_frame();
816 ui.begin_frame();
817 ui.add(widget(1, [0.; 2])).unwrap();
818 ui.add(widget(2, [20., 0.])).unwrap();
819 ui.end_frame();
820 assert_eq!(ui.focus_direction(Right, Clamp), Some(2));
821 }
822 ui.begin_frame();
823 ui.add(widget(1, [0.; 2])).unwrap();
824 assert_eq!(ui.focus_direction(Up, Wrap), Some(1)); ui.begin_frame();
826 ui.end_frame();
827 assert_eq!(ui.focused(), None);
828 assert_eq!(ui.captured(), None);
829 assert_eq!(ui.focus_direction(Right, Wrap), None);
830 }
831
832 #[test]
833 fn navigation_preserves_capture_tab_order_hit_ownership_and_storage() {
834 let mut ui = UiState::with_capacity(4);
835 let storage = ui.widgets.as_ptr();
836 for w in [
837 widget(1, [0.; 2]),
838 widget(2, [40., 0.]),
839 widget(3, [20., 0.]),
840 ] {
841 ui.add(w).unwrap();
842 }
843 ui.add(Widget {
844 enabled: false,
845 ..widget(4, [40., 0.])
846 })
847 .unwrap();
848 assert_eq!(ui.pointer_down([5.; 2]), Some(1));
849 assert_eq!(ui.focus_direction(Right, Clamp), Some(3));
850 assert_eq!(ui.captured(), Some(1));
851 assert_eq!(ui.activate_focused(), Some(3));
852 assert_eq!(ui.pointer_up([5.; 2]), Some(1));
853 assert_eq!(ui.focus_next(false), Some(1));
854 assert_eq!(ui.focus_next(true), Some(3));
855 assert_eq!(ui.focus_direction(Right, Clamp), Some(2));
856 assert_eq!(ui.hit_test([45., 5.]), None); assert_eq!(ui.activate_focused(), Some(2)); assert_eq!(ui.widgets.as_ptr(), storage);
859 assert_eq!(ui.capacity(), 4);
860 assert_eq!(ui.add(widget(5, [60., 0.])), Err(UiError::Capacity));
861 }
862
863 #[test]
864 fn extreme_and_tiny_finite_coordinates_keep_distance_ordering() {
865 for scale in [f32::MAX / 4., f32::from_bits(1)] {
866 let mut ui = UiState::with_capacity(3);
867 for (id, x) in [(5, -3. * scale), (1, 2. * scale), (9, 0.)] {
868 ui.add(Widget {
869 rect: Rect {
870 min: [x, 0.],
871 size: [scale, 10.],
872 },
873 ..widget(id, [0.; 2])
874 })
875 .unwrap();
876 }
877 ui.focus_next(false);
878 assert_eq!(ui.focus_direction(Right, Clamp), Some(9));
879 assert_eq!(ui.focus_direction(Right, Clamp), Some(1));
880 assert_eq!(ui.focus_direction(Right, Wrap), Some(5));
881 }
882 }
883}
884
885#[derive(Clone, Copy, Debug)]
889pub struct Viewport {
890 bounds: Rect,
891 pixels: Rect,
892 scale: f32,
893}
894impl Viewport {
895 pub fn bounds(self) -> Rect {
896 self.bounds
897 }
898 pub fn pixels(self) -> Rect {
899 self.pixels
900 }
901 pub fn scale(self) -> f32 {
902 self.scale
903 }
904 pub fn responsive(screen: [f32; 2], insets: [f32; 4]) -> Result<Self, UiError> {
919 let pixels = Rect {
920 min: [0.; 2],
921 size: screen,
922 }
923 .inset(insets)?;
924 Ok(Self {
925 bounds: Rect {
926 min: [0.; 2],
927 size: pixels.size,
928 },
929 pixels,
930 scale: 1.,
931 })
932 }
933 pub fn fit(screen: [f32; 2], design: [f32; 2], insets: [f32; 4]) -> Result<Self, UiError> {
935 if !screen
936 .into_iter()
937 .chain(design)
938 .all(|v| v.is_finite() && v > 0.)
939 || !insets.into_iter().all(|v| v.is_finite() && v >= 0.)
940 {
941 return Err(UiError::InvalidLayout);
942 }
943 let available = [
944 screen[0] - insets[0] - insets[2],
945 screen[1] - insets[1] - insets[3],
946 ];
947 let scale = (available[0] / design[0]).min(available[1] / design[1]);
948 if !scale.is_finite() || scale <= 0. {
949 return Err(UiError::InvalidLayout);
950 }
951 let size = [design[0] * scale, design[1] * scale];
952 let viewport = Self {
953 bounds: Rect {
954 min: [0.; 2],
955 size: design,
956 },
957 pixels: Rect {
958 min: [
959 insets[0] + (available[0] - size[0]) * 0.5,
960 insets[1] + (available[1] - size[1]) * 0.5,
961 ],
962 size,
963 },
964 scale,
965 };
966 if !viewport.bounds.valid() || !viewport.pixels.valid() {
967 return Err(UiError::InvalidLayout);
968 }
969 Ok(viewport)
970 }
971 pub fn unproject(self, point: [f32; 2]) -> Option<[f32; 2]> {
972 self.pixels
973 .contains(point)
974 .then(|| std::array::from_fn(|i| (point[i] - self.pixels.min[i]) / self.scale))
975 }
976}
977pub fn slots(
979 parent: Rect,
980 count: usize,
981 gap: f32,
982 vertical: bool,
983) -> Result<impl Iterator<Item = Rect>, UiError> {
984 let axis = usize::from(vertical);
985 if !parent.valid()
986 || count == 0
987 || count > 4096
988 || !gap.is_finite()
989 || gap < 0.
990 || gap * (count - 1) as f32 > parent.size[axis]
991 {
992 return Err(UiError::InvalidLayout);
993 }
994 let extent = (parent.size[axis] - gap * (count - 1) as f32) / count as f32;
995 Ok((0..count).map(move |i| {
996 let mut r = parent;
997 r.min[axis] += (extent + gap) * i as f32;
998 r.size[axis] = extent;
999 r
1000 }))
1001}
1002
1003pub fn hud_slots(
1022 parent: Rect,
1023 count: usize,
1024 min_width: f32,
1025 height: f32,
1026 gap: f32,
1027) -> Result<impl ExactSizeIterator<Item = Rect>, UiError> {
1028 if !parent.valid()
1029 || count > 4096
1030 || ![min_width, height]
1031 .into_iter()
1032 .all(|v| v.is_finite() && v > 0.)
1033 || !gap.is_finite()
1034 || gap < 0.
1035 {
1036 return Err(UiError::InvalidLayout);
1037 }
1038 let gap = gap as f64;
1039 let width = parent.size[0] as f64;
1040 let columns =
1041 (((width + gap) / (min_width as f64 + gap)).floor() as usize).clamp(1, count.max(1));
1042 let cell_width = ((width - gap * (columns - 1) as f64) / columns as f64).max(0.);
1043 Ok((0..count).map(move |index| {
1044 let x = ((cell_width + gap) * (index % columns) as f64).min(width);
1045 let y = ((height as f64 + gap) * (index / columns) as f64).min(parent.size[1] as f64);
1046 Rect {
1047 min: [parent.min[0] + x as f32, parent.min[1] + y as f32],
1048 size: [
1049 cell_width.min(width - x) as f32,
1050 (height as f64).min(parent.size[1] as f64 - y) as f32,
1051 ],
1052 }
1053 }))
1054}
1055
1056#[derive(Clone, Copy, Debug, PartialEq)]
1059pub struct FittedLabel<'a> {
1060 pub prefix: &'a str,
1061 pub suffix: &'static str,
1062 pub width: f32,
1063 pub truncated: bool,
1064}
1065
1066pub fn fit_label(text: &str, width: f32, advance: f32) -> Result<FittedLabel<'_>, UiError> {
1082 if !width.is_finite() || width < 0. || !advance.is_finite() || advance <= 0. {
1083 return Err(UiError::InvalidLayout);
1084 }
1085 let columns = (width as f64 / advance as f64).floor() as usize;
1086 let mut count = 0;
1087 let mut end = 0;
1088 let mut truncated = false;
1089 for (index, ch) in text.char_indices() {
1090 if count == columns || ch == '\n' || ch == '\r' {
1091 truncated = true;
1092 break;
1093 }
1094 count += 1;
1095 end = index + ch.len_utf8();
1096 }
1097 let suffix = if truncated {
1098 let dots = columns.min(3);
1099 let keep = count.min(columns - dots);
1100 end = text[..end].char_indices().nth(keep).map_or(end, |(i, _)| i);
1101 count = keep + dots;
1102 &"..."[..dots]
1103 } else {
1104 ""
1105 };
1106 Ok(FittedLabel {
1107 prefix: &text[..end],
1108 suffix,
1109 width: (count as f64 * advance as f64) as f32,
1110 truncated,
1111 })
1112}
1113
1114#[cfg(test)]
1115mod bounds_tests {
1116 use super::*;
1117 fn widget(id: u64) -> Widget {
1118 Widget {
1119 id,
1120 rect: Rect {
1121 min: [0.; 2],
1122 size: [100.; 2],
1123 },
1124 clip: None,
1125 enabled: true,
1126 focusable: true,
1127 }
1128 }
1129 #[test]
1130 fn disabled_overlay_occludes_and_invisible_widgets_cannot_focus() {
1131 let mut ui = UiState::with_capacity(3);
1132 ui.add(widget(1)).unwrap();
1133 ui.add(Widget {
1134 enabled: false,
1135 ..widget(2)
1136 })
1137 .unwrap();
1138 assert_eq!(ui.hit_test([10.; 2]), None);
1139 ui.add(Widget {
1140 clip: Some(Rect {
1141 min: [200.; 2],
1142 size: [10.; 2],
1143 }),
1144 ..widget(3)
1145 })
1146 .unwrap();
1147 assert_eq!(ui.focus_next(false), Some(1));
1148 assert_eq!(ui.focus_next(false), Some(1));
1149 assert_eq!(ui.add(widget(4)), Err(UiError::Capacity));
1150 }
1151 #[test]
1152 fn viewport_safe_area_letterbox_edges_and_layout_limits() {
1153 let v = Viewport::fit([1000., 700.], [800., 400.], [20., 30., 40., 50.]).unwrap();
1154 assert_eq!(v.scale, 1.175);
1155 assert!((v.pixels.min[0] - 20.).abs() < 0.001 && (v.pixels.min[1] - 105.).abs() < 0.001);
1156 assert_eq!(v.unproject(v.pixels.min), Some([0.; 2]));
1157 assert_eq!(
1158 v.unproject([v.pixels.min[0] + v.pixels.size[0], 200.]),
1159 None
1160 );
1161 assert!(Viewport::fit([100.; 2], [0.; 2], [0.; 4]).is_err());
1162 assert!(Viewport::fit([100.; 2], [1.; 2], [60.; 4]).is_err());
1163 let parent = Rect {
1164 min: [10., 20.],
1165 size: [100., 40.],
1166 };
1167 let row: Vec<_> = slots(parent, 3, 5., false).unwrap().collect();
1168 assert_eq!(
1169 row[2],
1170 Rect {
1171 min: [80., 20.],
1172 size: [30., 40.]
1173 }
1174 );
1175 assert!(slots(parent, 0, 0., false).is_err());
1176 assert!(slots(parent, 3, 51., false).is_err());
1177 }
1178}
1179
1180#[cfg(test)]
1181mod responsive_tests {
1182 use super::*;
1183
1184 #[test]
1185 fn safe_area_preserves_pixel_size_and_handles_collapsed_viewports() {
1186 let viewport = Viewport::responsive([320., 240.], [10., 20., 30., 40.]).unwrap();
1187 assert_eq!(viewport.scale(), 1.);
1188 assert_eq!(
1189 viewport.bounds(),
1190 Rect {
1191 min: [0.; 2],
1192 size: [280., 180.]
1193 }
1194 );
1195 assert_eq!(
1196 viewport.pixels(),
1197 Rect {
1198 min: [10., 20.],
1199 size: [280., 180.]
1200 }
1201 );
1202 assert_eq!(viewport.unproject([10., 20.]), Some([0.; 2]));
1203 assert_eq!(viewport.unproject([289., 199.]), Some([279., 179.]));
1204 for point in [[9., 20.], [10., 19.], [290., 20.], [10., 200.]] {
1205 assert_eq!(viewport.unproject(point), None);
1206 }
1207 let collapsed = Viewport::responsive([100., 60.], [80., 20., 80., 60.]).unwrap();
1208 assert_eq!(
1209 collapsed.pixels(),
1210 Rect {
1211 min: [50., 15.],
1212 size: [0.; 2]
1213 }
1214 );
1215 assert_eq!(collapsed.unproject([50., 15.]), None);
1216 for screen in [[0.; 2], [0., 100.], [100., 0.], [1.; 2]] {
1217 let tiny = Viewport::responsive(screen, [f32::MAX; 4]).unwrap();
1218 assert!(tiny.bounds().valid() && tiny.pixels().valid());
1219 assert_eq!(tiny.bounds().size, [0.; 2]);
1220 assert_eq!(tiny.unproject(tiny.pixels().min), None);
1221 }
1222 for invalid in [-1., f32::NAN, f32::INFINITY] {
1223 assert!(Viewport::responsive([invalid, 100.], [0.; 4]).is_err());
1224 assert!(Viewport::responsive([100.; 2], [invalid, 0., 0., 0.]).is_err());
1225 }
1226 }
1227
1228 #[test]
1229 fn all_anchors_keep_requested_and_oversized_panels_inside_parent() {
1230 let parent = Rect {
1231 min: [10., 20.],
1232 size: [100., 60.],
1233 };
1234 for (anchor, min) in [
1235 (Anchor::TopLeft, [10., 20.]),
1236 (Anchor::TopCenter, [50., 20.]),
1237 (Anchor::TopRight, [90., 20.]),
1238 (Anchor::CenterLeft, [10., 40.]),
1239 (Anchor::Center, [50., 40.]),
1240 (Anchor::CenterRight, [90., 40.]),
1241 (Anchor::BottomLeft, [10., 60.]),
1242 (Anchor::BottomCenter, [50., 60.]),
1243 (Anchor::BottomRight, [90., 60.]),
1244 ] {
1245 assert_eq!(
1246 anchor.place(parent, [20.; 2]).unwrap(),
1247 Rect {
1248 min,
1249 size: [20.; 2]
1250 }
1251 );
1252 assert_eq!(anchor.place(parent, [200.; 2]).unwrap(), parent);
1253 let empty = Rect {
1254 size: [0.; 2],
1255 ..parent
1256 };
1257 assert_eq!(anchor.place(empty, [20.; 2]).unwrap(), empty);
1258 }
1259 assert!(Anchor::Center.place(parent, [f32::NAN, 20.]).is_err());
1260 assert!(Anchor::Center.place(parent, [-1., 20.]).is_err());
1261 }
1262
1263 #[test]
1264 fn hud_cells_reflow_clip_and_reject_invalid_dimensions() {
1265 let parent = Rect {
1266 min: [12.; 2],
1267 size: [300., 96.],
1268 };
1269 let cells: Vec<_> = hud_slots(parent, 5, 140., 44., 8.).unwrap().collect();
1270 assert_eq!(
1271 cells[0],
1272 Rect {
1273 min: [12.; 2],
1274 size: [146., 44.]
1275 }
1276 );
1277 assert_eq!(
1278 cells[1],
1279 Rect {
1280 min: [166., 12.],
1281 size: [146., 44.]
1282 }
1283 );
1284 assert_eq!(
1285 cells[2],
1286 Rect {
1287 min: [12., 64.],
1288 size: [146., 44.]
1289 }
1290 );
1291 assert_eq!(cells[4].size, [146., 0.]);
1292 let narrow = Rect {
1293 size: [100., 30.],
1294 ..parent
1295 };
1296 let mut cells = hud_slots(narrow, 3, 140., 44., 8.).unwrap();
1297 assert_eq!(cells.len(), 3);
1298 assert_eq!(cells.next().unwrap(), narrow);
1299 assert!(cells.all(|r| r.valid() && r.size[1] == 0.));
1300 let zero = Rect {
1301 min: [0.; 2],
1302 size: [0.; 2],
1303 };
1304 assert!(
1305 hud_slots(zero, 3, 140., 44., 8.)
1306 .unwrap()
1307 .all(|r| r == zero)
1308 );
1309 assert_eq!(hud_slots(parent, 0, 140., 44., 8.).unwrap().len(), 0);
1310 assert!(hud_slots(parent, 4097, 140., 44., 8.).is_err());
1311 assert!(hud_slots(parent, 2, 0., 44., 8.).is_err());
1312 assert!(hud_slots(parent, 2, 140., f32::NAN, 8.).is_err());
1313 assert!(hud_slots(parent, 2, 140., 44., -1.).is_err());
1314 assert!(
1315 hud_slots(parent, 2, f32::MAX, f32::MAX, f32::MAX)
1316 .unwrap()
1317 .all(Rect::valid)
1318 );
1319 }
1320
1321 #[test]
1322 fn resized_hud_hit_regions_focus_and_capture_use_visible_geometry() {
1323 let mut ui = UiState::with_capacity(3);
1324 let storage = ui.widgets.as_ptr();
1325 let build = |ui: &mut UiState, width, height| {
1326 let viewport = Viewport::responsive([width, height], [10., 20., 10., 0.]).unwrap();
1327 ui.begin_frame();
1328 for (index, rect) in hud_slots(viewport.bounds(), 3, 100., 44., 8.)
1329 .unwrap()
1330 .enumerate()
1331 {
1332 ui.add(Widget {
1333 id: index as u64 + 1,
1334 rect,
1335 clip: Some(viewport.bounds()),
1336 enabled: true,
1337 focusable: true,
1338 })
1339 .unwrap();
1340 }
1341 ui.end_frame();
1342 viewport
1343 };
1344 let viewport = build(&mut ui, 228., 64.);
1345 assert_eq!(
1346 ui.hit_test(viewport.unproject([10., 20.]).unwrap()),
1347 Some(1)
1348 );
1349 assert_eq!(ui.hit_test([100., 10.]), None); assert_eq!(ui.pointer_down([108., 10.]), Some(2));
1351 assert_eq!(ui.focus_next(false), Some(1)); ui.focus_next(false);
1353 build(&mut ui, 120., 116.); assert_eq!(ui.focused(), Some(2));
1355 assert_eq!(ui.pointer_up([108., 10.]), None); assert_eq!(ui.pointer_down([10., 60.]), Some(2));
1357 assert_eq!(ui.pointer_up([10., 60.]), Some(2));
1358 ui.pointer_down([10., 60.]);
1359 build(&mut ui, 0., 0.);
1360 assert_eq!(ui.focused(), None);
1361 assert_eq!(ui.captured(), None);
1362 assert_eq!(ui.focus_next(false), None);
1363 assert_eq!(ui.hit_test([0.; 2]), None);
1364 assert_eq!(ui.widgets.as_ptr(), storage); }
1366
1367 #[test]
1368 fn adjacent_responsive_cells_have_one_hit_owner() {
1369 let mut ui = UiState::with_capacity(2);
1370 for (index, rect) in hud_slots(
1371 Rect {
1372 min: [0.; 2],
1373 size: [200., 44.],
1374 },
1375 2,
1376 100.,
1377 44.,
1378 0.,
1379 )
1380 .unwrap()
1381 .enumerate()
1382 {
1383 ui.add(Widget {
1384 id: index as u64,
1385 rect,
1386 clip: None,
1387 enabled: true,
1388 focusable: true,
1389 })
1390 .unwrap();
1391 }
1392 assert_eq!(ui.hit_test([99.999, 10.]), Some(0));
1393 assert_eq!(ui.hit_test([100., 10.]), Some(1));
1394 assert_eq!(ui.hit_test([200., 10.]), None);
1395 }
1396
1397 #[test]
1398 fn readable_labels_preserve_utf8_and_never_shrink_or_exceed_width() {
1399 for (text, width, prefix, suffix, truncated) in [
1400 ("é日ABC", 50., "é日ABC", "", false),
1401 ("é日ABC", 40., "é", "...", true),
1402 ("é\nAB", 60., "é", "...", true),
1403 ("A\r\nB", 60., "A", "...", true),
1404 ("LONG", 20., "", "..", true),
1405 ("LONG", 10., "", ".", true),
1406 ("LONG", 9., "", "", true),
1407 ("LONG", 0., "", "", true),
1408 ("", 0., "", "", false),
1409 ] {
1410 let fit = fit_label(text, width, 10.).unwrap();
1411 assert_eq!(
1412 (fit.prefix, fit.suffix, fit.truncated),
1413 (prefix, suffix, truncated)
1414 );
1415 assert_eq!(
1416 fit.width,
1417 (prefix.chars().count() + suffix.len()) as f32 * 10.
1418 );
1419 assert!(fit.width <= width);
1420 assert_eq!(fit.prefix.as_ptr(), text.as_ptr());
1421 }
1422 let long = "é".repeat(100_000);
1423 assert_eq!(fit_label(&long, 50., 10.).unwrap().prefix, "éé");
1424 for invalid in [-1., f32::NAN, f32::INFINITY] {
1425 assert!(fit_label("TEXT", invalid, 10.).is_err());
1426 assert!(fit_label("TEXT", 100., invalid).is_err());
1427 }
1428 assert!(fit_label("TEXT", 100., 0.).is_err());
1429 }
1430}