1use super::*;
2use std::fmt::{self, Write};
3
4fn write_code_label(out: &mut impl Write, code: InputCode) -> fmt::Result {
5 match code {
6 InputCode::Key(32) => out.write_str("Space"),
7 InputCode::Key(0xff1b) => out.write_str("Esc"),
8 InputCode::Key(0xff0d) => out.write_str("Enter"),
9 InputCode::Key(0xff09) => out.write_str("Tab"),
10 InputCode::Key(0xff08) => out.write_str("Backspace"),
11 InputCode::Key(0xffff) => out.write_str("Delete"),
12 InputCode::Key(0xff51) => out.write_str("Left"),
13 InputCode::Key(0xff53) => out.write_str("Right"),
14 InputCode::Key(0xff52) => out.write_str("Up"),
15 InputCode::Key(0xff54) => out.write_str("Down"),
16 InputCode::Key(0xff50) => out.write_str("Home"),
17 InputCode::Key(0xff57) => out.write_str("End"),
18 InputCode::Key(0xff55) => out.write_str("PageUp"),
19 InputCode::Key(0xff56) => out.write_str("PageDown"),
20 InputCode::Key(0xff63) => out.write_str("Insert"),
21 InputCode::Key(0xffe1) => out.write_str("Left Shift"),
22 InputCode::Key(0xffe2) => out.write_str("Right Shift"),
23 InputCode::Key(0xffe3) => out.write_str("Left Ctrl"),
24 InputCode::Key(0xffe4) => out.write_str("Right Ctrl"),
25 InputCode::Key(0xffe9) => out.write_str("Left Alt"),
26 InputCode::Key(0xffea) => out.write_str("Right Alt"),
27 InputCode::Key(n @ 0xffbe..=0xffc9) => write!(out, "F{}", n - 0xffbe + 1),
28 InputCode::Key(n) if (32..=126).contains(&n) => {
29 out.write_char((n as u8 as char).to_ascii_uppercase())
30 }
31 InputCode::Key(n) => write!(out, "Key {n}"),
32 InputCode::Mouse(n) => write!(out, "Mouse {n}"),
33 InputCode::MouseDelta(0) => out.write_str("Mouse X"),
34 InputCode::MouseDelta(_) => out.write_str("Mouse Y"),
35 InputCode::Wheel(n) => write!(out, "Wheel {n}"),
36 InputCode::PadButton(n) => write!(out, "Pad {n}"),
37 InputCode::PadAxis(n) => write!(out, "Pad axis {n}"),
38 InputCode::Touch(n) => write!(out, "Touch {n}"),
39 InputCode::TouchDelta(n) => write!(out, "Touch look {n}"),
40 }
41}
42
43struct BindingLabel(Binding);
44impl fmt::Display for BindingLabel {
45 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46 write_code_label(f, self.0.code)?;
47 if self.0.scale != 1. {
48 write!(f, " x{}", self.0.scale)?;
49 }
50 Ok(())
51 }
52}
53
54struct HintWriter<'a> {
57 buffer: Option<&'a mut [u8]>,
58 len: usize,
59}
60impl Write for HintWriter<'_> {
61 fn write_str(&mut self, text: &str) -> fmt::Result {
62 let end = self.len.checked_add(text.len()).ok_or(fmt::Error)?;
63 if let Some(buffer) = &mut self.buffer {
64 buffer
65 .get_mut(self.len..end)
66 .ok_or(fmt::Error)?
67 .copy_from_slice(text.as_bytes());
68 }
69 self.len = end;
70 Ok(())
71 }
72}
73
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
88pub struct VisibleTouchLabel<'a> {
89 pub slot: usize,
90 pub code: InputCode,
91 pub label: &'a str,
92}
93
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
103pub enum VisibleHintError {
104 Hint(HintError),
105 Capacity,
107 InvalidLabel {
110 index: usize,
111 },
112}
113impl fmt::Display for VisibleHintError {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 match self {
116 Self::Hint(error) => error.fmt(f),
117 Self::Capacity => f.write_str("visible hints exceed 32 labels"),
118 Self::InvalidLabel { index } => write!(f, "invalid visible touch label {index}"),
119 }
120 }
121}
122impl std::error::Error for VisibleHintError {}
123
124fn touch_role(output: touch::Output, code: InputCode) -> Option<&'static str> {
128 match (output, code) {
129 (touch::Output::Button(a), InputCode::Touch(b)) if a == b => Some(""),
130 (touch::Output::Stick { x, .. }, InputCode::Touch(b)) if x == b => Some("stick X"),
131 (touch::Output::Stick { y, .. }, InputCode::Touch(b)) if y == b => Some("stick Y"),
132 (touch::Output::Look { x, .. }, InputCode::TouchDelta(b)) if x == b => Some("gesture X"),
133 (touch::Output::Look { y, .. }, InputCode::TouchDelta(b)) if y == b => Some("gesture Y"),
134 _ => None,
135 }
136}
137
138fn write_visible_hint(
139 out: &mut impl Write,
140 bindings: &[Binding],
141 device: Option<HintDevice>,
142 labels: &[VisibleTouchLabel<'_>],
143 controls: &[touch::Control],
144) -> fmt::Result {
145 let mut empty = true;
146 for binding in bindings
147 .iter()
148 .filter(|b| b.scale != 0. && device.is_none_or(|d| d == HintDevice::for_code(b.code)))
149 {
150 let mut named = false;
151 for label in labels.iter().filter(|label| label.code == binding.code) {
152 if !empty {
153 out.write_str(" / ")?;
154 }
155 out.write_str(label.label)?;
156 let role =
157 touch_role(controls[label.slot].output, label.code).expect("validated label");
158 if !role.is_empty() {
159 write!(out, " ({role})")?;
160 }
161 if binding.scale != 1. {
162 write!(out, " x{}", binding.scale)?;
163 }
164 named = true;
165 empty = false;
166 }
167 if !named {
168 if !empty {
169 out.write_str(" / ")?;
170 }
171 write!(out, "{}", BindingLabel(*binding))?;
172 if HintDevice::for_code(binding.code) == HintDevice::Touch {
173 out.write_str(if binding.code.is_delta() {
174 " (gesture; not visible)"
175 } else {
176 " (not visible)"
177 })?;
178 }
179 empty = false;
180 }
181 }
182 if empty {
183 out.write_str("Unbound")?;
184 }
185 Ok(())
186}
187
188fn write_hint(
189 out: &mut impl Write,
190 bindings: &[Binding],
191 device: Option<HintDevice>,
192) -> fmt::Result {
193 let mut empty = true;
194 for binding in bindings
195 .iter()
196 .filter(|b| b.scale != 0. && device.is_none_or(|d| d == HintDevice::for_code(b.code)))
197 {
198 if !empty {
199 out.write_str(" / ")?;
200 }
201 write!(out, "{}", BindingLabel(*binding))?;
202 empty = false;
203 }
204 if empty {
205 out.write_str("Unbound")?;
206 }
207 Ok(())
208}
209
210impl PlayerInput {
211 pub fn format_visible_hint<'a>(
223 &self,
224 name: &str,
225 labels: &[VisibleTouchLabel<'_>],
226 buffer: &'a mut [u8],
227 ) -> Result<&'a str, VisibleHintError> {
228 self.format_visible_hint_for(name, Some(self.current_device()), labels, buffer)
229 }
230
231 pub fn format_visible_hint_for<'a>(
291 &self,
292 name: &str,
293 device: Option<HintDevice>,
294 labels: &[VisibleTouchLabel<'_>],
295 buffer: &'a mut [u8],
296 ) -> Result<&'a str, VisibleHintError> {
297 let handle =
298 self.map
299 .action_handle(name)
300 .ok_or(VisibleHintError::Hint(HintError::Input(
301 InputError::InvalidHandle,
302 )))?;
303 let descriptor = self
304 .map
305 .action_descriptor(handle)
306 .map_err(|error| VisibleHintError::Hint(HintError::Input(error)))?;
307 if labels.len() > touch::MAX_TOUCH_CONTROLS * 2 {
308 return Err(VisibleHintError::Capacity);
309 }
310 let controls = self.surface.controls();
311 for (index, label) in labels.iter().enumerate() {
312 if label.label.is_empty()
313 || label.label.len() > 96
314 || label.label.chars().any(char::is_control)
315 || controls
316 .get(label.slot)
317 .is_none_or(|control| touch_role(control.output, label.code).is_none())
318 || labels[..index]
319 .iter()
320 .any(|prior| (prior.slot, prior.code) == (label.slot, label.code))
321 {
322 return Err(VisibleHintError::InvalidLabel { index });
323 }
324 }
325 let mut measure = HintWriter {
326 buffer: None,
327 len: 0,
328 };
329 write_visible_hint(&mut measure, descriptor.bindings, device, labels, controls)
330 .expect("bounded visible hint length");
331 let required = measure.len;
332 if buffer.len() < required {
333 return Err(VisibleHintError::Hint(HintError::BufferTooSmall {
334 required,
335 }));
336 }
337 write_visible_hint(
338 &mut HintWriter {
339 buffer: Some(&mut buffer[..required]),
340 len: 0,
341 },
342 descriptor.bindings,
343 device,
344 labels,
345 controls,
346 )
347 .expect("measured visible hint capacity");
348 Ok(std::str::from_utf8(&buffer[..required]).expect("UTF-8 visible hint labels"))
349 }
350
351 pub fn format_hint<'a>(&self, name: &str, buffer: &'a mut [u8]) -> Result<&'a str, HintError> {
367 self.format_hint_for(name, Some(self.current_device()), buffer)
368 }
369
370 pub fn format_hint_for<'a>(
405 &self,
406 name: &str,
407 device: Option<HintDevice>,
408 buffer: &'a mut [u8],
409 ) -> Result<&'a str, HintError> {
410 let handle = self
411 .map
412 .action_handle(name)
413 .ok_or(HintError::Input(InputError::InvalidHandle))?;
414 let descriptor = self
415 .map
416 .action_descriptor(handle)
417 .map_err(HintError::Input)?;
418 let mut measure = HintWriter {
419 buffer: None,
420 len: 0,
421 };
422 write_hint(&mut measure, descriptor.bindings, device).expect("bounded hint length");
423 let required = measure.len;
424 if buffer.len() < required {
425 return Err(HintError::BufferTooSmall { required });
426 }
427 write_hint(
428 &mut HintWriter {
429 buffer: Some(&mut buffer[..required]),
430 len: 0,
431 },
432 descriptor.bindings,
433 device,
434 )
435 .expect("measured hint capacity");
436 Ok(std::str::from_utf8(&buffer[..required]).expect("ASCII hint labels"))
437 }
438}
439
440fn fit(text: &str, width: f32, size: u16) -> String {
441 if measure_text(text, None, size, 1.).width <= width {
442 return text.into();
443 }
444 let mut text = text.to_string();
445 while !text.is_empty() && measure_text(&(text.clone() + "..."), None, size, 1.).width > width {
446 text.pop();
447 }
448 text + "..."
449}
450
451const EDITOR_LINE: f32 = 16.;
454fn editor_lines(text: &str, width: f32) -> crate::ui::text_layout::WrappedLines<'_> {
455 crate::ui::text_layout::WrappedText::new(text, width, 14.)
456 .expect("bounded editor width")
457 .lines()
458}
459fn editor_copy(text: &str, rect: Rect, first: usize, lines: usize, color: Color) {
460 for (line, span) in editor_lines(text, rect.w)
461 .skip(first)
462 .take(lines)
463 .enumerate()
464 {
465 draw_text(
466 span.text,
467 rect.x,
468 rect.y + 14. + line as f32 * EDITOR_LINE,
469 14.,
470 color,
471 );
472 }
473}
474
475#[derive(Clone, Copy, Debug)]
476struct EditorGeometry {
477 panel: Rect,
478 narrow: bool,
479 body_y: f32,
480 footer_y: f32,
481 capture_y: f32,
482 detail_lines: usize,
483 per_page: usize,
484}
485impl EditorGeometry {
486 fn new(w: f32, h: f32) -> Self {
487 let width = (w - 24.).clamp(280., 760.);
488 let height = (h - 24.).clamp(300., 620.);
489 let x = (w - width) * 0.5;
490 let y = (h - height) * 0.5;
491 let narrow = width < 530.;
492 Self {
493 panel: Rect::new(x, y, width, height),
494 narrow,
495 body_y: y + 143.,
496 footer_y: y + height - 90.,
497 capture_y: y + height - 140.,
498 detail_lines: (((height - 287.) / EDITOR_LINE).floor() as usize).max(1),
499 per_page: (((height - 245.) / if narrow { 76. } else { 43. }).floor() as usize)
500 .clamp(1, 8),
501 }
502 }
503}
504
505struct BindingDetail {
506 action: usize,
507 first_line: usize,
508 text: String,
509 pages: usize,
510}
511impl PlayerInput {
512 fn binding_detail(&self, width: f32, lines: usize) -> BindingDetail {
516 let mut detail = BindingDetail {
517 action: 0,
518 first_line: 0,
519 text: String::new(),
520 pages: 0,
521 };
522 for (action, info) in self.actions.iter().enumerate() {
523 let mut text = format!("Action: {}\nBindings: ", info.label);
524 write_hint(
525 &mut text,
526 self.map.bindings(info.id).expect("registered action"),
527 None,
528 )
529 .expect("String writer");
530 let pages = editor_lines(&text, width).count().div_ceil(lines).max(1);
531 if self.page >= detail.pages {
532 detail.action = action;
533 detail.first_line = (self.page - detail.pages).min(pages - 1) * lines;
534 detail.text = text;
535 }
536 detail.pages += pages;
537 }
538 detail.pages = detail.pages.max(1);
539 detail
540 }
541
542 fn ui_button(&mut self, rect: Rect, label: &str, selected: bool, index: usize) -> bool {
543 let hovered = rect.contains(self.pointer);
544 let keyboard = self.ui_focus == index;
545 let fill = if selected {
546 Color::from_rgba(60, 104, 105, 255)
547 } else if hovered || keyboard {
548 Color::from_rgba(53, 72, 80, 255)
549 } else {
550 Color::from_rgba(30, 44, 52, 255)
551 };
552 draw_rectangle(rect.x, rect.y, rect.w, rect.h, fill);
553 if keyboard {
554 draw_rectangle_lines(
555 rect.x,
556 rect.y,
557 rect.w,
558 rect.h,
559 1.,
560 Color::from_rgba(141, 196, 187, 255),
561 );
562 }
563 let label = fit(label, (rect.w - 8.).max(0.), 14);
564 let width = measure_text(&label, None, 14, 1.).width;
565 draw_text(
566 &label,
567 rect.x + (rect.w - width) * 0.5,
568 rect.y + rect.h * 0.5 + 5.,
569 14.,
570 WHITE,
571 );
572 !self.ui_block
573 && ((self.ui_click && hovered)
574 || self.ui_taps[..self.ui_tap_len]
575 .iter()
576 .any(|p| rect.contains(*p))
577 || keyboard && self.ui_accept)
578 }
579 pub fn draw_settings(&mut self) {
582 self.draw_settings_impl(true);
583 }
584
585 pub fn draw_controls(&mut self) {
605 self.draw_settings_impl(false);
606 }
607
608 fn draw_settings_impl(&mut self, show_pause_hint: bool) {
609 if self.external_details {
610 return;
611 }
612 if !self.open {
613 if self.touch_seen && self.enabled && !self.paused && self.touch_customized() {
614 self.draw_custom_touch();
615 }
616 if self.paused && show_pause_hint {
617 crate::set_default_camera();
618 let w = screen_width();
619 let h = screen_height();
620 let label = "PAUSED";
621 let width = measure_text(label, None, 16, 1.).width;
622 let badge_width = (w - 24.).clamp(1., 160.);
623 draw_rectangle(
624 (w - badge_width) * 0.5,
625 h * 0.5 - 20.,
626 badge_width,
627 40.,
628 Color::new(0.02, 0.04, 0.05, 0.9),
629 );
630 draw_text(label, (w - width) * 0.5, h * 0.5 + 6., 16., WHITE);
631 }
632 return;
633 }
634 crate::set_default_camera();
635 crate::ui::warm_up_font_sizes(&[14, 16, 20]);
636 let w = screen_width();
637 let h = screen_height();
638 let geometry = EditorGeometry::new(w, h);
639 let Rect {
640 x,
641 y,
642 w: width,
643 h: height,
644 } = geometry.panel;
645 let narrow = geometry.narrow;
646 draw_rectangle(0., 0., w, h, Color::new(0.02, 0.04, 0.05, 0.88));
647 draw_rectangle(x, y, width, height, Color::from_rgba(18, 29, 37, 255));
648 draw_rectangle_lines(x, y, width, height, 1., Color::from_rgba(70, 101, 108, 255));
649 draw_text("CONTROLS", x + 18., y + 31., 20., WHITE);
650 let per_page = geometry.per_page;
651 let count = if self.devices_tab {
652 20 + self.raw_touch.len() * 3
653 } else {
654 self.actions.len()
655 };
656 let detail = (narrow && !self.devices_tab)
657 .then(|| self.binding_detail(width - 36., geometry.detail_lines));
658 let pages = detail
659 .as_ref()
660 .map_or_else(|| count.div_ceil(per_page).max(1), |d| d.pages);
661 self.page = self.page.min(pages - 1);
662 let start = detail.as_ref().map_or(self.page * per_page, |d| d.action);
663 let end = if detail.is_some() {
664 (start + 1).min(count)
665 } else {
666 (start + per_page).min(count)
667 };
668 let footer = 3 + (end - start) * 2;
669 let mut focusable = vec![0, 1, 2];
670 for (row, i) in (start..end).enumerate() {
671 focusable.push(3 + row * 2);
672 if self.devices_tab || self.actions[i].kind != ActionKind::Delta {
673 focusable.push(4 + row * 2);
674 }
675 }
676 focusable.extend([footer, footer + 1, footer + 2]);
677 let current = focusable
678 .iter()
679 .position(|&n| n == self.ui_focus)
680 .unwrap_or(0);
681 self.ui_focus = focusable[if self.ui_down {
682 (current + 1) % focusable.len()
683 } else if self.ui_up {
684 (current + focusable.len() - 1) % focusable.len()
685 } else {
686 current
687 }];
688 if self.ui_button(
689 Rect::new(x + width - 94., y + 13., 76., 27.),
690 "Done",
691 false,
692 0,
693 ) {
694 self.set_controls_open(false);
695 return;
696 }
697 if self.ui_button(
698 Rect::new(x + 18., y + 47., 92., 28.),
699 "Bindings",
700 !self.devices_tab,
701 1,
702 ) {
703 self.devices_tab = false;
704 self.page = 0;
705 self.capture = None;
706 return;
707 }
708 if self.ui_button(
709 Rect::new(x + 120., y + 47., 92., 28.),
710 "Devices",
711 self.devices_tab,
712 2,
713 ) {
714 self.devices_tab = true;
715 self.page = 0;
716 self.capture = None;
717 return;
718 }
719 let hint = if self.capture.is_some() {
720 "Press key/button or move axis right/down. Esc cancels."
721 } else {
722 "Changes save on this device. F2 / Esc closes."
723 };
724 editor_copy(
725 hint,
726 Rect::new(x + 18., y + 87., width - 36., 48.),
727 0,
728 3,
729 Color::from_rgba(161, 185, 189, 255),
730 );
731 let mut settings = self.settings;
732 let mut touch = self.touch_settings;
733 let mut preferences = self.preferences();
734 if self.devices_tab {
735 for (row, i) in (start..end).enumerate() {
736 let yy = geometry.body_y + row as f32 * if narrow { 76. } else { 43. };
737 let (label, value) = match i {
738 0 => ("Mouse look", format!("{:.2}", settings.mouse_sensitivity)),
739 1 => ("Touch look", format!("{:.4}", settings.touch_sensitivity)),
740 2 => ("Pad look X", format!("{:.2} rad/s", settings.pad_look.x)),
741 3 => ("Pad look Y", format!("{:.2} rad/s", settings.pad_look.y)),
742 4 => ("Dead zone", format!("{:.2}", settings.pad_deadzone)),
743 5 => ("Stick curve", format!("{:.2}", settings.pad_curve)),
744 6 => (
745 "Invert Y",
746 if settings.invert_y {
747 "On".into()
748 } else {
749 "Off".into()
750 },
751 ),
752 7 => (
753 "Controller",
754 format!(
755 "{} {}",
756 settings.gamepad + 1,
757 if gamepads()[settings.gamepad as usize].connected {
758 "connected"
759 } else {
760 "offline"
761 }
762 ),
763 ),
764 8 => (
765 "Master volume",
766 format!("{}%", (preferences.master * 100.).round() as u32),
767 ),
768 9..=12 => (
769 [
770 "Effects volume",
771 "Ambience volume",
772 "Music volume",
773 "UI volume",
774 ][i - 9],
775 format!("{}%", (preferences.buses[i - 9] * 100.).round() as u32),
776 ),
777 13 => (
778 "Sound",
779 if preferences.muted {
780 "Muted".into()
781 } else {
782 "On".into()
783 },
784 ),
785 14 => (
786 "Graphics quality",
787 match preferences.quality {
788 None => "Game default",
789 Some(0) => "Low",
790 Some(1) => "Medium",
791 _ => "High",
792 }
793 .into(),
794 ),
795 15 => (
796 "Visual style",
797 crate::Look::from_index(preferences.look as u32)
798 .unwrap_or_default()
799 .name()
800 .into(),
801 ),
802 16 => (
803 "Touch handedness",
804 if touch.mirrored {
805 "Mirrored"
806 } else {
807 "Authored"
808 }
809 .into(),
810 ),
811 17 => ("Touch scale", format!("{:.0}%", touch.scale * 100.)),
812 18 => ("Touch opacity", format!("{:.0}%", touch.opacity * 100.)),
813 19 => (
814 "Adaptive performance",
815 if preferences.adaptive { "On" } else { "Off" }.into(),
816 ),
817 _ => {
818 let slot = (i - 20) / 3;
819 let axis = (i - 20) % 3;
820 (
821 ["Touch X", "Touch Y", "Touch size"][axis],
822 format!(
823 "{}: {:.0}%",
824 slot + 1,
825 match axis {
826 0 => touch.edits[slot].offset.x,
827 1 => touch.edits[slot].offset.y,
828 _ => touch.edits[slot].scale,
829 } * 100.
830 ),
831 )
832 }
833 };
834 editor_copy(
835 label,
836 Rect::new(x + 18., yy, width - if narrow { 36. } else { 192. }, 16.),
837 0,
838 1,
839 WHITE,
840 );
841 editor_copy(
842 &value,
843 Rect::new(x + 18., yy + 18., width - 192., 32.),
844 0,
845 2,
846 Color::from_rgba(161, 185, 189, 255),
847 );
848 let button_y = yy + if narrow { 32. } else { 0. };
849 let minus = self.ui_button(
850 Rect::new(x + width - 158., button_y, 62., 31.),
851 "-",
852 false,
853 3 + row * 2,
854 );
855 let plus = self.ui_button(
856 Rect::new(x + width - 86., button_y, 62., 31.),
857 "+",
858 false,
859 4 + row * 2,
860 );
861 if minus || plus {
862 let d = if plus { 1. } else { -1. };
863 match i {
864 0 => {
865 settings.mouse_sensitivity = (settings.mouse_sensitivity
866 * if plus { 1.15 } else { 1. / 1.15 })
867 .clamp(0.01, 20.)
868 }
869 1 => {
870 settings.touch_sensitivity = (settings.touch_sensitivity
871 * if plus { 1.15 } else { 1. / 1.15 })
872 .clamp(0.00005, 0.1)
873 }
874 2 => settings.pad_look.x = (settings.pad_look.x + d * 0.25).clamp(0., 20.),
875 3 => settings.pad_look.y = (settings.pad_look.y + d * 0.25).clamp(0., 20.),
876 4 => {
877 settings.pad_deadzone =
878 (settings.pad_deadzone + d * 0.02).clamp(0., 0.95)
879 }
880 5 => settings.pad_curve = (settings.pad_curve + d * 0.25).clamp(0.25, 4.),
881 6 => settings.invert_y = !settings.invert_y,
882 7 => {
883 settings.gamepad = if plus {
884 (settings.gamepad + 1) % 4
885 } else {
886 (settings.gamepad + 3) % 4
887 }
888 }
889 8 => preferences.master = (preferences.master + d * 0.05).clamp(0., 1.),
890 9..=12 => {
891 preferences.buses[i - 9] =
892 (preferences.buses[i - 9] + d * 0.05).clamp(0., 1.)
893 }
894 13 => preferences.muted = !preferences.muted,
895 14 => {
896 let value = preferences.quality.map_or(0, |q| q + 1);
897 let next = if plus {
898 (value + 1) % 4
899 } else {
900 (value + 3) % 4
901 };
902 preferences.quality = next.checked_sub(1);
903 }
904 15 => preferences.look = (preferences.look + if plus { 1 } else { 3 }) % 4,
905 16 => touch.mirrored = !touch.mirrored,
906 17 => touch.scale = (touch.scale + d * 0.1).clamp(0.6, 1.8),
907 18 => touch.opacity = (touch.opacity + d * 0.1).clamp(0.2, 1.),
908 19 => preferences.adaptive = !preferences.adaptive,
909 _ => {
910 let slot = (i - 20) / 3;
911 match (i - 20) % 3 {
912 0 => {
913 touch.edits[slot].offset.x =
914 (touch.edits[slot].offset.x + d * 0.025).clamp(-0.4, 0.4)
915 }
916 1 => {
917 touch.edits[slot].offset.y =
918 (touch.edits[slot].offset.y + d * 0.025).clamp(-0.4, 0.4)
919 }
920 _ => {
921 touch.edits[slot].scale =
922 (touch.edits[slot].scale + d * 0.1).clamp(0.5, 2.)
923 }
924 }
925 }
926 }
927 }
928 }
929 } else if let Some(detail) = detail.as_ref().filter(|_| start < end) {
930 editor_copy(
931 &detail.text,
932 Rect::new(x + 18., geometry.body_y, width - 36., 0.),
933 detail.first_line,
934 geometry.detail_lines,
935 WHITE,
936 );
937 let info = &self.actions[detail.action];
938 let name = info.name.clone();
939 let kind = info.kind;
940 if self.ui_button(
941 Rect::new(x + 18., geometry.capture_y, 122., 31.),
942 "Bind key",
943 self.capture.is_some_and(|c| {
944 c.action == detail.action && c.device == CaptureDevice::KeyboardMouse
945 }),
946 3,
947 ) {
948 let _ = self.begin_capture(&name, CaptureDevice::KeyboardMouse);
949 }
950 if kind != ActionKind::Delta
951 && self.ui_button(
952 Rect::new(x + width - 140., geometry.capture_y, 122., 31.),
953 "Bind pad",
954 self.capture.is_some_and(|c| {
955 c.action == detail.action && c.device == CaptureDevice::Gamepad
956 }),
957 4,
958 )
959 {
960 let _ = self.begin_capture(&name, CaptureDevice::Gamepad);
961 }
962 } else {
963 let key_x = if narrow {
964 x + width - 190.
965 } else {
966 x + width - 340.
967 };
968 let pad_x = if narrow {
969 x + width - 96.
970 } else {
971 x + width - 174.
972 };
973 let bw = if narrow { 88. } else { 156. };
974 for (row, i) in (start..end).enumerate() {
975 let yy = geometry.body_y + row as f32 * 43.;
976 let info = &self.actions[i];
977 let name = info.name.clone();
978 let kind = info.kind;
979 let label = fit(&info.label, key_x - x - 28., if narrow { 14 } else { 16 });
980 draw_text(
981 &label,
982 x + 18.,
983 yy + 20.,
984 if narrow { 14. } else { 16. },
985 WHITE,
986 );
987 let keyboard = self
988 .map
989 .bindings(info.id)
990 .unwrap()
991 .iter()
992 .filter(|b| {
993 matches!(
994 b.code,
995 InputCode::Key(_)
996 | InputCode::Mouse(_)
997 | InputCode::MouseDelta(_)
998 | InputCode::Wheel(_)
999 )
1000 })
1001 .take(2)
1002 .map(|b| BindingLabel(*b).to_string())
1003 .collect::<Vec<_>>()
1004 .join(" / ");
1005 let pad = self
1006 .map
1007 .bindings(info.id)
1008 .unwrap()
1009 .iter()
1010 .find(|b| matches!(b.code, InputCode::PadButton(_) | InputCode::PadAxis(_)))
1011 .map_or_else(|| "Bind pad".into(), |b| BindingLabel(*b).to_string());
1012 if self.ui_button(
1013 Rect::new(key_x, yy, bw, 31.),
1014 if keyboard.is_empty() {
1015 "Bind key"
1016 } else {
1017 &keyboard
1018 },
1019 self.capture
1020 .is_some_and(|c| c.action == i && c.device == CaptureDevice::KeyboardMouse),
1021 3 + row * 2,
1022 ) {
1023 let _ = self.begin_capture(&name, CaptureDevice::KeyboardMouse);
1024 }
1025 if kind != ActionKind::Delta
1026 && self.ui_button(
1027 Rect::new(pad_x, yy, bw, 31.),
1028 &pad,
1029 self.capture
1030 .is_some_and(|c| c.action == i && c.device == CaptureDevice::Gamepad),
1031 4 + row * 2,
1032 )
1033 {
1034 let _ = self.begin_capture(&name, CaptureDevice::Gamepad);
1035 }
1036 }
1037 }
1038 if touch != self.touch_settings {
1039 let _ = self.set_touch_settings(touch);
1040 }
1041 if preferences != self.preferences() {
1042 let _ = self.set_preferences(preferences);
1043 }
1044 if settings != self.settings {
1045 self.set_settings(settings)
1046 .expect("bounded editor settings");
1047 self.save();
1048 }
1049 let yy = geometry.footer_y;
1050 if self.ui_button(Rect::new(x + 18., yy, 48., 26.), "<", false, footer) {
1051 self.page = self.page.saturating_sub(1);
1052 self.ui_focus = 0;
1053 self.capture = None;
1054 }
1055 let page_label = format!("{} / {pages}", self.page + 1);
1058 draw_text(&page_label, x + 18., yy - 5., 14., WHITE);
1059 if self.ui_button(Rect::new(x + 76., yy, 48., 26.), ">", false, footer + 1) {
1060 self.page = (self.page + 1).min(pages - 1);
1061 self.ui_focus = 0;
1062 self.capture = None;
1063 }
1064 if self.ui_button(
1065 Rect::new(x + width - 88., yy, 70., 26.),
1066 "Reset",
1067 false,
1068 footer + 2,
1069 ) {
1070 self.reset_defaults();
1071 if self.devices_tab {
1072 let _ = self.reset_preferences();
1073 let _ = self.set_touch_settings(touch::TouchLayoutSettings::default());
1074 }
1075 self.capture = None;
1076 }
1077 let message = if self.devices_tab {
1078 if self.touch_save_failed
1079 || self.preferences_error().is_some()
1080 || matches!(
1081 self.status,
1082 ControlsStatus::Storage(_) | ControlsStatus::Invalid(_)
1083 )
1084 {
1085 "Settings not saved; changes work for this session"
1086 } else {
1087 "Device, audio and graphics settings apply immediately"
1088 }
1089 } else {
1090 match self.status {
1091 ControlsStatus::Defaults => "Default bindings",
1092 ControlsStatus::Transient => "Session controls; persistence disabled",
1093 ControlsStatus::Saved => "Saved on this device",
1094 ControlsStatus::Loaded { unknown: 0 } => "Loaded saved controls",
1095 ControlsStatus::Loaded { .. } => "Loaded controls; retired actions ignored",
1096 ControlsStatus::Invalid(_) => "Invalid file; defaults remain available",
1097 ControlsStatus::Storage(_) => "Storage unavailable; session changes only",
1098 }
1099 };
1100 editor_copy(
1101 message,
1102 Rect::new(x + 18., y + height - 56., width - 36., 48.),
1103 0,
1104 3,
1105 Color::from_rgba(161, 185, 189, 255),
1106 );
1107 }
1108}
1109
1110impl PlayerInput {
1111 fn draw_custom_touch(&self) {
1114 crate::set_default_camera();
1115 let color = Color::new(0.9, 0.94, 0.86, self.touch_settings.opacity);
1116 for c in self.surface.controls() {
1117 if matches!(c.output, touch::Output::Look { .. }) {
1118 continue;
1119 }
1120 let center = match c.region {
1121 touch::Region::Circle { center, radius } => {
1122 draw_circle(
1123 center.x,
1124 center.y,
1125 radius,
1126 Color::new(0.04, 0.08, 0.09, self.touch_settings.opacity * 0.5),
1127 );
1128 draw_circle_lines(center.x, center.y, radius, 2., color);
1129 center
1130 }
1131 touch::Region::Rect(r) => {
1132 draw_rectangle(
1133 r.x,
1134 r.y,
1135 r.w,
1136 r.h,
1137 Color::new(0.04, 0.08, 0.09, self.touch_settings.opacity * 0.5),
1138 );
1139 draw_rectangle_lines(r.x, r.y, r.w, r.h, 2., color);
1140 r.center()
1141 }
1142 };
1143 match c.output {
1144 touch::Output::Stick { x, y, radius, .. } => {
1145 let (origin, delta) = self.surface.stick(x, y).unwrap_or((center, Vec2::ZERO));
1146 let p = origin + delta * radius * 0.6;
1147 draw_circle(p.x, p.y, 12., color);
1148 }
1149 touch::Output::Button(channel) => {
1150 let label = self
1151 .actions
1152 .iter()
1153 .find(|a| {
1154 self.map
1155 .bindings(a.id)
1156 .unwrap()
1157 .iter()
1158 .any(|b| b.code == InputCode::Touch(channel))
1159 })
1160 .map_or("Action", |a| a.label.as_str());
1161 let width = measure_text(label, None, 14, 1.).width;
1162 draw_text(label, center.x - width * 0.5, center.y + 5., 14., color);
1163 }
1164 _ => {}
1165 }
1166 }
1167 }
1168}
1169
1170#[cfg(test)]
1171mod journey400_292 {
1172 use super::*;
1173
1174 fn reset(w: u32, h: u32) {
1175 crate::edit(|s| {
1176 *s = crate::State::default();
1177 s.w = w;
1178 s.h = h;
1179 s.default_camera();
1180 });
1181 }
1182 fn vertices_in(
1183 vertices: &[[f32; 8]],
1184 rect: Rect,
1185 color: Color,
1186 screen: [f32; 2],
1187 ) -> Vec<[f32; 8]> {
1188 vertices
1189 .iter()
1190 .copied()
1191 .filter(|v| {
1192 let p = vec2((v[0] + 1.) * screen[0] * 0.5, (1. - v[1]) * screen[1] * 0.5);
1193 p.x >= rect.x - 0.001
1194 && p.x <= rect.x + rect.w + 0.001
1195 && p.y >= rect.y - 0.001
1196 && p.y <= rect.y + rect.h + 0.001
1197 && v[4..] == [color.r, color.g, color.b, color.a]
1198 })
1199 .collect()
1200 }
1201 fn assert_full_glyphs(
1202 actual: &[[f32; 8]],
1203 rect: Rect,
1204 lines: &[String],
1205 color: Color,
1206 screen: [f32; 2],
1207 ) {
1208 crate::edit(|s| s.vertices.clear());
1209 for (i, line) in lines.iter().enumerate() {
1210 draw_text(line, rect.x, rect.y + 14. + i as f32 * 16., 14., color);
1213 }
1214 let expected = crate::read(|s| s.vertices.clone());
1215 assert!(!expected.is_empty());
1216 assert_eq!(vertices_in(actual, rect, color, screen), expected);
1217 }
1218
1219 #[test]
1220 fn full_default_long_unbound_and_maximum_binding_glyphs_are_paged_at_minimum_size() {
1221 for [w, h] in [[320, 480], [320, 324], [304, 324]] {
1222 reset(w, h);
1223 let mut input = PlayerInput::preset("journey400-292-glyphs", Preset::TopDown);
1224 input
1225 .action(
1226 "long",
1227 &"LONG ACTION ".repeat(8),
1228 ActionKind::Axis,
1229 (0..MAX_BINDINGS)
1230 .map(|n| Binding {
1231 code: InputCode::Key(0xff55 + (n % 2) as u16),
1232 scale: if n % 2 == 0 { -f32::MAX } else { 0.5 },
1233 deadzone: 0.,
1234 })
1235 .collect(),
1236 )
1237 .unwrap();
1238 input
1239 .action(
1240 "empty",
1241 "Unbound action with a complete readable name",
1242 ActionKind::Button,
1243 vec![],
1244 )
1245 .unwrap();
1246 let before = input.export_config().unwrap();
1247 input.set_controls_open(true);
1248 let g = EditorGeometry::new(w as f32, h as f32);
1249 let width = g.panel.w - 36.;
1250 let screen = [w as f32, h as f32];
1251 let mut expected_pages = Vec::new();
1252 for info in &input.actions {
1253 let mut buffer = vec![0; 8192];
1254 let bindings = input
1255 .format_hint_for(&info.name, None, &mut buffer)
1256 .unwrap();
1257 let complete = format!("Action: {}\nBindings: {bindings}", info.label);
1258 let lines: Vec<_> = crate::ui::text_layout::WrappedText::new(&complete, width, 14.)
1259 .unwrap()
1260 .lines()
1261 .map(|line| line.text.to_owned())
1262 .collect();
1263 for chunk in lines.chunks(g.detail_lines) {
1264 expected_pages.push(chunk.to_vec());
1265 }
1266 }
1267 assert!(expected_pages.len() > input.actions.len());
1268 for (page, lines) in expected_pages.iter().enumerate() {
1269 input.page = page;
1270 crate::edit(|s| s.vertices.clear());
1271 input.draw_controls();
1272 let actual = crate::read(|s| s.vertices.clone());
1273 assert_eq!(input.page, page);
1274 assert!(g.body_y + (g.detail_lines - 1) as f32 * 16. + 14. < g.capture_y);
1275 assert!(g.capture_y + 31. < g.footer_y - 5. - 12.25);
1276 assert!(g.footer_y + 26. < g.panel.y + g.panel.h - 56.);
1277 assert_full_glyphs(
1278 &actual,
1279 Rect::new(
1280 g.panel.x + 18.,
1281 g.body_y,
1282 width,
1283 g.detail_lines as f32 * 16.,
1284 ),
1285 lines,
1286 WHITE,
1287 screen,
1288 );
1289 let help: Vec<_> = crate::ui::text_layout::WrappedText::new(
1291 "Changes save on this device. F2 / Esc closes.",
1292 width,
1293 14.,
1294 )
1295 .unwrap()
1296 .lines()
1297 .map(|line| line.text.to_owned())
1298 .collect();
1299 assert!(help.len() <= 3);
1300 assert_full_glyphs(
1301 &actual,
1302 Rect::new(g.panel.x + 18., g.panel.y + 87., width, 48.),
1303 &help,
1304 Color::from_rgba(161, 185, 189, 255),
1305 screen,
1306 );
1307 for v in actual {
1308 let p = [(v[0] + 1.) * screen[0] * 0.5, (1. - v[1]) * screen[1] * 0.5];
1309 assert!(p[0] >= -0.001 && p[0] <= screen[0] + 0.001, "{p:?}");
1310 assert!(p[1] >= -0.001 && p[1] <= screen[1] + 0.001, "{p:?}");
1311 }
1312 }
1313 assert_eq!(
1314 input.export_config().unwrap(),
1315 before,
1316 "drawing preserves exact save bytes"
1317 );
1318 }
1319 }
1320
1321 fn frame(input: &mut PlayerInput) {
1322 host_frame(0., 320, 480, || {
1323 input.sample(true);
1324 input.draw_controls();
1325 });
1326 }
1327 fn click(input: &mut PlayerInput, position: Vec2) {
1328 crate::pointer(position.x, position.y, 0., 0.);
1329 crate::button(1, true);
1330 frame(input);
1331 crate::button(1, false);
1332 frame(input);
1333 }
1334 fn tap(input: &mut PlayerInput, key: u32) {
1335 crate::key(key, true);
1336 frame(input);
1337 crate::key(key, false);
1338 frame(input);
1339 }
1340
1341 #[test]
1342 fn minimum_panel_keeps_capture_help_status_navigation_and_delta_focus_readable() {
1343 reset(320, 324);
1344 let mut input = PlayerInput::transient("journey400-292-minimum");
1345 input
1346 .action(
1347 "look",
1348 "Look",
1349 ActionKind::Delta,
1350 vec![Binding::digital(InputCode::MouseDelta(0))],
1351 )
1352 .unwrap();
1353 input.set_controls_open(true);
1354 input
1355 .begin_capture("look", CaptureDevice::KeyboardMouse)
1356 .unwrap();
1357 input.draw_controls();
1358 let actual = crate::read(|s| s.vertices.clone());
1359 let g = EditorGeometry::new(320., 324.);
1360 let width = g.panel.w - 36.;
1361 let muted = Color::from_rgba(161, 185, 189, 255);
1362 for (text, top) in [
1363 (
1364 "Press key/button or move axis right/down. Esc cancels.",
1365 g.panel.y + 87.,
1366 ),
1367 (
1368 "Session controls; persistence disabled",
1369 g.panel.y + g.panel.h - 56.,
1370 ),
1371 ] {
1372 let lines: Vec<_> = crate::ui::text_layout::WrappedText::new(text, width, 14.)
1373 .unwrap()
1374 .lines()
1375 .map(|line| line.text.to_owned())
1376 .collect();
1377 assert!(lines.len() <= 3);
1378 assert_full_glyphs(
1379 &actual,
1380 Rect::new(g.panel.x + 18., top, width, 48.),
1381 &lines,
1382 muted,
1383 [320., 324.],
1384 );
1385 }
1386 for (label, rect) in [
1387 (
1388 "Done",
1389 Rect::new(g.panel.x + g.panel.w - 94., g.panel.y + 13., 76., 27.),
1390 ),
1391 (
1392 "Bind key",
1393 Rect::new(g.panel.x + 18., g.capture_y, 122., 31.),
1394 ),
1395 ("<", Rect::new(g.panel.x + 18., g.footer_y, 48., 26.)),
1396 (">", Rect::new(g.panel.x + 76., g.footer_y, 48., 26.)),
1397 (
1398 "Reset",
1399 Rect::new(g.panel.x + g.panel.w - 88., g.footer_y, 70., 26.),
1400 ),
1401 ] {
1402 crate::edit(|s| s.vertices.clear());
1403 let text_width = measure_text(label, None, 14, 1.).width;
1404 draw_text(
1405 label,
1406 rect.x + (rect.w - text_width) * 0.5,
1407 rect.y + rect.h * 0.5 + 5.,
1408 14.,
1409 WHITE,
1410 );
1411 let expected = crate::read(|s| s.vertices.clone());
1412 assert_eq!(
1413 vertices_in(&actual, rect, WHITE, [320., 324.]),
1414 expected,
1415 "{label}"
1416 );
1417 }
1418 crate::key(0xff1b, true);
1421 input.sample(true);
1422 assert!(input.capture.is_none());
1423 crate::key(0xff1b, false);
1424 host_frame(0., 320, 324, || {
1425 input.sample(true);
1426 input.draw_controls();
1427 });
1428 for expected in [1, 2, 3, 5, 6, 7, 0] {
1429 crate::key(0xff09, true);
1430 host_frame(0., 320, 324, || {
1431 input.sample(true);
1432 input.draw_controls();
1433 });
1434 assert_eq!(input.ui_focus, expected);
1435 crate::key(0xff09, false);
1436 host_frame(0., 320, 324, || {
1437 input.sample(true);
1438 input.draw_controls();
1439 });
1440 }
1441 }
1442
1443 #[test]
1444 fn journal_ticks_editor_capture_cancel_reset_paging_tabs_and_done_use_production_paths() {
1445 reset(320, 480);
1446 let mut input = PlayerInput::transient("journey400-292-journal");
1447 input
1448 .action(
1449 "jump",
1450 "Jump with a long default action label",
1451 ActionKind::Button,
1452 vec![
1453 Binding::digital(InputCode::Key(32)),
1454 Binding::digital(InputCode::PadButton(0)),
1455 Binding::digital(InputCode::Touch(6)),
1456 ],
1457 )
1458 .unwrap();
1459 input
1460 .action(
1461 "look",
1462 "Look",
1463 ActionKind::Delta,
1464 vec![Binding::digital(InputCode::MouseDelta(0))],
1465 )
1466 .unwrap();
1467 input
1468 .set_touch_layout(&[touch::Control {
1469 region: touch::Region::Rect(Rect::new(10., 300., 80., 80.)),
1470 output: touch::Output::Button(6),
1471 }])
1472 .unwrap();
1473 let labels = [VisibleTouchLabel {
1474 slot: 0,
1475 code: InputCode::Touch(6),
1476 label: "JUMP",
1477 }];
1478 let original = input.export_config().unwrap();
1479 frame(&mut input);
1480 crate::key(32, true);
1481 crate::key(32, false);
1482 crate::pointer(100., 100., 9., 0.);
1483 frame(&mut input); let mut buffer = [0; 128];
1485 for _ in 0..3 {
1486 assert_eq!(
1487 input
1488 .format_visible_hint_for("jump", None, &labels, &mut buffer)
1489 .unwrap(),
1490 "Space / Pad 0 / JUMP"
1491 );
1492 frame(&mut input);
1493 }
1494 let [jump, look] = input.take_tick(["jump", "look"]);
1495 assert!(jump.pressed && jump.released);
1496 assert_ne!(look.value, 0.);
1497 assert_eq!(input.take_tick(["jump", "look"]), [Action::default(); 2]);
1498 for phase in [touch::Phase::Start, touch::Phase::Cancel] {
1500 touch_event(touch::Event {
1501 id: 292,
1502 position: vec2(40., 330.),
1503 phase,
1504 });
1505 frame(&mut input);
1506 input
1507 .format_visible_hint("jump", &labels, &mut buffer)
1508 .unwrap();
1509 }
1510 assert!(!input.touch_active());
1511 input.take_tick(["jump"]);
1512 assert_eq!(input.take_tick(["jump"]), [Action::default()]);
1513 tap(&mut input, 0xffbf); assert!(input.controls_open());
1515 let g = EditorGeometry::new(320., 480.);
1516 let key_button = vec2(g.panel.x + 70., g.capture_y + 15.);
1517 click(&mut input, key_button);
1518 assert!(input.capture.is_some());
1519 tap(&mut input, 0xff1b);
1520 assert!(input.controls_open());
1521 assert!(input.capture.is_none());
1522 assert_eq!(input.export_config().unwrap(), original);
1523 click(&mut input, key_button);
1524 tap(&mut input, 0xff56); assert!(input.capture.is_none());
1526 assert_eq!(
1527 input.format_hint_for("jump", None, &mut buffer).unwrap(),
1528 "Pad 0 / Touch 6 / PageDown"
1529 );
1530 assert_eq!(
1531 input
1532 .format_visible_hint_for("jump", None, &labels, &mut buffer)
1533 .unwrap(),
1534 "Pad 0 / JUMP / PageDown"
1535 );
1536 let edited = input.export_config().unwrap();
1537 input.rebind("jump", vec![]).unwrap();
1538 input.import_config(&edited).unwrap();
1539 assert_eq!(input.export_config().unwrap(), edited);
1540 assert!(
1541 !input.take_tick(["jump"])[0].pressed,
1542 "capture/menu events cannot leak to gameplay"
1543 );
1544 click(&mut input, vec2(g.panel.x + 90., g.footer_y + 13.));
1545 assert_eq!(input.page, 1);
1546 click(&mut input, vec2(g.panel.x + 40., g.footer_y + 13.));
1547 assert_eq!(input.page, 0);
1548 click(
1549 &mut input,
1550 vec2(g.panel.x + g.panel.w - 50., g.footer_y + 13.),
1551 );
1552 assert_eq!(input.export_config().unwrap(), original);
1553 input.page = usize::MAX;
1555 click(&mut input, vec2(g.panel.x + 160., g.panel.y + 60.));
1556 assert!(input.devices_tab);
1557 assert_eq!(input.page, 0);
1558 click(&mut input, vec2(g.panel.x + 60., g.panel.y + 60.));
1559 assert!(!input.devices_tab);
1560 click(
1561 &mut input,
1562 vec2(g.panel.x + g.panel.w - 50., g.panel.y + 26.),
1563 );
1564 assert!(!input.controls_open());
1565 frame(&mut input);
1566 assert_eq!(input.take_tick(["jump", "look"]), [Action::default(); 2]);
1567 }
1568}