pinch-points 0.9.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before time runs out
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
//! The settings the whole game reads (spec §8.4): keyboard preset and
//! bindings, cursor repeat tuning, audio, accessibility, and the
//! single-player speed assist. Persisted as a plain `settings.txt` under
//! the XDG config directory (see [`crate::app::paths::config_dir`]),
//! leniently parsed so an old or hand-edited file never breaks startup.
//!
//! The screen that edits them is [`screen`]; the systems that push a
//! changed setting out into Bevy (UI scale, sink volume, tick rate) stay
//! here, beside the values they read.

mod file;
pub mod screen;

use crate::app::Screen;
use crate::app::audio::Music;
use crate::app::binds::{BOUND_SEATS, SeatBinds, default_binds};
use crate::app::i18n::Lang;
use crate::app::palette;
use crate::app::teams::TeamMode;
use crate::sim::MAX_PLAYERS;
use bevy::audio::Volume;
use bevy::prelude::*;
use bevy::window::{MonitorSelection, WindowMode};

/// How many finished rounds the shelf keeps, and the range the dial turns
/// through. Zero is not offered: a library that keeps nothing is the menu's
/// Replay entry quietly doing nothing, which reads as a fault rather than
/// as a setting.
pub const REPLAY_CAP_MIN: u8 = 5;
pub const REPLAY_CAP_MAX: u8 = 99;
pub const REPLAY_CAP_DEFAULT: u8 = 20;

/// Where the gamepad deadzone dial stops, percent of travel.
pub const DEADZONE_RANGE: std::ops::RangeInclusive<u8> = 20..=80;
/// Where the volume dials stop.
pub const VOLUME_RANGE: std::ops::RangeInclusive<u8> = 0..=100;
/// Hold-to-repeat bounds, seconds: the card steps inside these and the
/// parser clamps a saved value into them, so the two cannot disagree.
pub const REPEAT_DELAY_RANGE: std::ops::RangeInclusive<f32> = 0.1..=0.5;
pub const REPEAT_INTERVAL_RANGE: std::ops::RangeInclusive<f32> = 0.03..=0.2;
/// UI scale bounds, percent of the window the interface fills. 100 fills
/// it: the interface is laid out once, in design pixels, and scaled to the
/// window, so every screen looks the same at 720p as at 1440p. It cannot
/// go past filling it, since nothing reflows; turning it down hands the
/// room back to the board, which a big screen may want.
pub const UI_SCALE_MIN: u8 = 60;
pub const UI_SCALE_MAX: u8 = 100;

/// `value` held inside `range`, for the dials the card steps and the
/// numbers the file reads, which keep to the same bounds.
pub(crate) fn clamp_in<T: PartialOrd + Copy>(value: T, range: &std::ops::RangeInclusive<T>) -> T {
    if value < *range.start() {
        *range.start()
    } else if value > *range.end() {
        *range.end()
    } else {
        value
    }
}

/// What drives one of the two keyboard seats. Pads fill the table from P2
/// upwards and P1 last, so with two pads and no ceremony pad one drives P2
/// and pad two drives P1; this is how you say otherwise.
///
/// The keyboard stays live whatever this says, apart from [`Self::Keys`],
/// which is the one that turns pads off: picking a controller says *which*
/// controller is yours, not that the keyboard has stopped working.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum SeatInput {
    /// Whichever pad the seat rule deals it (see `gamepad::PadSeats`).
    #[default]
    Auto,
    /// Keyboard only: no pad drives this seat.
    Keys,
    /// The nth controller, counting in the order they were plugged in:
    /// never the order of the Starts, or a friend's Start renamed it.
    Pad(u8),
}

/// How many controllers a seat may name: the stops the dial offers.
pub const NAMED_PADS: u8 = 4;

/// Where player 1's four commit keys live: the stock arrows, or the §8.2
/// one-hand preset on IJKL. A dial, like the seat inputs beside it, and a
/// token in settings.txt that an unknown word falls back from rather than
/// silently reading as "arrows".
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum CommitScheme {
    #[default]
    Arrows,
    Ijkl,
}

impl CommitScheme {
    pub fn key(self) -> &'static str {
        match self {
            CommitScheme::Arrows => "arrows",
            CommitScheme::Ijkl => "ijkl",
        }
    }

    pub fn from_key(key: &str) -> CommitScheme {
        use crate::app::cycle::Cycle;
        Self::VARIANTS
            .iter()
            .copied()
            .find(|scheme| scheme.key() == key)
            .unwrap_or_default()
    }
}

impl crate::app::cycle::Cycle for CommitScheme {
    const VARIANTS: &'static [CommitScheme] = &[CommitScheme::Arrows, CommitScheme::Ijkl];
}

