1use super::text_layout::WrappedText;
79use super::{ButtonStyle, TextStyle, Ui, UiComposition, UiError, UiRect, WidgetId};
80use ferravex_play::ui::theme::{ColorRole, UiTheme};
81use std::fmt::{self, Write};
82
83pub const MAX_INSPECTOR_FIELDS: usize = 16;
85pub const MAX_INSPECTOR_CHOICES: usize = 8;
87pub const MAX_INSPECTOR_BYTES: usize = 8192;
89const MAX_CONTROLS: usize = MAX_INSPECTOR_FIELDS * MAX_INSPECTOR_CHOICES;
90const EMPTY: UiRect = UiRect {
91 min: [0.; 2],
92 size: [0.; 2],
93};
94
95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub enum LimitPolicy {
98 Reject,
100 Clamp,
102}
103
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub enum FieldState<'a> {
107 Enabled,
108 Disabled(&'a str),
109 Unavailable(&'a str),
110 Invalid(&'a str),
111}
112impl<'a> FieldState<'a> {
113 fn message(self) -> (&'static str, &'a str) {
114 match self {
115 Self::Enabled => ("", ""),
116 Self::Disabled(s) => ("X DISABLED: ", s),
117 Self::Unavailable(s) => ("X UNAVAILABLE: ", s),
118 Self::Invalid(s) => ("! INVALID: ", s),
119 }
120 }
121}
122
123#[derive(Clone, Copy, Debug)]
125pub struct InspectorChoice<'a> {
126 pub id: WidgetId,
127 pub label: &'a str,
128 pub enabled: bool,
129}
130
131#[derive(Clone, Copy, Debug)]
172pub enum InspectorControl<'a> {
173 Stepper {
177 value: f32,
178 min: f32,
179 max: f32,
180 step: f32,
181 policy: LimitPolicy,
182 decrease: WidgetId,
183 increase: WidgetId,
184 },
185 Toggle {
187 value: bool,
188 id: WidgetId,
189 on: &'a str,
190 off: &'a str,
191 },
192 Choice {
195 selected: usize,
196 choices: &'a [InspectorChoice<'a>],
197 },
198}
199
200#[derive(Clone, Copy, Debug)]
203pub struct InspectorField<'a> {
204 pub id: WidgetId,
205 pub label: &'a str,
206 pub display: &'a str,
207 pub unit: &'a str,
208 pub state: FieldState<'a>,
209 pub control: InspectorControl<'a>,
210}
211
212#[derive(Clone, Copy, Debug, PartialEq)]
214pub enum FieldValue {
215 Number(f32),
216 Toggle(bool),
217 Choice(usize),
218}
219#[derive(Clone, Copy, Debug, PartialEq)]
221pub struct ValueChange {
222 pub field: WidgetId,
223 pub previous: FieldValue,
224 pub value: FieldValue,
225}
226#[derive(Clone, Copy, Debug, PartialEq, Eq)]
228pub enum InvalidEdit<E> {
229 NumericLimit,
230 NoNumericProgress,
231 Validation(E),
232}
233#[derive(Clone, Copy, Debug, PartialEq)]
236pub enum InspectorOutcome<E> {
237 Idle,
238 Accepted(ValueChange),
239 Invalid {
240 field: WidgetId,
241 reason: InvalidEdit<E>,
242 },
243}
244
245#[derive(Clone, Copy, Debug)]
246struct Row {
247 bounds: UiRect,
248 label: UiRect,
249 value: UiRect,
250 message: UiRect,
251}
252const EMPTY_ROW: Row = Row {
253 bounds: EMPTY,
254 label: EMPTY,
255 value: EMPTY,
256 message: EMPTY,
257};
258#[derive(Clone, Copy, Debug)]
259struct Control {
260 id: WidgetId,
261 rect: UiRect,
262 field: usize,
263 action: usize,
264}
265const EMPTY_CONTROL: Control = Control {
266 id: 0,
267 rect: EMPTY,
268 field: 0,
269 action: 0,
270};
271
272#[derive(Debug)]
276pub struct InspectorLayout<'a> {
277 bounds: UiRect,
278 fields: &'a [InspectorField<'a>],
279 theme: UiTheme,
280 rows: [Row; MAX_INSPECTOR_FIELDS],
281 controls: [Control; MAX_CONTROLS],
282 count: usize,
283}
284
285impl<'a> InspectorLayout<'a> {
286 pub fn new(
290 bounds: UiRect,
291 fields: &'a [InspectorField<'a>],
292 theme: UiTheme,
293 ) -> Result<Self, UiError> {
294 validate_source(fields)?;
295 checked_rect(bounds.min[0], bounds.min[1], bounds.size[0], bounds.size[1])?;
296 let mut result = Self {
297 bounds,
298 fields,
299 theme,
300 rows: [EMPTY_ROW; MAX_INSPECTOR_FIELDS],
301 controls: [EMPTY_CONTROL; MAX_CONTROLS],
302 count: 0,
303 };
304 let spacing = theme.spacing();
305 let inner = bounds.inset([spacing.inset; 4])?;
306 checked_rect(inner.min[0], inner.min[1], inner.size[0], inner.size[1])?;
307 let mut y = inner.min[1];
308 let mut copy = CopyBuffer::new();
309 for (index, field) in fields.iter().enumerate() {
310 let top = y;
311 let label = text_rect(inner, y, field.label, theme.types().label)?;
312 y = label.min[1] + label.size[1] + spacing.compact_gap;
313 value_copy(&mut copy, field)?;
314 let value = text_rect(inner, y, copy.as_str(), theme.types().body)?;
315 y = value.min[1] + value.size[1] + spacing.compact_gap;
316 let controls_top = y;
317 let mut x = inner.min[0];
318 let mut line_y = y;
319 for action in 0..control_count(field.control) {
320 control_copy(&mut copy, field.control, action)?;
321 let mut width = button_width(copy.as_str(), theme.types().body)?;
322 if let InspectorControl::Toggle { value, .. } = field.control {
324 control_copy(&mut copy, toggle_value(field.control, !value), 0)?;
325 width = width.max(button_width(copy.as_str(), theme.types().body)?);
326 }
327 if width > inner.size[0] {
328 return Err(UiError::InvalidLayout);
329 }
330 if x + width > inner.min[0] + inner.size[0] {
331 x = inner.min[0];
332 line_y += spacing.control_height + spacing.compact_gap;
333 }
334 let rect = checked_rect(x, line_y, width, spacing.control_height)?;
335 contained(inner, rect)?;
336 let measured =
337 WrappedText::new(copy.as_str(), rect.size[0] - 16., theme.types().body)?
338 .measure();
339 if measured.line_count != 1 || measured.width > rect.size[0] - 16. {
340 return Err(UiError::InvalidLayout);
341 }
342 result.controls[result.count] = Control {
343 id: control_id(field.control, action),
344 rect,
345 field: index,
346 action,
347 };
348 result.count += 1;
349 x = rect.min[0] + rect.size[0] + spacing.compact_gap;
350 }
351 y = line_y + spacing.control_height;
352 debug_assert!(y > controls_top);
353 let message = if field.state == FieldState::Enabled {
354 EMPTY
355 } else {
356 y += spacing.compact_gap;
357 status_copy(&mut copy, field.state)?;
358 let r = text_rect(inner, y, copy.as_str(), theme.types().body)?;
359 y = r.min[1] + r.size[1];
360 r
361 };
362 let row = checked_rect(inner.min[0], top, inner.size[0], y - top)?;
363 contained(inner, row)?;
364 result.rows[index] = Row {
365 bounds: row,
366 label,
367 value,
368 message,
369 };
370 y += spacing.gap;
371 }
372 Ok(result)
373 }
374
375 pub fn bounds(&self) -> UiRect {
376 self.bounds
377 }
378 pub fn field_rect(&self, id: WidgetId) -> Option<UiRect> {
380 self.fields
381 .iter()
382 .position(|f| f.id == id)
383 .map(|i| self.rows[i].bounds)
384 }
385 pub fn control_rect(&self, id: WidgetId) -> Option<UiRect> {
387 self.controls[..self.count]
388 .iter()
389 .find(|c| c.id == id)
390 .map(|c| c.rect)
391 }
392
393 pub fn finish<E>(
396 &self,
397 ui: &mut Ui,
398 enabled: bool,
399 validate: impl FnOnce(ValueChange) -> Result<(), E>,
400 ) -> Result<InspectorOutcome<E>, UiError> {
401 ui.compose(|group| self.submit(group))?;
402 ui.finish(enabled);
403 Ok(self.resolve(ui, validate))
404 }
405
406 pub fn finish_player<E>(
409 &self,
410 ui: &mut Ui,
411 player: &mut crate::input::PlayerInput,
412 enabled: bool,
413 validate: impl FnOnce(ValueChange) -> Result<(), E>,
414 ) -> Result<InspectorOutcome<E>, UiError> {
415 ui.compose(|group| self.submit(group))?;
416 ui.finish_player(player, enabled);
417 Ok(self.resolve(ui, validate))
418 }
419
420 fn submit(&self, group: &mut UiComposition<'_>) -> Result<(), UiError> {
421 let theme = self.theme;
422 group.push_clip(self.bounds)?;
423 group.panel(self.bounds, theme.color(ColorRole::Surface))?;
424 let mut copy = CopyBuffer::new();
425 for (field, row) in self.fields.iter().zip(self.rows.iter()) {
426 group.text(
427 row.label,
428 field.label,
429 text_style(theme, theme.types().label, ColorRole::MutedText),
430 )?;
431 value_copy(&mut copy, field)?;
432 group.text(
433 row.value,
434 copy.as_str(),
435 text_style(theme, theme.types().body, ColorRole::Text),
436 )?;
437 if field.state != FieldState::Enabled {
438 status_copy(&mut copy, field.state)?;
439 let role = if matches!(field.state, FieldState::Invalid(_)) {
440 ColorRole::Danger
441 } else {
442 ColorRole::DisabledText
443 };
444 group.text(
445 row.message,
446 copy.as_str(),
447 text_style(theme, theme.types().body, role),
448 )?;
449 }
450 }
451 for c in &self.controls[..self.count] {
452 let field = &self.fields[c.field];
453 let enabled = field.state == FieldState::Enabled
454 && match field.control {
455 InspectorControl::Choice { choices, .. } => choices[c.action].enabled,
456 _ => true,
457 };
458 control_copy(&mut copy, field.control, c.action)?;
459 group.button(
460 c.id,
461 c.rect,
462 copy.as_str(),
463 enabled,
464 ButtonStyle {
465 fill: theme.color(ColorRole::Surface),
466 ink: theme.color(if enabled {
467 ColorRole::Text
468 } else {
469 ColorRole::DisabledText
470 }),
471 focus: theme.color(ColorRole::Focus),
472 disabled: theme.color(ColorRole::Surface),
473 size: theme.types().body,
474 },
475 )?;
476 }
477 group.pop_clip()
478 }
479
480 fn resolve<E>(
481 &self,
482 ui: &Ui,
483 validate: impl FnOnce(ValueChange) -> Result<(), E>,
484 ) -> InspectorOutcome<E> {
485 let Some(c) = self.controls[..self.count]
486 .iter()
487 .find(|c| ui.activated(c.id))
488 else {
489 return InspectorOutcome::Idle;
490 };
491 let field = &self.fields[c.field];
492 if field.state != FieldState::Enabled {
493 return InspectorOutcome::Idle;
494 }
495 let candidate = match field.control {
496 InspectorControl::Stepper {
497 value,
498 min,
499 max,
500 step,
501 policy,
502 ..
503 } => {
504 let next = if c.action == 0 {
505 value - step
506 } else {
507 value + step
508 };
509 if !next.is_finite() {
510 return invalid(field.id, InvalidEdit::NumericLimit);
511 }
512 if next == value {
513 return invalid(field.id, InvalidEdit::NoNumericProgress);
514 }
515 let next = match policy {
516 LimitPolicy::Reject if !(min..=max).contains(&next) => {
517 return invalid(field.id, InvalidEdit::NumericLimit);
518 }
519 LimitPolicy::Clamp => next.clamp(min, max),
520 _ => next,
521 };
522 if next == value {
523 return InspectorOutcome::Idle;
524 }
525 (FieldValue::Number(value), FieldValue::Number(next))
526 }
527 InspectorControl::Toggle { value, .. } => {
528 (FieldValue::Toggle(value), FieldValue::Toggle(!value))
529 }
530 InspectorControl::Choice { selected, choices } => {
531 if !choices[c.action].enabled || selected == c.action {
532 return InspectorOutcome::Idle;
533 }
534 (FieldValue::Choice(selected), FieldValue::Choice(c.action))
535 }
536 };
537 let change = ValueChange {
538 field: field.id,
539 previous: candidate.0,
540 value: candidate.1,
541 };
542 match validate(change) {
543 Ok(()) => InspectorOutcome::Accepted(change),
544 Err(error) => invalid(field.id, InvalidEdit::Validation(error)),
545 }
546 }
547}
548
549fn invalid<E>(field: WidgetId, reason: InvalidEdit<E>) -> InspectorOutcome<E> {
550 InspectorOutcome::Invalid { field, reason }
551}
552fn text_style(theme: UiTheme, size: f32, role: ColorRole) -> TextStyle {
553 TextStyle {
554 size,
555 color: theme.color(role),
556 wrap: true,
557 ..TextStyle::default()
558 }
559}
560fn checked_rect(x: f32, y: f32, w: f32, h: f32) -> Result<UiRect, UiError> {
561 let right = x + w;
562 let bottom = y + h;
563 if ![x, y, w, h, right, bottom].iter().all(|n| n.is_finite())
564 || w <= 0.
565 || h <= 0.
566 || right <= x
567 || bottom <= y
568 {
569 return Err(UiError::InvalidLayout);
570 }
571 Ok(UiRect {
572 min: [x, y],
573 size: [right - x, bottom - y],
574 })
575}
576fn contained(parent: UiRect, child: UiRect) -> Result<(), UiError> {
577 if (0..2).any(|a| {
578 child.min[a] < parent.min[a]
579 || child.min[a] + child.size[a] > parent.min[a] + parent.size[a]
580 }) {
581 return Err(UiError::InvalidLayout);
582 }
583 Ok(())
584}
585fn text_rect(inner: UiRect, y: f32, copy: &str, size: f32) -> Result<UiRect, UiError> {
586 let metrics = WrappedText::new(copy, inner.size[0], size)?.measure();
587 if metrics.width > inner.size[0] {
588 return Err(UiError::InvalidLayout);
589 }
590 let rect = checked_rect(inner.min[0], y, inner.size[0], metrics.required_height)?;
591 if rect.size[0] < metrics.width || rect.size[1] < metrics.required_height {
592 return Err(UiError::InvalidLayout);
593 }
594 Ok(rect)
595}
596fn button_width(copy: &str, size: f32) -> Result<f32, UiError> {
597 let width = WrappedText::new(copy, f32::MAX, size)?.measure().width;
598 Ok((width + 16.).ceil().max(44.) + 1.)
599}
600fn control_count(c: InspectorControl<'_>) -> usize {
601 match c {
602 InspectorControl::Stepper { .. } => 2,
603 InspectorControl::Toggle { .. } => 1,
604 InspectorControl::Choice { choices, .. } => choices.len(),
605 }
606}
607fn control_id(c: InspectorControl<'_>, action: usize) -> WidgetId {
608 match c {
609 InspectorControl::Stepper {
610 decrease, increase, ..
611 } => {
612 if action == 0 {
613 decrease
614 } else {
615 increase
616 }
617 }
618 InspectorControl::Toggle { id, .. } => id,
619 InspectorControl::Choice { choices, .. } => choices[action].id,
620 }
621}
622fn toggle_value(c: InspectorControl<'_>, value: bool) -> InspectorControl<'_> {
623 if let InspectorControl::Toggle { id, on, off, .. } = c {
624 InspectorControl::Toggle { value, id, on, off }
625 } else {
626 c
627 }
628}
629fn value_copy(out: &mut CopyBuffer, f: &InspectorField<'_>) -> Result<(), UiError> {
630 out.clear();
631 write!(
632 out,
633 "{}{}{}",
634 f.display,
635 if f.unit.is_empty() { "" } else { " " },
636 f.unit
637 )
638 .map_err(|_| UiError::Capacity)
639}
640fn status_copy(out: &mut CopyBuffer, state: FieldState<'_>) -> Result<(), UiError> {
641 out.clear();
642 let (prefix, message) = state.message();
643 write!(out, "{prefix}{message}").map_err(|_| UiError::Capacity)
644}
645fn control_copy(
646 out: &mut CopyBuffer,
647 c: InspectorControl<'_>,
648 action: usize,
649) -> Result<(), UiError> {
650 out.clear();
651 match c {
652 InspectorControl::Stepper { .. } => out.write_str(if action == 0 { "-" } else { "+" }),
653 InspectorControl::Toggle { value, on, off, .. } => write!(
654 out,
655 "{} {}",
656 if value { "[X]" } else { "[ ]" },
657 if value { on } else { off }
658 ),
659 InspectorControl::Choice { selected, choices } => write!(
660 out,
661 "{} {}",
662 if selected == action { "[X]" } else { "[ ]" },
663 choices[action].label
664 ),
665 }
666 .map_err(|_| UiError::Capacity)
667}
668fn single_line(copy: &str) -> bool {
669 !copy.trim().is_empty()
670 && !copy.chars().any(char::is_control)
671 && !copy.contains(['\u{2028}', '\u{2029}'])
672}
673fn validate_source(fields: &[InspectorField<'_>]) -> Result<(), UiError> {
674 if fields.len() > MAX_INSPECTOR_FIELDS {
675 return Err(UiError::Capacity);
676 }
677 let mut bytes = 0usize;
679 let mut add = |s: &str| -> Result<(), UiError> {
680 bytes = bytes.checked_add(s.len()).ok_or(UiError::Capacity)?;
681 if bytes > MAX_INSPECTOR_BYTES {
682 return Err(UiError::Capacity);
683 }
684 Ok(())
685 };
686 for f in fields {
687 add(f.label)?;
688 add(f.display)?;
689 add(f.unit)?;
690 add(f.state.message().1)?;
691 match f.control {
692 InspectorControl::Choice { choices, .. } => {
693 if choices.len() > MAX_INSPECTOR_CHOICES {
694 return Err(UiError::Capacity);
695 }
696 for choice in choices {
697 add(choice.label)?;
698 }
699 }
700 InspectorControl::Toggle { on, off, .. } => {
701 add(on)?;
702 add(off)?;
703 }
704 _ => {}
705 }
706 }
707 let mut ids = [0; MAX_INSPECTOR_FIELDS + MAX_CONTROLS];
708 let mut count = 0;
709 let mut id = |id| -> Result<(), UiError> {
710 if ids[..count].contains(&id) {
711 return Err(UiError::DuplicateId);
712 }
713 ids[count] = id;
714 count += 1;
715 Ok(())
716 };
717 for f in fields {
718 id(f.id)?;
719 }
720 for f in fields {
721 if f.label.trim().is_empty()
722 || f.display.trim().is_empty()
723 || (f.state != FieldState::Enabled && f.state.message().1.trim().is_empty())
724 {
725 return Err(UiError::InvalidLayout);
726 }
727 match f.control {
728 InspectorControl::Stepper {
729 value,
730 min,
731 max,
732 step,
733 ..
734 } => {
735 if ![min, max, step].iter().all(|n| n.is_finite())
736 || min > max
737 || step <= 0.
738 || (f.state == FieldState::Enabled
739 && (!value.is_finite() || !(min..=max).contains(&value)))
740 {
741 return Err(UiError::InvalidLayout);
742 }
743 }
744 InspectorControl::Toggle { on, off, .. } if !single_line(on) || !single_line(off) => {
745 return Err(UiError::InvalidLayout);
746 }
747 InspectorControl::Choice { selected, choices }
748 if selected >= choices.len() || choices.iter().any(|c| !single_line(c.label)) =>
749 {
750 return Err(UiError::InvalidLayout);
751 }
752 _ => {}
753 }
754 for action in 0..control_count(f.control) {
755 id(control_id(f.control, action))?;
756 }
757 }
758 Ok(())
759}
760struct CopyBuffer {
762 bytes: [u8; MAX_INSPECTOR_BYTES + 32],
763 len: usize,
764}
765impl CopyBuffer {
766 fn new() -> Self {
767 Self {
768 bytes: [0; MAX_INSPECTOR_BYTES + 32],
769 len: 0,
770 }
771 }
772 fn clear(&mut self) {
773 self.len = 0;
774 }
775 fn as_str(&self) -> &str {
776 std::str::from_utf8(&self.bytes[..self.len]).expect("only UTF-8 str writes")
777 }
778}
779impl Write for CopyBuffer {
780 fn write_str(&mut self, text: &str) -> fmt::Result {
781 let end = self.len.checked_add(text.len()).ok_or(fmt::Error)?;
782 self.bytes
783 .get_mut(self.len..end)
784 .ok_or(fmt::Error)?
785 .copy_from_slice(text.as_bytes());
786 self.len = end;
787 Ok(())
788 }
789}
790
791#[cfg(test)]
792mod journey400_285 {
793 use super::*;
794 use crate::input::{
795 ActionKind, Binding, InputCode, PlayerInput, host_frame, touch, touch_event,
796 };
797 use ferravex_play::ui::theme::ThemeMode;
798
799 fn field() -> InspectorField<'static> {
800 InspectorField {
801 id: 1,
802 label: "MASS",
803 display: "1",
804 unit: "kg",
805 state: FieldState::Enabled,
806 control: InspectorControl::Stepper {
807 value: 1.,
808 min: 0.,
809 max: 10.,
810 step: 0.25,
811 policy: LimitPolicy::Reject,
812 decrease: 2,
813 increase: 3,
814 },
815 }
816 }
817 fn viewport() -> super::super::Viewport {
818 super::super::Viewport::responsive([320., 480.], [0.; 4]).unwrap()
819 }
820 fn accept(_: ValueChange) -> Result<(), ()> {
821 Ok(())
822 }
823 fn touch(phase: touch::Phase, rect: UiRect) {
824 touch_event(touch::Event {
825 id: 17,
826 phase,
827 position: crate::Vec2::from_array([rect.min[0] + 2., rect.min[1] + 2.]),
828 });
829 }
830
831 #[test]
832 fn keyboard_focus_skips_disabled_and_held_confirm_does_not_repeat() {
833 let choices = [
834 InspectorChoice {
835 id: 12,
836 label: "BALL",
837 enabled: false,
838 },
839 InspectorChoice {
840 id: 13,
841 label: "CRATE",
842 enabled: true,
843 },
844 InspectorChoice {
845 id: 14,
846 label: "COMPOUND",
847 enabled: true,
848 },
849 ];
850 let fields = [InspectorField {
851 control: InspectorControl::Choice {
852 selected: 0,
853 choices: &choices,
854 },
855 ..field()
856 }];
857 let layout = InspectorLayout::new(
858 viewport().bounds(),
859 &fields,
860 UiTheme::preset(ThemeMode::Normal),
861 )
862 .unwrap();
863 let mut ui = Ui::new();
864 ui.set_auto_focus(false);
865 host_frame(0., 320, 480, || {
867 ui.begin(viewport());
868 layout.finish(&mut ui, true, accept).unwrap();
869 });
870 assert_eq!(ui.focused(), None);
871 crate::key(0xff09, true);
872 crate::key(0xff09, false);
873 crate::key(0xff09, true);
874 crate::key(0xff09, false);
875 crate::key(0xff0d, true);
876 host_frame(0., 320, 480, || {
877 ui.begin(viewport());
878 assert_eq!(
879 layout.finish(&mut ui, true, accept).unwrap(),
880 InspectorOutcome::Accepted(ValueChange {
881 field: 1,
882 previous: FieldValue::Choice(0),
883 value: FieldValue::Choice(2)
884 })
885 );
886 assert_eq!(ui.interaction().keyboard_confirmed, Some(14));
887 });
888 host_frame(0., 320, 480, || {
889 ui.begin(viewport());
890 assert_eq!(
891 layout.finish(&mut ui, true, accept).unwrap(),
892 InspectorOutcome::Idle
893 );
894 });
895 crate::key(0xff0d, false);
896 host_frame(0., 320, 480, || {
897 ui.begin(viewport());
898 assert_eq!(
899 layout.finish(&mut ui, true, accept).unwrap(),
900 InspectorOutcome::Idle
901 );
902 });
903 }
904
905 #[test]
906 fn real_remapped_confirm_leaves_gameplay_tap_for_actual_tick_and_blur_cancels() {
907 let mut player = PlayerInput::transient("journey400-285-remap");
908 player
909 .global_action(
910 "confirm",
911 "Confirm",
912 ActionKind::Button,
913 vec![Binding::digital(InputCode::Key(106))],
914 )
915 .unwrap();
916 player
917 .action(
918 "jump",
919 "Jump",
920 ActionKind::Button,
921 vec![Binding::digital(InputCode::Key(32))],
922 )
923 .unwrap();
924 let fields = [field()];
925 let layout = InspectorLayout::new(
926 viewport().bounds(),
927 &fields,
928 UiTheme::preset(ThemeMode::Normal),
929 )
930 .unwrap();
931 let mut ui = Ui::new();
932 host_frame(0., 320, 480, || {
933 player.sample(true);
934 ui.begin(viewport());
935 layout
936 .finish_player(&mut ui, &mut player, true, accept)
937 .unwrap();
938 });
939 crate::key(106, true);
940 crate::key(106, false);
941 crate::key(32, true);
942 crate::key(32, false);
943 host_frame(0., 320, 480, || {
944 player.sample(true);
945 ui.begin(viewport());
946 assert!(matches!(
947 layout
948 .finish_player(&mut ui, &mut player, true, accept)
949 .unwrap(),
950 InspectorOutcome::Accepted(_)
951 ));
952 assert_eq!(ui.interaction().player_confirmed, Some(2));
953 });
955 host_frame(0., 320, 480, || {
956 player.sample(true);
957 ui.begin(viewport());
958 assert_eq!(
959 layout
960 .finish_player(&mut ui, &mut player, true, accept)
961 .unwrap(),
962 InspectorOutcome::Idle
963 );
964 assert!(player.take_tick(["jump"])[0].pressed);
965 assert!(!player.take_tick(["jump"])[0].pressed);
966 });
967 touch(touch::Phase::Start, layout.control_rect(3).unwrap());
968 host_frame(0., 320, 480, || {
969 ui.begin(viewport());
970 layout.finish(&mut ui, true, accept).unwrap();
971 });
972 crate::focus(false);
973 touch(touch::Phase::End, layout.control_rect(3).unwrap());
974 host_frame(0., 320, 480, || {
975 ui.begin(viewport());
976 assert_eq!(
977 layout.finish(&mut ui, true, accept).unwrap(),
978 InspectorOutcome::Idle
979 );
980 assert!(ui.interaction().input_blocked);
981 });
982 crate::focus(true);
983 host_frame(0., 320, 480, || {
984 ui.begin(viewport());
985 assert_eq!(
986 layout.finish(&mut ui, true, accept).unwrap(),
987 InspectorOutcome::Idle
988 );
989 });
990 }
991
992 #[test]
993 fn failed_late_submission_preserves_prior_capture_focus_paint_and_clips() {
994 let fields = [field()];
995 let layout = InspectorLayout::new(
996 viewport().bounds(),
997 &fields,
998 UiTheme::preset(ThemeMode::Normal),
999 )
1000 .unwrap();
1001 let r = layout.control_rect(3).unwrap();
1002 let mut ui = Ui::new();
1003 ui.set_inspection_enabled(true);
1004 touch(touch::Phase::Start, r);
1005 host_frame(0., 320, 480, || {
1006 ui.begin(viewport());
1007 layout.finish(&mut ui, true, accept).unwrap();
1008 });
1009 assert_eq!(ui.interaction().pointer_capture, Some(3));
1010 touch(touch::Phase::End, r);
1011 host_frame(0., 320, 480, || {
1012 ui.begin(viewport());
1013 ui.button(3, r, "PRIOR", true, ButtonStyle::default())
1014 .unwrap();
1015 assert_eq!(
1016 layout.finish(&mut ui, true, accept),
1017 Err(UiError::DuplicateId)
1018 );
1019 assert_eq!(ui.inspect().unwrap().count(), 1);
1020 assert_eq!(ui.focused(), Some(3));
1021 ui.finish(true);
1022 assert!(ui.activated(3));
1023 ui.paint();
1024 let vertices = crate::read(|s| s.vertices.clone());
1025 crate::edit(|s| s.vertices.clear());
1027 ui.paint();
1028 assert_eq!(vertices, crate::read(|s| s.vertices.clone()));
1029 });
1030 touch(touch::Phase::Start, r);
1032 touch(touch::Phase::End, r);
1033 host_frame(0., 320, 480, || {
1034 ui.begin(viewport());
1035 ui.push_clip(UiRect {
1036 min: [300., 450.],
1037 size: [10., 10.],
1038 })
1039 .unwrap();
1040 assert_eq!(
1041 layout.finish(&mut ui, true, accept).unwrap(),
1042 InspectorOutcome::Idle
1043 );
1044 assert!(!ui.interaction().pointer_consumed);
1045 ui.pop_clip();
1046 });
1047 }
1048}