impl crate::app::cycle::Cycle for SeatInput {
    const VARIANTS: &'static [SeatInput] = &[
        SeatInput::Auto,
        SeatInput::Keys,
        SeatInput::Pad(0),
        SeatInput::Pad(1),
        SeatInput::Pad(2),
        SeatInput::Pad(3),
    ];
}

impl SeatInput {
    /// The settings-file spelling, and its inverse.
    fn name(self) -> String {
        match self {
            SeatInput::Auto => "auto".to_string(),
            SeatInput::Keys => "keys".to_string(),
            SeatInput::Pad(n) => format!("pad{}", n + 1),
        }
    }

    fn from_name(text: &str) -> SeatInput {
        match text.trim() {
            "keys" => SeatInput::Keys,
            other => other
                .strip_prefix("pad")
                .and_then(|n| n.parse::<u8>().ok())
                .filter(|&n| (1..=NAMED_PADS).contains(&n))
                .map_or(SeatInput::Auto, |n| SeatInput::Pad(n - 1)),
        }
    }
}

/// How fast a puzzle runs, the §8.4 single-player speed assist: three
/// stops, as a share of the canonical tick rate. Kept in the settings file
/// as its percent.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum PuzzleSpeed {
    Half,
    ThreeQuarter,
    #[default]
    Full,
}

impl PuzzleSpeed {
    /// Every stop, slowest first: the order the dial turns through.
    const ALL: [PuzzleSpeed; 3] = [
        PuzzleSpeed::Half,
        PuzzleSpeed::ThreeQuarter,
        PuzzleSpeed::Full,
    ];

    /// The speed as a percent of the canonical rate, as it is shown and
    /// saved.
    pub fn percent(self) -> u8 {
        match self {
            PuzzleSpeed::Half => 50,
            PuzzleSpeed::ThreeQuarter => 75,
            PuzzleSpeed::Full => 100,
        }
    }

    /// The stop nearest a saved percent, so a hand-edited file still lands
    /// on one.
    pub fn from_percent(percent: u8) -> PuzzleSpeed {
        match percent {
            0..=62 => PuzzleSpeed::Half,
            63..=87 => PuzzleSpeed::ThreeQuarter,
            88.. => PuzzleSpeed::Full,
        }
    }

    /// One stop slower or faster, stopping at either end rather than
    /// wrapping round: half speed and full are not neighbours.
    pub fn stepped(self, turn: crate::app::cycle::Turn) -> PuzzleSpeed {
        let at = Self::ALL.iter().position(|&s| s == self).unwrap_or(0);
        let to = match turn {
            crate::app::cycle::Turn::Left => at.saturating_sub(1),
            crate::app::cycle::Turn::Right => (at + 1).min(Self::ALL.len() - 1),
        };
        Self::ALL[to]
    }
}

#[derive(Resource, Clone, PartialEq, Debug)]
pub struct GameSettings {
    /// §8.2: which keys player 1 commits a signpost on. The one-hand
    /// preset puts them on IJKL (solo modes only: IJKL moves player 2 in
    /// shared-keyboard versus).
    pub commit: CommitScheme,
    /// What drives P1 and P2. Seats past the second are always `Auto`:
    /// they have no keyboard of their own to choose between.
    pub seat_input: [SeatInput; BOUND_SEATS],
    /// Cursor hold-to-repeat: initial delay and repeat interval, seconds.
    pub repeat_delay: f32,
    pub repeat_interval: f32,
    /// Whether the background music plays at all. Separate from the
    /// volume so switching it off and back on returns the player to the
    /// level they had set, rather than to whatever 0% was hiding.
    pub music_on: bool,
    /// Background music volume, 0–100.
    pub music_volume: u8,
    /// Whether sound effects play at all; the companion to `music_on`.
    pub sfx_on: bool,
    /// Sound-effect volume, 0–100 (0 is the old "off").
    pub sfx_volume: u8,
    /// Puzzle-mode simulation speed, the §8.4 single-player speed
    /// reduction. Never applies to versus or online.
    pub puzzle_speed: PuzzleSpeed,
    /// How a versus round is scored: free-for-all, pairs, or trios.
    /// Presentation and win condition only; the sim is unchanged, so it is
    /// lockstep-safe.
    pub team_mode: TeamMode,
    /// UI language; every player-facing string localizes through this.
    pub language: Lang,
    /// Controller rumble on raids, surges, and round end.
    ///
    /// The two board-wide ones buzz every pad in the room: the surge and
    /// the tide coming in happen to the whole beach
    /// (`audio::play_events`). A raid happens to one seat, so that one is
    /// aimed at the hands of the player whose castle it was
    /// (`gamepad::rumble_on_raid`).
    pub rumble: bool,
    /// Left-stick deadzone percent (20-80) before it counts as a direction.
    pub pad_deadzone: u8,
    /// Use the colour-vision-safe player palette (no red/green pair).
    pub colorblind: bool,
    /// Borderless fullscreen on the current monitor, or a window. On by
    /// default, so a first launch fills the screen the way a game is
    /// expected to; F11 flips it from anywhere (`toggle_fullscreen`).
    pub fullscreen: bool,
    /// UI scale percent, `UI_SCALE_MIN..=UI_SCALE_MAX`: every HUD, panel,
    /// and menu element.
    pub ui_scale: u8,
    /// Drop the decorative motion: particle bursts, confetti, footprints,
    /// raid flashes, bouncing numbers, the blinking clock.
    pub reduced_motion: bool,
    /// Smooth the edges of what is drawn on the beach (4x multisampling).
    /// Off by default: on this game's sprites it changes a row of pixels
    /// along a plank, and on an integrated chip it made the beach's own
    /// passes half again to twice as slow (see `boot::apply_antialiasing`).
    pub antialiasing: bool,
    /// Per-seat keyboard bindings (spec §8.4 full remapping).
    pub binds: [SeatBinds; BOUND_SEATS],
    /// What each seat is called. Empty means "no name given", and the seat
    /// falls back to the localized P1/J1/S1 label, so a fresh install and
    /// a player who never opens the naming rows behave as they always did.
    pub names: [String; MAX_PLAYERS],
    /// How many kept rounds the shelf holds before the oldest fall off.
    ///
    /// Rounds are kept one at a time from the results card and pasted in
    /// as codes, so without a cap the library grows for as long as the
    /// game is played.
    pub replay_cap: u8,
    /// The last beach dialled by hand, `ip:port`, empty until one is.
    ///
    /// A LAN with broadcast turned off does not turn it back on between
    /// rounds, so the machine dialled once has to be dialled again. Only
    /// ever written from an address that parsed.
    pub last_beach: String,
    /// Ask GitHub on start-up whether a newer release is out, and say so
    /// on a page of its own (see [`crate::app::update`]). The one thing
    /// the game says to the wider internet, so it is the player's to
    /// switch off.
    pub check_updates: bool,
    /// The keyboard the player says they have, or `None` for the game
    /// working it out (which is right almost always - see
    /// [`crate::app::keycaps::KeyCaps::force`] for the "almost").
    ///
    /// A preference, unlike the learned caps table, which nobody sets and
    /// which lives as its own resource, [`crate::app::keycaps::KeyCaps`].
    /// The two still share the file: the save path takes both and writes
    /// the `keycaps:` line beside this one.
    pub keyboard: Option<crate::app::keycaps::Layout>,
    /// Whether the editor's tips are still to be shown: on until a first
    /// visit puts the card away (`editor::editor_card_input`), and never
    /// again after.
    pub editor_tips: bool,
}

/// Longest seat name we keep. The score chips and the event feed are laid
/// out in a fixed-width sidebar; a twelve-character name is the most that
/// fits beside a four-digit score.
pub const NAME_MAX: usize = 12;

impl GameSettings {
    /// The active string table.
    pub fn tr(&self) -> &'static crate::app::i18n::Tr {
        self.language.tr()
    }

    /// Set the keyboard the game reads the caps off, or `None` to have it
    /// work that out again. The one path that changes it, and it asks for
    /// the caps table outright so the two can never disagree.
    pub fn set_keyboard(
        &mut self,
        keyboard: Option<crate::app::keycaps::Layout>,
        caps: &mut crate::app::keycaps::KeyCaps,
    ) {
        self.keyboard = keyboard;
        caps.force(keyboard);
    }

    /// Set the interface language, and with it the keyboard the game
    /// presumes: a player reading in French is typing on AZERTY until a
    /// press says otherwise (see [`crate::app::keycaps::Layout::of`]).
    /// Every path that changes the language comes through here and brings
    /// the caps table with it, so the presumption cannot be left behind by
    /// the words on screen.
    pub fn set_language(&mut self, language: Lang, caps: &mut crate::app::keycaps::KeyCaps) {
        self.language = language;
        caps.presume(crate::app::keycaps::Layout::of(language));
    }

    /// Whether the player has moved any key off its factory binding. The
    /// on-screen key legends are written for the stock layout, so they step
    /// aside when this is true rather than teach the wrong keys.
    pub fn custom_binds(&self) -> bool {
        self.binds != default_binds()
    }

    /// The commit scheme the keyboard is read with: the one set, unless
    /// the keyboard is `shared`. Versus seats a rival on the second seat's
    /// keys, and a co-op puzzle a partner (a cursor for player 1), so
    /// either way IJKL is somebody else's and the one-hand preset stands
    /// down.
    ///
    /// One rule for every reader of those keys: the cursor, a puzzle's
    /// setup, the seat keys a global letter yields to
    /// ([`crate::app::cursor::LiveSeatKeys`]), and the legends that
    /// teach them ([`Self::stock_legend`]).
    pub fn commit_in_play(&self, shared: bool) -> CommitScheme {
        if shared {
            CommitScheme::Arrows
        } else {
            self.commit
        }
    }

    /// Whether the stock key legends ("WASD move, arrows place") describe
    /// what the keys do right now, with the keyboard `shared` or not (see
    /// [`Self::commit_in_play`]): they do not once a key is rebound, and
    /// not under the one-hand preset either, which puts placement on IJKL
    /// whatever the bindings say. Anything that teaches keys asks this
    /// rather than [`Self::custom_binds`] alone.
    pub fn stock_legend(&self, shared: bool) -> bool {
        !self.custom_binds() && self.commit_in_play(shared) == CommitScheme::Arrows
    }

    /// Sound-effect gain, 0.0 to [`SFX_TRIM`], with the on/off switch folded in. Zero
    /// means silence, so callers test the gain rather than the switch and
    /// the slider separately, and a one-shot at zero gain is not spawned.
    pub fn sfx_gain(&self) -> f32 {
        if self.sfx_on {
            f32::from(self.sfx_volume) / 100.0 * SFX_TRIM
        } else {
            0.0
        }
    }

    /// Music gain, 0.0 to [`MUSIC_LIFT`]: the sink volume, wherever it is
    /// set. Switched off reads as zero, the same as the slider at the
    /// bottom.
    pub fn music_gain(&self) -> f32 {
        if self.music_on {
            f32::from(self.music_volume) / 100.0 * MUSIC_LIFT
        } else {
            0.0
        }
    }

    /// UI scale as the ratio Bevy wants (1.0 is 100%).
    pub fn ui_ratio(&self) -> f32 {
        f32::from(self.ui_scale) / 100.0
    }

    /// Left-stick deadzone as the 0.0–1.0 magnitude it is compared against.
    pub fn deadzone(&self) -> f32 {
        f32::from(self.pad_deadzone) / 100.0
    }

    /// The couch-table name for a seat. Round displays go through
    /// [`crate::app::SeatNames`] instead, which knows when an online table
    /// overrides these; this stays as the reference for the typing tests.
    #[cfg(test)]
    pub fn seat_name(&self, seat: u8) -> String {
        crate::app::name_or_label(&self.names, self.tr(), seat)
    }

    /// Type one character into a seat's name, dropping anything that would
    /// make a mess of the save file or the sidebar.
    pub fn push_name_char(&mut self, seat: u8, ch: char) {
        let Some(name) = self.names.get_mut(usize::from(seat)) else {
            return;
        };
        // `|` separates names in the save file and `:` its keys; control
        // characters would corrupt the line outright.
        let ok = !ch.is_control() && ch != '|' && ch != ':' && (ch != ' ' || !name.is_empty());
        if ok && name.chars().count() < NAME_MAX {
            name.push(ch);
        }
    }

    /// Set a seat's name from a whole string, through the same gate one
    /// typed character goes through.
    ///
    /// Assigning the field directly is what the lobby used to do, and it
    /// skipped all three of [`push_name_char`](Self::push_name_char)'s
    /// rules at once: a lobby name could be any length, and could carry
    /// the `|` that separates names in the save file, which on the next
    /// launch handed everything after it to the seats behind.
    pub fn set_name(&mut self, seat: u8, name: &str) {
        let Some(slot) = self.names.get_mut(usize::from(seat)) else {
            return;
        };
        slot.clear();
        for ch in name.chars() {
            self.push_name_char(seat, ch);
        }
    }

    /// Rub out the last character of a seat's name.
    pub fn pop_name_char(&mut self, seat: u8) {
        if let Some(name) = self.names.get_mut(usize::from(seat)) {
            name.pop();
        }
    }

    /// Tidy a seat's name once the player is done typing: a name of nothing
    /// but spaces is no name at all.
    pub fn tidy_name(&mut self, seat: u8) {
        if let Some(name) = self.names.get_mut(usize::from(seat)) {
            *name = name.trim().to_string();
        }
    }
}

impl Default for GameSettings {
    fn default() -> Self {
        GameSettings {
            commit: CommitScheme::Arrows,
            seat_input: [SeatInput::Auto; BOUND_SEATS],
            repeat_delay: 0.28,
            repeat_interval: 0.09,
            music_on: true,
            music_volume: 45,
            sfx_on: true,
            sfx_volume: 80,
            puzzle_speed: PuzzleSpeed::Full,
            team_mode: TeamMode::default(),
            language: Lang::default(),
            rumble: true,
            pad_deadzone: 50,
            colorblind: false,
            fullscreen: true,
            ui_scale: 100,
            reduced_motion: false,
            antialiasing: false,
            binds: default_binds(),
            names: std::array::from_fn(|_| String::new()),
            replay_cap: REPLAY_CAP_DEFAULT,
            last_beach: String::new(),
            check_updates: true,
            editor_tips: true,
            keyboard: None,
        }
    }
}

/// How much louder the music plays than its slider reads.
///
/// The tracks are mastered quieter than the effects: about -23 dB on
/// average against -19 for the effects (measured with ffmpeg's
/// `volumedetect`), and the effects' slider starts higher. At one to one
/// the music sat some ten decibels under the effects at the defaults,
/// and a playtest heard it as missing. Lifted, the default sits about four
/// under, and the slider at the top still leaves the loudest track's peak
/// (-7.1 dB, `theme_b`) just under full scale: see the test beside
/// [`GameSettings::music_gain`].
pub const MUSIC_LIFT: f32 = 2.2;

/// How much quieter the effects play than their slider reads.
///
/// Even with the music lifted, a playtest still heard the effects over
/// it. Trimmed by about three decibels, the default puts the two about
/// level, and a saved setting keeps its number and plays quieter.
pub const SFX_TRIM: f32 = 0.7;

/// The window the interface was laid out for. Every card, gutter and
/// offset on every screen is a number of these pixels, so a window smaller
/// than this shrinks the whole interface to fit rather than letting the
/// cards run off the edges.
pub const DESIGN_W: f32 = 1280.0;
pub const DESIGN_H: f32 = 720.0;

/// The UI scale actually applied: the interface fitted to the window, then
/// the player's share of that.
///
/// The interface is a fixed layout of design pixels, so fitting it means
/// scaling it by the tighter of the window's two sides against the design:
/// a window smaller than the design shrinks it rather than letting cards
/// run off the edges, and a bigger one grows it. It used to stop growing
/// at the design size, giving a big window more room instead, "as the
/// board is"; but the board fills the window now, and an interface held at
/// 1280x720 beside it read small and far from the play on every screen
/// larger than that. The player's ratio, at most 1, takes some back.
pub fn applied_ui_ratio(ui_ratio: f32, width: f32, height: f32) -> f32 {
    let fit = (width / DESIGN_W).min(height / DESIGN_H).max(0.01);
    fit * ui_ratio.min(1.0)
}

/// Push the accessibility choices that live outside this resource: the
/// player palette (read from a static by every renderer) and Bevy's global
/// UI scale. The palette follows the settings; the scale also follows the
/// window, so it is recomputed every frame and written only when it moves.
pub fn apply_accessibility(
    settings: Res<GameSettings>,
    windows: Query<&Window>,
    mut ui_scale: ResMut<UiScale>,
) {
    if settings.is_changed() {
        palette::set_colorblind(settings.colorblind);
    }
    let scale = windows.iter().next().map_or(settings.ui_ratio(), |window| {
        applied_ui_ratio(settings.ui_ratio(), window.width(), window.height())
    });
    if (ui_scale.0 - scale).abs() > f32::EPSILON {
        ui_scale.0 = scale;
    }
}

/// The mode the window should be in for these settings.
///
/// A dev run that sized its window or came to take a picture stays in that
/// window whatever the settings say: `PINCH_WINDOW` asks for a size a
/// fullscreen window would ignore, and a screenshot harness launches one
/// process per peer, which would otherwise take the whole screen each.
pub fn window_mode(settings: &GameSettings) -> WindowMode {
    if settings.fullscreen && !crate::app::dev::window_pinned() {
        WindowMode::BorderlessFullscreen(MonitorSelection::Current)
    } else {
        WindowMode::Windowed
    }
}

/// Put the window in the mode the settings ask for. The launch mode is set
/// when the window is built (`schedule::run`), so this only acts on a
/// change: the settings row, or F11.
pub fn apply_window_mode(settings: Res<GameSettings>, mut windows: Query<&mut Window>) {
    if !settings.is_changed() {
        return;
    }
    let mode = window_mode(&settings);
    for mut window in &mut windows {
        if window.mode != mode {
            window.mode = mode;
        }
    }
}

/// F11 flips fullscreen on every screen, and keeps the answer: a player who
/// wanted the window once will want it next launch too.
///
/// Except before the first-run language picker is answered, which is
/// shown because there is no settings file yet: written then, the file
/// made the picker a screen nobody would see again. The flag still flips, and is kept with the rest
/// when the language is taken.
pub fn toggle_fullscreen(
    keys: Res<ButtonInput<KeyCode>>,
    mut settings: ResMut<GameSettings>,
    caps: Res<crate::app::keycaps::KeyCaps>,
    unasked: Res<crate::app::language::LanguageUnasked>,
) {
    if flip_fullscreen(&keys, &mut settings, &unasked) {
        settings.save(&caps);
    }
}

/// F11's flip, and whether it may be written down now. Apart from the
/// system so the rule can be checked without writing a settings file.
fn flip_fullscreen(
    keys: &ButtonInput<KeyCode>,
    settings: &mut GameSettings,
    unasked: &crate::app::language::LanguageUnasked,
) -> bool {
    if !keys.just_pressed(KeyCode::F11) {
        return false;
    }
    settings.fullscreen = !settings.fullscreen;
    unasked.may_save()
}

/// Push the music volume to the sink whenever settings change.
pub fn apply_music_volume(
    settings: Res<GameSettings>,
    mut sinks: Query<&mut AudioSink, (With<Music>, Without<crate::app::audio::FadingOut>)>,
) {
    if !settings.is_changed() {
        return;
    }
    for mut sink in &mut sinks {
        sink.set_volume(Volume::Linear(settings.music_gain()));
    }
}

/// The §8.4 speed assist: puzzles tick slower when asked; every other mode
/// (and online determinism) stays at the canonical 30 Hz.
///
/// A puzzle playtested in the editor is a puzzle too: an author who needs
/// the assist to follow a stage needs it to test one, and a stage tested
/// at a pace its player will never see is not the stage that ships. A
/// beach under test plays at the versus rate, as it will in a match.
pub fn apply_sim_speed(
    settings: Res<GameSettings>,
    screen: Res<State<Screen>>,
    editor: Res<crate::app::editor::EditorState>,
    mut fixed_time: ResMut<Time<Fixed>>,
) {
    let puzzle = match screen.get() {
        Screen::Puzzle => true,
        Screen::Editor => editor.is_testing() && editor.kind == crate::sim::LevelKind::Puzzle,
        Screen::Menu
        | Screen::Versus
        | Screen::Lobby
        | Screen::Settings
        | Screen::Controls
        | Screen::MatchSetup
        | Screen::Achievements
        | Screen::StageSelect
        | Screen::Replays
        | Screen::Interlude
        | Screen::Language
        | Screen::NewVersion => false,
    };
    let hz = if puzzle {
        f64::from(crate::sim::TICKS_PER_SECOND) * f64::from(settings.puzzle_speed.percent()) / 100.0
    } else {
        f64::from(crate::sim::TICKS_PER_SECOND)
    };
    if (fixed_time.timestep().as_secs_f64() - 1.0 / hz).abs() > 1e-9 {
        fixed_time.set_timestep_hz(hz);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// F11 before the first-run language question is answered flips the
    /// window but writes nothing: a settings file is what tells the next
    /// launch the picker has been seen. Once answered it is kept at once.
    #[test]
    fn fullscreen_before_a_language_is_taken_is_not_written_yet() {
        use crate::app::language::LanguageUnasked;
        let mut keys = ButtonInput::<KeyCode>::default();
        let mut settings = GameSettings::default();
        let was = settings.fullscreen;
        let unasked = LanguageUnasked(true);
        assert!(!flip_fullscreen(&keys, &mut settings, &unasked));
        assert_eq!(settings.fullscreen, was, "no F11, no flip");
        keys.press(KeyCode::F11);
        assert!(!flip_fullscreen(&keys, &mut settings, &unasked));
        assert_ne!(settings.fullscreen, was, "the window still flips");
        assert!(flip_fullscreen(
            &keys,
            &mut settings,
            &LanguageUnasked(false)
        ));
        assert_eq!(settings.fullscreen, was);
    }

    /// The world `apply_sim_speed` runs in: a screen, the settings, and the
    /// fixed clock at the canonical rate.
    fn clocked(screen: Screen, puzzle_speed: PuzzleSpeed) -> App {
        let mut app = App::new();
        app.add_plugins(bevy::state::app::StatesPlugin);
        app.init_state::<Screen>();
        app.insert_resource(State::new(screen));
        app.insert_resource(GameSettings {
            puzzle_speed,
            ..GameSettings::default()
        });
        app.insert_resource(Time::<Fixed>::from_hz(f64::from(
            crate::sim::TICKS_PER_SECOND,
        )));
        app.init_resource::<crate::app::editor::EditorState>();
        app.add_systems(Update, apply_sim_speed);
        app
    }

    fn hz(app: &App) -> f64 {
        1.0 / app
            .world()
            .resource::<Time<Fixed>>()
            .timestep()
            .as_secs_f64()
    }

    /// The speed dial stops at either end, and a saved percent lands on
    /// the nearest stop and is written back as that stop.
    #[test]
    fn the_speed_dial_stops_at_its_ends() {
        use crate::app::cycle::Turn;
        assert_eq!(PuzzleSpeed::Full.stepped(Turn::Right), PuzzleSpeed::Full);
        assert_eq!(PuzzleSpeed::Half.stepped(Turn::Left), PuzzleSpeed::Half);
        assert_eq!(
            PuzzleSpeed::Full.stepped(Turn::Left),
            PuzzleSpeed::ThreeQuarter
        );
        assert_eq!(
            PuzzleSpeed::Half.stepped(Turn::Right),
            PuzzleSpeed::ThreeQuarter
        );
        for speed in PuzzleSpeed::ALL {
            assert_eq!(PuzzleSpeed::from_percent(speed.percent()), speed);
        }
        assert_eq!(PuzzleSpeed::from_percent(70), PuzzleSpeed::ThreeQuarter);
        assert_eq!(PuzzleSpeed::from_percent(0), PuzzleSpeed::Half);
    }

    /// The speed assist slows a puzzle to the fraction asked for.
    #[test]
    fn a_puzzle_runs_at_the_speed_asked_for() {
        let mut app = clocked(Screen::Puzzle, PuzzleSpeed::Half);
        app.update();
        assert!((hz(&app) - 15.0).abs() < 1e-6, "{} Hz", hz(&app));
    }

    /// A stage playtested in the editor is slowed the same, and a beach
    /// under test is not: it is a versus map, played at the versus rate.
    #[test]
    fn an_editor_playtest_of_a_stage_runs_at_the_speed_asked_for() {
        use crate::app::editor::{EditorState, Mode};
        use crate::sim::LevelKind;
        for (kind, want) in [(LevelKind::Puzzle, 15.0), (LevelKind::Arena, 30.0)] {
            let mut app = clocked(Screen::Editor, PuzzleSpeed::Half);
            let mut editor = app.world_mut().resource_mut::<EditorState>();
            editor.kind = kind;
            editor.mode = Mode::testing(crate::sim::Board::new(9, 9, 1));
            app.update();
            assert!((hz(&app) - want).abs() < 1e-6, "{kind:?}: {} Hz", hz(&app));
        }
    }

    /// And nothing else ever leaves the canonical rate, whatever the dial
    /// says: a versus round is ticked in step with other machines.
    #[test]
    fn every_other_screen_keeps_the_canonical_rate() {
        for screen in [Screen::Versus, Screen::Editor, Screen::Menu] {
            let mut app = clocked(screen, PuzzleSpeed::Half);
            app.update();
            assert!(
                (hz(&app) - 30.0).abs() < 1e-6,
                "{screen:?}: {} Hz",
                hz(&app)
            );
        }
    }

    /// With no window to measure, the scale is the dial's own ratio.
    #[test]
    fn the_ui_scale_follows_the_dial_without_a_window() {
        let mut app = App::new();
        app.insert_resource(GameSettings {
            ui_scale: 80,
            ..GameSettings::default()
        });
        app.init_resource::<UiScale>();
        app.add_systems(Update, apply_accessibility);
        app.update();
        assert!((app.world().resource::<UiScale>().0 - 0.8).abs() < f32::EPSILON);
    }

    /// At 100 the interface fills the window, whatever its size: the same
    /// screen at 720p as at 1080p, only sharper. Never more than the window
    /// has, which is the tighter side's share, since nothing reflows; and
    /// the dial only ever takes some back.
    #[test]
    fn the_interface_fills_the_window_and_the_dial_takes_some_back() {
        assert_eq!(applied_ui_ratio(1.0, DESIGN_W, DESIGN_H), 1.0);
        assert_eq!(applied_ui_ratio(1.0, 1920.0, 1080.0), 1.5);
        assert_eq!(applied_ui_ratio(1.0, 2560.0, 1440.0), 2.0);
        // Wide but short is short: the smaller side decides.
        assert_eq!(applied_ui_ratio(1.0, 3840.0, 800.0), 800.0 / DESIGN_H);
        // A window smaller than the design shrinks to fit.
        let small = applied_ui_ratio(1.0, 1024.0, 576.0);
        assert!((small - 0.8).abs() < 1e-6, "{small}");
        // The dial takes a share of the fit, and asking past it buys nothing.
        assert!((applied_ui_ratio(0.8, 1920.0, 1080.0) - 1.2).abs() < 1e-6);
        assert_eq!(
            applied_ui_ratio(1.5, 1920.0, 1080.0),
            1.5,
            "capped at the fit"
        );
        // A settings file from before, saying 150, reads as the fit.
        let (old, _) = GameSettings::parse("ui_scale: 150\n");
        assert_eq!(old.ui_scale, UI_SCALE_MAX);
    }

    /// A name goes through one gate however it was typed.
    ///
    /// The lobby used to assign the field outright, so a name could be any
    /// length and could carry the `|` that separates names in the save
    /// file. "Ann|Bob" was written as two seats: on the next launch the
    /// player was "Ann", seat two was called "Bob", and whoever really sat
    /// there had been pushed along one.
    #[test]
    fn a_name_cannot_carry_the_save_files_own_punctuation() {
        let caps = crate::app::keycaps::KeyCaps::default();
        let mut settings = GameSettings::default();
        settings.set_name(0, "Ann|Bob");
        settings.set_name(1, "Cass");
        assert_eq!(settings.names[0], "AnnBob", "the separator is not a name");

        let (back, _) = GameSettings::parse(&settings.to_text(&caps));
        assert_eq!(back.names[0], "AnnBob");
        assert_eq!(back.names[1], "Cass", "still in their own seat");
        assert_eq!(back.names[2], "", "and nobody invented behind them");

        // The colon that separates the file's keys goes the same way.
        settings.set_name(0, "a: b");
        assert_eq!(settings.names[0], "a b");

        // And the length cap holds, so what the player sees is what the
        // wire carries and what survives a restart.
        settings.set_name(0, &"W".repeat(48));
        assert_eq!(settings.names[0].chars().count(), NAME_MAX);
    }

    /// A seat with no name of its own reads as the localized default label,
    /// and one with a name reads as the name, everywhere, since every
    /// mention of a seat goes through here.
    #[test]
    fn a_named_seat_answers_to_its_name() {
        let mut settings = GameSettings::default();
        assert_eq!(settings.seat_name(0), "P1");
        assert_eq!(settings.seat_name(3), "P4");
        settings.language = Lang::Fr;
        assert_eq!(settings.seat_name(1), "J2", "the default localizes");
        for ch in "Zoé".chars() {
            settings.push_name_char(1, ch);
        }
        assert_eq!(settings.seat_name(1), "Zoé");
        settings.pop_name_char(1);
        assert_eq!(settings.seat_name(1), "Zo");
        // A seat outside the table never panics (still French, above).
        assert_eq!(settings.seat_name(9), "J10");
    }

    /// Typing is filtered so a name can never break the save file, overflow
    /// the sidebar, or start with a space.
    #[test]
    fn typed_names_are_kept_clean() {
        let mut settings = GameSettings::default();
        for ch in " \n|:Ann|a: ".chars() {
            settings.push_name_char(0, ch);
        }
        assert_eq!(settings.names[0], "Anna ", "separators and controls drop");
        settings.tidy_name(0);
        assert_eq!(settings.names[0], "Anna", "trailing space trimmed away");

        settings.names[1] = String::new();
        for ch in "abcdefghijklmnopqrstuvwxyz".chars() {
            settings.push_name_char(1, ch);
        }
        assert_eq!(settings.names[1].chars().count(), NAME_MAX);

        // A name that is nothing but spaces is no name at all.
        settings.names[2] = "   ".into();
        settings.tidy_name(2);
        assert_eq!(settings.seat_name(2), "P3");

        // And a hand-edited file with a stray separator or an over-long name
        // is cleaned on the way in, not trusted.
        let parsed = GameSettings::parse("names: Anna|Bo:bby|aaaaaaaaaaaaaaaaaaaa\n").0;
        assert_eq!(parsed.names[0], "Anna");
        assert_eq!(parsed.names[1], "Bobby");
        assert_eq!(parsed.names[2].chars().count(), NAME_MAX);
        assert_eq!(parsed.names[3], "", "a missing field stays unnamed");
    }

    /// At the defaults the music sits about level with the effects, not
    /// lost under them, and the slider at the top does not clip the loudest
    /// track. The loudness is the files' own, measured with
    /// `ffmpeg -i FILE -af volumedetect -f null -` (mean over the theme
    /// tracks and over the round's effects); re-measure them when the
    /// tracks are regenerated.
    #[test]
    fn the_music_sits_level_with_the_effects() {
        const TRACK_MEAN_DB: f32 = -23.0;
        const EFFECT_MEAN_DB: f32 = -18.7;
        const LOUDEST_TRACK_PEAK_DB: f32 = -7.1;
        let db = |gain: f32| 20.0 * gain.log10();
        let stock = GameSettings::default();
        let music = TRACK_MEAN_DB + db(stock.music_gain());
        let effects = EFFECT_MEAN_DB + db(stock.sfx_gain());
        let under = effects - music;
        assert!(
            (-2.0..=2.0).contains(&under),
            "the music plays {under:.1} dB under the effects"
        );
        let top = GameSettings {
            music_volume: 100,
            ..GameSettings::default()
        };
        let peak = LOUDEST_TRACK_PEAK_DB + db(top.music_gain());
        assert!(peak <= 0.0, "the music clips at the top: {peak:.1} dB");
    }
}