pinch-points 0.8.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before time runs out
Documentation
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
//! The beach lobby: LAN matchmaking for online Turf War.
//!
//! Hosting binds an ephemeral game port and broadcasts it once a second;
//! every lobby on the network lists discovered hosts and joins one with a
//! number key. Pairing completes through the normal online handshake, then
//! both sides drop into versus. Direct-IP play (`PINCH_JOIN`) still works
//! for beyond-the-LAN matches. When the match ends, the whole table walks
//! back in through [`Homecoming`], sockets still connected, so the next
//! game is a keypress rather than a rediscovery.
//!
//! A beach comes off the list two ways. Normally it says so, on leaving
//! the lobby or on starting the match. Failing that it simply stops being
//! heard, and ages off after [`HOST_TTL`]: nothing can be sent by a process
//! that was killed or a machine that lost power, so the timeout stays
//! underneath the farewell rather than being replaced by it.
//!
//! A host does not listen while it hosts: it cannot join anyone, and the
//! lobby port it would hold is one another instance on the same machine
//! might need.

mod discovery;
mod entry;
mod hosting;
mod joining;
mod terms;
mod ui;
pub use discovery::*;
pub use entry::*;
pub use hosting::*;
pub use joining::*;
pub use terms::*;
pub use ui::*;

use crate::app::cycle::{Cycle, Turn};
use crate::app::i18n::fill;
use crate::app::match_setup::MatchConfig;
use crate::app::menu_ui::Nav;
use crate::app::net::{Invitation, LobbyReturn, Online, OnlineSession, PeerBook};
use crate::app::palette;
use crate::app::settings::GameSettings;
use crate::app::{Screen, VersusPhase};
use crate::sim::MAX_PLAYERS;
use crate::transport::{Announcer, Beacon, Discovery, MatchTerms, NetMsg, UdpTransport};
use bevy::ecs::relationship::RelatedSpawnerCommands;
use bevy::prelude::*;
use std::net::SocketAddr;

/// Also the cadence a running match keeps its beacon up at, which is why
/// it is not private: see `net::OnlineSession::keep_announcing`.
pub(crate) const ANNOUNCE_EVERY: f32 = 1.0;

/// Run a once-a-second clock down by `delta` and say whether it rang; a
/// clock that rang is wound back up to [`ANNOUNCE_EVERY`]. The beacon, the
/// joiner's greeting, and the running match's own copies of both keep time
/// this way.
pub(crate) fn once_a_second(clock: &mut f32, delta: f32) -> bool {
    *clock -= delta;
    if *clock > 0.0 {
        return false;
    }
    *clock = ANNOUNCE_EVERY;
    true
}

/// What a joiner says to a host, every second until it is answered: a
/// `Watch` if it came to look, else a `Hello` carrying its name. The same
/// greeting from the lobby and from a results card, so the host reads the
/// wish to watch the same way wherever it was greeted from.
pub(crate) fn greeting(watching: bool, name: &str) -> NetMsg {
    match watching {
        true => NetMsg::watch(name),
        false => NetMsg::hello(name),
    }
}

/// Where the player stands in the lobby, and everything that goes with
/// standing there.
///
/// One value rather than the four fields that used to say it (`hosting`,
/// `joining`, `watching`, and whether anything had been heard): a field
/// that only means anything in one standing (the host's peers, the
/// joiner's patience with a silent host) is a field that can be read in
/// the wrong one.
pub enum Standing {
    /// Choosing a beach, with W armed or not: armed, the next pick
    /// watches rather than plays.
    Choosing { watching: bool },
    /// Greeting a host, waiting to be given a seat.
    Joining(Joined),
    /// On the air, gathering a table.
    Hosting(Hosted),
}

impl Default for Standing {
    fn default() -> Self {
        Standing::Choosing { watching: false }
    }
}

impl Standing {
    /// Whether there is anybody at the other end: somebody to talk to, a
    /// table to show, and no list worth reading.
    pub fn at_a_beach(&self) -> bool {
        matches!(self, Standing::Joining(_) | Standing::Hosting(_))
    }

    /// A beach going on the air this frame.
    pub fn hosting(announcer: Announcer, transport: UdpTransport) -> Standing {
        Standing::Hosting(Hosted {
            announcer,
            transport,
            peers: PeerBook::default(),
            announce_in: 0.0,
        })
    }
}

/// A beach on the air: its beacon, the game socket gathering the table,
/// and everyone who has turned up on it.
pub struct Hosted {
    pub announcer: Announcer,
    pub transport: UdpTransport,
    /// Everyone on the socket, by its index there: the name its greeting
    /// carried, whether it asked to watch, and how long since it was last
    /// heard from. A joiner re-greets every second for as long as it sits
    /// in the lobby, so silence is the only evidence of leaving there is:
    /// UDP will never say so. Nobody holds a chair here; the plan is dealt
    /// at the launch.
    pub peers: PeerBook,
    announce_in: f32,
}

impl Hosted {
    /// Drop a peer from the socket and from the table, so whoever came
    /// after it moves up one in both.
    fn forget_peer(&mut self, peer: usize) {
        self.transport.forget(peer);
        self.peers.forget(peer);
    }

    /// Ask a peer to leave, and keep it out of this beach.
    pub(super) fn turn_away(&mut self, peer: usize) {
        self.transport.turn_away(peer);
        self.peers.forget(peer);
    }

    /// Peers here to play, the ones who fill the seats. Capped at the five
    /// chairs beside the host's: seats run out long before the socket
    /// does, which takes [`MAX_PEERS`](crate::transport::MAX_PEERS), and
    /// `seat_plan` turns the surplus into onlookers, so a table of eight
    /// would-be rivals reads as "5 aboard".
    pub fn players_aboard(&self) -> usize {
        let seatable = MAX_PLAYERS - 1;
        self.peers
            .iter()
            .filter(|peer| !peer.watch)
            .count()
            .min(seatable)
    }

    /// Peers here to look rather than play.
    fn watchers_aboard(&self) -> usize {
        self.peers.iter().filter(|peer| peer.watch).count()
    }
}

/// A beach being greeted: the socket greeting it, and what has come back.
pub struct Joined {
    pub transport: UdpTransport,
    /// We asked to watch, so we greet with `Watch` and expect no seat back.
    pub watching: bool,
    /// How many are in front of us in line for the next round, once the
    /// host has said we are in one. `None` while there is still a lobby
    /// to be in: a round has to be under way before anybody queues.
    pub queued: Option<u8>,
    hello_in: f32,
    /// Seconds since the host last said anything, and whether it has ever
    /// said anything at all.
    ///
    /// Dialling opens a socket, which on UDP proves nothing: there may be
    /// no machine at that address, or no game on it, or a firewall in the
    /// way, and all three look just like a host who has not started the
    /// round yet. These two are how the difference gets onto the screen.
    host_silence: f32,
    host_answered: bool,
    /// The seed of the round just played, set when a finished match walks
    /// back into this lobby still connected. The host may still be on its
    /// results card, where it re-answers every greeting with that round's
    /// `Start`; without this the lobby would read the repeat as an
    /// invitation and walk straight back into the finished round.
    played_seed: Option<u64>,
    /// The host's dials, from its [`NetMsg::Roster`]. The terms card
    /// paints these rather than this machine's own [`MatchConfig`], which
    /// is nothing to do with the match being joined; `None` until the
    /// first roster lands.
    pub terms: Option<MatchTerms>,
    /// The round as it stands, arriving in parts, for a watcher who
    /// greeted a beach mid-round (`net::catch_up`).
    catching_up: crate::app::net::catch_up::Assembly,
    /// Joining as a bot (route 1): the seat's name, "Greedy (Ana)",
    /// greeted with the flag that says a bot will drive it.
    pub bot: Option<String>,
    /// The beacon id of the beach this is, once known: taken from its row
    /// when it was picked off the list, or learnt from the row that
    /// matches its address. Rows are found by it rather than by address,
    /// because one beach arrives from two addresses (the broadcast and the
    /// loopback copy) and the list keeps whichever it heard first.
    pub beach: Option<u64>,
}

impl Joined {
    /// A beach dialled this frame: calling, not aboard, since nothing has
    /// answered yet and on UDP an open socket is no evidence that anything
    /// will.
    pub fn dialled(transport: UdpTransport, watching: bool) -> Joined {
        Joined {
            transport,
            watching,
            queued: None,
            hello_in: ANNOUNCE_EVERY,
            host_silence: 0.0,
            host_answered: false,
            played_seed: None,
            terms: None,
            catching_up: Default::default(),
            bot: None,
            beach: None,
        }
    }

    /// A beach walked back into from a finished round: the host was
    /// talking moments ago, so this is a beach, not an unanswered address,
    /// until the silence rule says otherwise, and it greets again at once.
    pub fn returned(
        transport: UdpTransport,
        watching: bool,
        played_seed: u64,
        bot: Option<String>,
    ) -> Joined {
        Joined {
            transport,
            watching,
            queued: None,
            hello_in: 0.0,
            host_silence: 0.0,
            host_answered: true,
            played_seed: Some(played_seed),
            terms: None,
            catching_up: Default::default(),
            bot,
            beach: None,
        }
    }

    /// What this peer greets the host with: a bot's seat says so.
    pub fn greeting(&self, name: &str) -> NetMsg {
        match &self.bot {
            Some(seat) => NetMsg::hello_bot(seat),
            None => greeting(self.watching, name),
        }
    }

    /// The seed of the round this table walked out of, if it did.
    pub fn played_seed(&self) -> Option<u64> {
        self.played_seed
    }
}

/// What the player was trying to do when they were asked to name
/// themselves first.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Intent {
    Host,
    /// Take the beach that was on the cursor's row when the name was
    /// asked, by its address: the list re-sorts by name every frame, so a
    /// row number held while a name is typed can name another beach by
    /// the time Enter is pressed.
    Join(SocketAddr),
    /// Take the beach at this address, which is on no row: it was typed
    /// out because no beacon from it ever arrived.
    Dial(SocketAddr),
    /// Take that beach as a bot (route 1): a doorway first. By address,
    /// as `Join` is.
    JoinBot(SocketAddr),
}

/// One line in the feed, kept as who said it and what, rather than as the
/// finished string.
///
/// The two halves are painted differently, a name in its seat's colour
/// and a notice slanted, and a formatted `"who: line"` would have to be
/// picked apart at a colon the player may well have typed themselves.
#[derive(Default, Clone, PartialEq, Eq, Debug)]
pub struct Said {
    /// Who said it, or empty when the lobby itself is speaking: somebody
    /// arriving, somebody leaving.
    pub who: String,
    pub line: String,
}

impl Said {
    /// Whether this is the room talking rather than a player, which is
    /// what the slant on it says.
    pub fn is_notice(&self) -> bool {
        self.who.is_empty()
    }
}

#[derive(Resource, Default)]
pub struct LobbyState {
    discovery: Option<Discovery>,
    /// Where the player stands, and everything that goes with it.
    pub standing: Standing,
    pub hosts: Vec<HostEntry>,
    /// The beach under the cursor, remembered by address rather than by
    /// position. The list re-sorts as beaches come and go and as they fill
    /// up, so an index would silently point at a different game between the
    /// frame a player reads it and the frame they press Enter.
    pub selected: Option<SocketAddr>,
    /// First row shown, so a list longer than [`LIST_ROWS`] can scroll.
    pub scroll: usize,
    /// What has been said in this lobby, oldest first, capped at
    /// [`CHAT_LINES`]. Cleared with everything else on leaving.
    pub chat: Vec<Said>,
    /// What the keyboard is spelling out, if anything. While this is
    /// `Some`, every other lobby key is text.
    pub typing: Option<Typing>,
    /// Which dial the host has under the cursor.
    pub dial: usize,
    /// Who is at this beach, as this peer knows it: computed on the host,
    /// and told to a joiner by [`NetMsg::Roster`], since a joiner has only
    /// ever spoken to the host and would otherwise think itself alone.
    pub table: Vec<String>,
    /// What holds each place in [`Self::table`], so a bot at the beach
    /// wears the robot on the card that lists who is there.
    pub table_kinds: Vec<crate::sim::SeatKind>,
    /// What this beach is called, once its host has said. Announced in
    /// place of the host's own name: the list is choosing between games.
    /// Beside the standing rather than inside [`Hosted`] because it is
    /// asked for before the beach goes on the air, and kept after it comes
    /// off so the next one is pre-filled.
    pub game_name: String,
    pub feedback: String,
    auto_done: bool,
    /// The host pressed K and is picking whom to ask to leave: the next
    /// number is a seat at the table, Esc is never mind.
    pub kicking: bool,
    /// The string a bot connects straight to this beach with (route 2),
    /// while the host says bots are welcome and there is a chair for one.
    pub bot_string: Option<String>,
}

impl LobbyState {
    /// A line of chat as it came off the wire, into the feed: both halves
    /// tidied on the way, since a stranger on the LAN wrote them.
    pub fn hear(&mut self, name: &crate::transport::WireName, text: &crate::transport::WireChat) {
        let who = crate::transport::name_from_wire(name);
        let line = crate::transport::chat_from_wire(text);
        self.say(&who, &line);
    }

    /// Add a line to the feed, dropping the oldest to stay within
    /// [`CHAT_LINES`].
    pub fn say(&mut self, who: &str, line: &str) {
        if line.is_empty() {
            return;
        }
        self.chat.push(Said {
            who: who.to_string(),
            line: line.to_string(),
        });
        let over = self.chat.len().saturating_sub(CHAT_LINES);
        self.chat.drain(..over);
    }

    /// Where the player stands, the question most of the lobby is really
    /// asking.
    pub fn standing(&self) -> &Standing {
        &self.standing
    }

    /// Whether this lobby has anyone to say anything to.
    pub fn can_chat(&self) -> bool {
        self.standing.at_a_beach()
    }

    pub fn hosting(&self) -> bool {
        self.hosted().is_some()
    }

    /// The beach this lobby has on the air, if it is hosting one.
    pub fn hosted(&self) -> Option<&Hosted> {
        match &self.standing {
            Standing::Hosting(hosted) => Some(hosted),
            Standing::Choosing { .. } | Standing::Joining(_) => None,
        }
    }

    fn hosted_mut(&mut self) -> Option<&mut Hosted> {
        match &mut self.standing {
            Standing::Hosting(hosted) => Some(hosted),
            Standing::Choosing { .. } | Standing::Joining(_) => None,
        }
    }

    /// The beach this lobby is greeting, if it is greeting one.
    pub fn joined(&self) -> Option<&Joined> {
        match &self.standing {
            Standing::Joining(joined) => Some(joined),
            Standing::Choosing { .. } | Standing::Hosting(_) => None,
        }
    }

    fn joined_mut(&mut self) -> Option<&mut Joined> {
        match &mut self.standing {
            Standing::Joining(joined) => Some(joined),
            Standing::Choosing { .. } | Standing::Hosting(_) => None,
        }
    }

    /// Whoever is at the other end, host or table, to say something to.
    fn transport(&self) -> Option<&UdpTransport> {
        match &self.standing {
            Standing::Hosting(hosted) => Some(&hosted.transport),
            Standing::Joining(joined) => Some(&joined.transport),
            Standing::Choosing { .. } => None,
        }
    }

    /// Whether this player means to watch rather than play: W armed while
    /// choosing, or a beach greeted with `Watch`. A host plays.
    pub fn watching(&self) -> bool {
        match &self.standing {
            Standing::Choosing { watching } => *watching,
            Standing::Joining(joined) => joined.watching,
            Standing::Hosting(_) => false,
        }
    }

    /// Arm or disarm watching, wherever it can still be changed: while
    /// choosing, and on a greeting already in flight, which the dev hook
    /// sets the moment it joins.
    fn set_watching(&mut self, on: bool) {
        match &mut self.standing {
            Standing::Choosing { watching } => *watching = on,
            Standing::Joining(joined) => joined.watching = on,
            Standing::Hosting(_) => {}
        }
    }

    /// Back to choosing, keeping W armed as it was.
    ///
    /// The beach's conversation and its table go with it. Left behind,
    /// a player put out of one beach (kicked, unanswered, on another
    /// build) carried its chat into the next one they joined, and a host
    /// sends its chat to every arrival, so hosting next handed the old
    /// beach's talk, kick notice and all, to strangers.
    fn let_go(&mut self) {
        let watching = self.watching();
        self.standing = Standing::Choosing { watching };
        self.chat.clear();
        self.table.clear();
        self.table_kinds.clear();
    }

    /// The table as the lobby knows it: the host first, then every peer
    /// that came to play, by the name its greeting carried.
    pub fn roster(&self, tr: &crate::app::i18n::Tr, me: &str) -> Vec<String> {
        let nobody = PeerBook::default();
        let peers = self.hosted().map_or(&nobody, |hosted| &hosted.peers);
        table_of(peers, tr, me)
    }

    /// The beach this joiner is at, as its beacon described it: by the
    /// address it dialled, not the cursor, which a digit or a typed address
    /// never moved.
    pub fn joined_entry(&self) -> Option<&HostEntry> {
        let joined = self.joined()?;
        match joined.beach {
            Some(id) => self.hosts.iter().find(|host| host.id == id),
            None => {
                let there = joined.transport.peer_addr()?;
                self.hosts.iter().find(|host| host.addr == there)
            }
        }
    }

    /// What the beach under the cursor is called, for a card that is about
    /// to join it: its name, or its address when it gave none.
    pub fn joining_beach(&self) -> Option<String> {
        let host = &self.hosts[self.selected_index()?];
        Some(match host.name.is_empty() {
            true => host.addr.to_string(),
            false => host.name.clone(),
        })
    }

    /// What holds each place in [`Self::roster`]: the host a person, every
    /// peer that came to play whatever its greeting said.
    pub fn roster_kinds(&self) -> Vec<crate::sim::SeatKind> {
        let nobody = PeerBook::default();
        let peers = self.hosted().map_or(&nobody, |hosted| &hosted.peers);
        std::iter::once(crate::sim::SeatKind::Human)
            .chain(
                peers
                    .iter()
                    .filter(|peer| !peer.watch)
                    .map(|peer| match peer.bot {
                        true => crate::sim::SeatKind::Bot,
                        false => crate::sim::SeatKind::Human,
                    }),
            )
            .collect()
    }

    /// Where the cursor sits in the current list, if the beach it names is
    /// still on the air.
    pub fn selected_index(&self) -> Option<usize> {
        let want = self.selected?;
        self.hosts.iter().position(|host| host.addr == want)
    }

    /// Keep the cursor on something real, and keep it on screen.
    ///
    /// Called after every refresh: beaches appear, fill up and go away
    /// while the list is being read, and a cursor pointing at one that has
    /// gone should fall to a neighbour rather than to whatever slid into
    /// its row.
    fn settle_cursor(&mut self) {
        if self.hosts.is_empty() {
            self.selected = None;
            self.scroll = 0;
            return;
        }
        let at = match self.selected_index() {
            Some(at) => at,
            None => {
                // The beach it named is gone: take the first, which under a
                // stable sort is a predictable place to land.
                self.selected = self.hosts.first().map(|host| host.addr);
                0
            }
        };
        // Scroll only as far as it must to keep the cursor in view.
        self.scroll = self.scroll.min(at).max(at.saturating_sub(LIST_ROWS - 1));
        self.scroll = self.scroll.min(self.hosts.len().saturating_sub(1));
    }

    /// Step the cursor, wrapping, and follow it with the window.
    fn step_cursor(&mut self, nav: Nav) {
        if self.hosts.is_empty() {
            return;
        }
        let len = self.hosts.len();
        let at = self.selected_index().unwrap_or(0);
        let next = crate::app::menu_ui::step(nav, at, len);
        self.selected = Some(self.hosts[next].addr);
        self.settle_cursor();
    }
}

/// The table as a host knows it: the host first, then every peer that
/// came to play, by the name its greeting carried. Onlookers are not at
/// it, and a peer that has not said what to call it yet still holds its
/// chair, under a seat label rather than a blank.
pub(super) fn table_of(peers: &PeerBook, tr: &crate::app::i18n::Tr, me: &str) -> Vec<String> {
    let mine = match me.trim().is_empty() {
        true => crate::app::seat_label(tr, 0),
        false => me.to_string(),
    };
    let mut table = vec![mine];
    for peer in peers.iter().filter(|peer| !peer.watch) {
        table.push(match peer.name.is_empty() {
            true => crate::app::seat_label(tr, table.len() as u8),
            false => peer.name.clone(),
        });
    }
    table
}

/// A finished match walking its table back into the lobby, still
/// connected: the results card's Enter fills this, the screen switches,
/// and [`enter_lobby`] - which otherwise starts from nothing - stands the
/// beach back up from it.
#[derive(Resource, Default)]
pub struct Homecoming(pub Option<LobbyReturn>);

/// Stand the beach back up from what the match handed back: the host goes
/// straight back on the air as open, a joiner back to its chair (or the
/// watching), both on the sockets the round was played over.
fn settle_back_in(
    state: &mut LobbyState,
    returned: LobbyReturn,
    tr: &'static crate::app::i18n::Tr,
) {
    let LobbyReturn {
        announcer,
        transport,
        game_name,
        mut peers,
        watching,
        host,
        played_seed,
        bot,
    } = returned;
    if host {
        // A host that never announced (the direct pair) has no beach to
        // stand back up, and `from_lobby` keeps it from coming this way.
        let Some(announcer) = announcer else { return };
        // One row per peer the socket still has, no more and no fewer:
        // the rows are indexed by the socket's own list.
        peers.fit(transport.peer_count());
        peers.hush();
        state.game_name = game_name;
        // Back on the air this frame, as open: the round the beacon was
        // calling "running" is over.
        state.standing = Standing::Hosting(Hosted {
            announcer,
            transport,
            peers,
            announce_in: 0.0,
        });
    } else {
        state.standing = Standing::Joining(Joined::returned(transport, watching, played_seed, bot));
        state.feedback = match watching {
            true => tr.lobby_watching,
            false => tr.lobby_aboard,
        }
        .to_string();
    }
}

pub fn enter_lobby(
    mut commands: Commands,
    mut state: ResMut<LobbyState>,
    mut homecoming: ResMut<Homecoming>,
    mut notice: ResMut<crate::app::RoundNotice>,
    settings: Res<GameSettings>,
    art: Res<crate::app::art::Art>,
) {
    *state = LobbyState::default();
    spawn_lobby_ui(&mut commands, settings.tr(), &LobbyArt::from_art(&art));
    if let Some(returned) = homecoming.0.take() {
        settle_back_in(&mut state, returned, settings.tr());
    }
    // Word of the round just left, for somebody the round put out rather
    // than let go: the host walked off, or this peer was dropped. The
    // menu's own slot for it is no use to a player who was never sent
    // there, and taken rather than read, so it is not still hanging about
    // the next time the menu comes up.
    let why = std::mem::take(&mut notice.0);
    if !why.is_empty() {
        // The status line, and not the feed: the feed panel is not even
        // on screen while a player is browsing, and a line about the
        // beach they were thrown out of would surface inside the next
        // beach's conversation. Nothing on the browsing path writes this
        // slot, so the reason stays put until they pick something.
        state.feedback = why;
    }
    // A host does not listen while it hosts (see the module doc), which a
    // table walking back in together arrives already doing.
    if state.hosting() {
        return;
    }
    match Discovery::bind() {
        Ok(discovery) => {
            state.discovery = Some(discovery);
            if state.feedback.is_empty() {
                state.feedback = settings.tr().lobby_listening.into();
            }
        }
        Err(e) => {
            if state.feedback.is_empty() {
                state.feedback = format!("discovery unavailable: {e}");
            }
        }
    }
}

pub fn exit_lobby(mut state: ResMut<LobbyState>) {
    say_goodbye(&state);
    *state = LobbyState::default();
}

/// The ways out of the lobby a key can take: to another screen, or
/// through a doorway for a bot.
#[derive(bevy::ecs::system::SystemParam)]
pub struct LobbyExits<'w> {
    next_screen: ResMut<'w, NextState<Screen>>,
    bots: ResMut<'w, crate::app::bot_seats::BotSeats>,
    /// Whether a round is under way, which a joiner walking into the
    /// arena is part of before the screen changes.
    online: Res<'w, Online>,
}

/// B on a beach: open a doorway for the bot that will join it.
fn open_door_for(
    state: &mut LobbyState,
    bots: &mut crate::app::bot_seats::BotSeats,
    tr: &'static crate::app::i18n::Tr,
    at: usize,
) {
    let Some(host) = state.hosts.get(at) else {
        return;
    };
    if !host.bots {
        state.feedback = tr.lobby_no_bots.to_string();
        return;
    }
    if !host.has_room() {
        state.feedback = tr.lobby_beach_full.to_string();
        return;
    }
    let addr = host.addr;
    state.selected = Some(addr);
    match crate::app::bot_seats::Doorway::open() {
        Ok(mut door) => {
            door.seat_bots(&[0]);
            bots.door = Some(door);
            bots.join_to = Some(addr);
            bots.waiting = Some(crate::app::bot_seats::Waiting::Join);
        }
        Err(e) => state.feedback = fill(tr.door_could_not_listen, &[("e", &e.to_string())]),
    }
}

/// Lobby input: host, join by number, leave, and say something.
pub fn lobby_input(
    keyboard: crate::app::keycaps::Keyboard,
    mut typed: MessageReader<bevy::input::keyboard::KeyboardInput>,
    mut settings: ResMut<GameSettings>,
    dials: crate::app::match_setup::Dials,
    mut state: ResMut<LobbyState>,
    exits: LobbyExits,
    pads: Query<&Gamepad>,
) {
    let crate::app::keycaps::Keyboard { keys, caps } = keyboard;
    let LobbyExits {
        mut next_screen,
        mut bots,
        online,
    } = exits;
    bots.leave_the_beach(state.joined().is_some() || online.0.is_some());
    // A doorway card is up for a bot about to join a beach: its keys are
    // its own (see `bot_seats::door_input`), and the moment its bot is in,
    // this game dials the beach as that bot's seat.
    if bots.waiting.is_some() {
        typed.clear();
        let tr = settings.tr();
        if let Some(door) = &bots.door
            && door.ready()
            && let Some(addr) = bots.join_to
        {
            let name = door.named_for(tr, &settings.names[0]);
            bots.waiting = None;
            dial_as(&mut state, &settings, tr, addr, name);
        }
        return;
    }
    let crate::app::match_setup::Dials {
        mut config,
        beaches,
    } = dials;
    let tr = settings.tr();
    let tr: &'static crate::app::i18n::Tr = tr;
    // A pad's North is quick chat: the one way a player with no keyboard
    // has to say anything at all.
    let quick = pads
        .iter()
        .any(|pad| pad.just_pressed(GamepadButton::North));
    // Set when an answer finishes and the thing it was blocking can now go
    // ahead in the same frame.
    let mut intent: Option<Intent> = None;
    // While anything is being typed the keyboard is text and nothing else:
    // H would host, W would arm watching, and a digit would join a beach,
    // none of which anyone means halfway through "wait for me".
    match drive_typing(
        &keys,
        &mut typed,
        quick,
        &mut settings,
        &caps,
        &mut state,
        tr,
    ) {
        // The keyboard is busy: every other key in this lobby is text.
        Typed::Taken => return,
        // An answer finished and freed something to happen this frame.
        Typed::Unblocked(unblocked) => intent = Some(unblocked),
        Typed::Nothing => {}
    }
    // The reader must be drained even when nothing is being typed, or the
    // first line composed picks up every keystroke since the lobby opened.
    typed.clear();
    // T for talk, once there is anyone to talk to.
    if intent.is_none() && caps.just_pressed(&keys, 'T') && state.can_chat() {
        state.typing = Some(Typing::chat());
        return;
    }
    // North for the same line, saying the first quick-chat phrase already.
    if intent.is_none() && quick && state.can_chat() {
        state.typing = Some(Typing::chat_saying(tr.quick_chat[0]));
        return;
    }
    // J for a beach the list will never show: one whose beacons the
    // network drops, or that is a subnet away. Only while browsing, since
    // from a beach you are already at there is nothing to dial, and never
    // over a question already on screen, which a finished answer may have
    // opened earlier in this same frame.
    if intent.is_none()
        && keys.just_pressed(KeyCode::KeyJ)
        && !state.standing().at_a_beach()
        && state.typing.is_none()
    {
        state.typing = Some(Typing::address(&settings.last_beach));
        return;
    }
    let auto_host = crate::app::dev::auto_host_quota().is_some() && !state.auto_done;
    // PINCH_LOBBY_WATCH joins the first host found as a spectator, which is
    // the only way to watch: a session replays from frame zero, so an
    // onlooker has to be in the lobby with everyone else.
    let auto_watch = crate::app::dev::auto_watch();
    let auto_join =
        (crate::app::dev::auto_join() || auto_watch) && !state.auto_done && !state.hosts.is_empty();
    if auto_watch {
        state.set_watching(true);
    }
    // B: join the beach under the cursor as a bot, through a doorway. The
    // dev hook presses it on the first beach heard.
    if crate::app::dev::auto_join_bot() && !state.auto_done && !state.hosts.is_empty() {
        state.auto_done = true;
        open_door_for(&mut state, &mut bots, tr, 0);
        return;
    }
    let join_bot = match intent {
        // Gone off the air while the name was typed: nothing is taken in
        // its place, and the player is told why.
        Some(Intent::JoinBot(addr)) => {
            let at = state.hosts.iter().position(|host| host.addr == addr);
            if at.is_none() {
                state.feedback = tr.lobby_host_closed.to_string();
            }
            at
        }
        _ if intent.is_none()
            && caps.just_pressed(&keys, 'B')
            && !state.standing().at_a_beach()
            && state.typing.is_none() =>
        {
            state.selected_index()
        }
        _ => None,
    };
    if let Some(at) = join_bot {
        if settings.names[0].trim().is_empty() && intent.is_none() {
            state.typing = Some(
                Typing::player_name(Intent::JoinBot(state.hosts[at].addr), &settings.names[0])
                    .or_suggest(|| suggested_name(tr)),
            );
        } else {
            open_door_for(&mut state, &mut bots, tr, at);
        }
        return;
    }
    let step = host_step(HostAsk {
        answered: intent == Some(Intent::Host),
        pressed_h: caps.just_pressed(&keys, 'H'),
        busy: state.standing().at_a_beach(),
        auto: auto_host,
    });
    if step == HostStep::Ask {
        // Stopped at the door until we know who is asking and what the
        // beach is to be called. Both are what the rest of the hall reads.
        state.typing = Some(
            Typing::player_name(Intent::Host, &settings.names[0]).or_suggest(|| suggested_name(tr)),
        );
        return;
    }
    if step == HostStep::Go && !state.standing.at_a_beach() {
        state.auto_done = auto_host;
        match (
            Announcer::new(crate::app::clock::fresh_seed()),
            UdpTransport::host(0),
        ) {
            (Ok(announcer), Ok(transport)) => {
                state.feedback = match transport.local_addr() {
                    Ok(addr) => fill(tr.lobby_hosting, &[("p", &addr.port().to_string())]),
                    Err(_) => tr.lobby_hosting_noport.into(),
                };
                // Where this beach is, in the feed rather than the status
                // line: the status line is taken over by the rival count
                // the moment somebody arrives, and this is the number a
                // friend on a network that eats broadcasts has to be told
                // before they can dial it.
                if let Some(here) = address_here(&transport) {
                    let notice = fill(tr.lobby_hosting_at, &[("a", &here)]);
                    state.say("", &notice);
                }
                state.standing = Standing::hosting(announcer, transport);
                // Stop listening. A host cannot join anyone, and holding a
                // lobby port it will never read would deny one to another
                // instance on the same machine. It also stops the host
                // hearing its own beacon come back round the loopback and
                // listing itself.
                state.discovery = None;
                state.hosts.clear();
            }
            (Err(e), _) | (_, Err(e)) => {
                state.feedback = fill(tr.lobby_could_not_host, &[("e", &e.to_string())]);
            }
        }
    }
    // K: ask somebody to leave. The next number names them, Esc does not.
    if state.hosting() && state.typing.is_none() && caps.just_pressed(&keys, 'K') {
        state.kicking = true;
        return;
    }
    if state.kicking {
        if keys.just_pressed(KeyCode::Escape) || !state.hosting() {
            state.kicking = false;
            return;
        }
        if let Some(at) =
            crate::app::menu_ui::number_pressed(&keys, crate::app::menu_ui::NUMBER_KEYS.len())
        {
            state.kicking = false;
            ask_to_leave(&mut state, &mut bots, tr, at + 1);
        }
        return;
    }
    if state.hosting() {
        turn_the_dials(
            &keys,
            &mut settings,
            &caps,
            &mut config,
            &mut state,
            &beaches,
        );
    }
    if !state.standing.at_a_beach() {
        walk_the_list(&keys, &mut state);
    }
    take_a_beach(&keys, &settings, &mut state, tr, intent, auto_join);
    if keys.just_pressed(KeyCode::KeyW)
        && let Standing::Choosing { watching } = &mut state.standing
    {
        *watching = !*watching;
    }
    if keys.just_pressed(KeyCode::Escape) {
        next_screen.set(Screen::Menu);
    }
}

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

    fn addr(last: u8) -> SocketAddr {
        format!("10.0.0.{last}:47777").parse().expect("addr")
    }

    /// Both greetings say who is greeting. The watcher's did not, and the
    /// host has two uses for a name it never got: the feed, which
    /// announced every player and no spectator at all, and the check on
    /// who a chat line claims to be from, which a nameless peer walks
    /// straight through.
    #[test]
    fn a_spectator_greets_by_name_like_everybody_else() {
        assert_eq!(
            greeting(true, "Dee"),
            NetMsg::Watch {
                name: crate::transport::wire_name("Dee")
            },
        );
        assert_eq!(
            greeting(false, "Bo"),
            NetMsg::Hello {
                name: crate::transport::wire_name("Bo"),
                bot: false,
            },
        );
    }

    /// A beach on the air, as `refresh_hosts` hears it.
    fn open(last: u8) -> (SocketAddr, Beacon) {
        beach(last, "", 1, 6, false)
    }

    /// The same, said in full.
    fn beach(last: u8, name: &str, taken: u8, seats: u8, running: bool) -> (SocketAddr, Beacon) {
        (
            addr(last),
            Beacon::Here {
                id: u64::from(last),
                name: name.to_string(),
                host: "Sam".to_string(),
                taken,
                seats,
                running,
                bots: false,
                full: false,
            },
        )
    }

    /// A beach that keeps announcing stays on the list; one that goes quiet
    /// ages off it, so the join list only ever offers live hosts.
    #[test]
    fn hosts_expire_when_they_stop_announcing() {
        let mut hosts = Vec::new();
        refresh_hosts(&mut hosts, &[open(7)], 0.0);
        assert_eq!(hosts.len(), 1, "a new beach joins the list");

        // Heard again: still fresh, and not duplicated.
        refresh_hosts(&mut hosts, &[open(7)], 1.0);
        assert_eq!(hosts.len(), 1);
        assert_eq!(hosts[0].age, 0.0);

        // Silence, but not yet long enough.
        refresh_hosts(&mut hosts, &[], HOST_TTL - 0.5);
        assert_eq!(hosts.len(), 1, "given a moment's grace");

        // Silence past the deadline.
        refresh_hosts(&mut hosts, &[], 1.0);
        assert!(hosts.is_empty(), "a host that quit leaves the list");
    }

    /// A host that leaves properly is gone at once, rather than sitting in
    /// the list for the whole timeout. The ageing stays underneath for the
    /// exits that cannot be announced: a killed process, a pulled cable.
    #[test]
    fn a_farewell_clears_a_host_without_waiting_out_the_timeout() {
        let mut hosts = Vec::new();
        refresh_hosts(&mut hosts, &[open(1), open(2)], 0.0);
        assert_eq!(hosts.len(), 2);

        // No time passes at all, and it is still gone.
        refresh_hosts(&mut hosts, &[(addr(1), Beacon::Closing { id: 1 })], 0.0);
        assert_eq!(hosts.len(), 1, "the one that said goodbye left");
        assert_eq!(hosts[0].addr, addr(2), "and only that one");

        // A farewell for a beach nobody had listed is simply nothing.
        refresh_hosts(&mut hosts, &[(addr(9), Beacon::Closing { id: 9 })], 0.0);
        assert_eq!(hosts.len(), 1);

        // Opened and closed inside one frame: the order it arrived in wins,
        // so a beach that is already gone is never briefly offered.
        refresh_hosts(
            &mut hosts,
            &[open(5), (addr(5), Beacon::Closing { id: 5 })],
            0.0,
        );
        assert!(
            hosts.iter().all(|host| host.addr != addr(5)),
            "a beach that opened and shut in one frame is not listed"
        );
        // And the same two the other way round is a beach that came back.
        refresh_hosts(
            &mut hosts,
            &[(addr(5), Beacon::Closing { id: 5 }), open(5)],
            0.0,
        );
        assert!(hosts.iter().any(|host| host.addr == addr(5)));
    }

    /// What a host reads while it waits: one rival is not "1 rivals",
    /// onlookers are named separately from players, and the AI is only
    /// ever offered the chairs left over.
    #[test]
    fn the_gathering_line_counts_who_is_actually_there() {
        use crate::app::i18n::EN;
        let none = MatchConfig {
            bots: 0,
            ..MatchConfig::default()
        };
        assert_eq!(gathering_feedback(&EN, &none, 1, 0), EN.lobby_rivals_one);
        assert!(gathering_feedback(&EN, &none, 3, 0).contains('3'));

        // Onlookers are counted, and counted apart from the players.
        let watched = gathering_feedback(&EN, &none, 2, 2);
        assert!(watched.len() > gathering_feedback(&EN, &none, 2, 0).len());

        // The AI takes what the table leaves and no more, however many the
        // host asked for. Five aboard plus the host is a full beach.
        let greedy = MatchConfig {
            bots: 5,
            ..MatchConfig::default()
        };
        let full = gathering_feedback(&EN, &greedy, MAX_PLAYERS - 1, 0);
        assert_eq!(
            full,
            gathering_feedback(&EN, &none, MAX_PLAYERS - 1, 0),
            "no room for a bot, so no promise of one"
        );
    }

    /// A hosting lobby really does put a farewell on the wire, and a lobby
    /// that never hosted has nothing to say. Both ways out of hosting,
    /// leaving the screen and starting the match, go through this call.
    #[test]
    fn a_hosting_lobby_announces_its_own_departure() {
        let mut discovery = Discovery::bind().expect("bind lobby port");
        let mut state = LobbyState::default();
        // Beacons go to every lobby port on the machine, and the rest of the
        // suite is announcing while this runs, so "heard nothing at all" is
        // not a fact about this test. Take the game port first and judge
        // every packet by whether it names ours.
        let transport = UdpTransport::host(0).expect("game socket");
        let port = transport.local_addr().expect("addr").port();
        let mine = |heard: Vec<(SocketAddr, Beacon)>| {
            heard
                .into_iter()
                .filter(|(addr, _)| addr.port() == port)
                .collect::<Vec<_>>()
        };

        // Nothing hosted, nothing said.
        say_goodbye(&state);
        std::thread::sleep(std::time::Duration::from_millis(30));
        assert!(
            mine(discovery.poll()).is_empty(),
            "a joiner has no beach to close"
        );

        state.standing = Standing::hosting(Announcer::new(0xB0A7).expect("announcer"), transport);
        say_goodbye(&state);
        let mut heard = Vec::new();
        for _ in 0..20 {
            std::thread::sleep(std::time::Duration::from_millis(10));
            heard.extend(mine(discovery.poll()));
            if !heard.is_empty() {
                break;
            }
        }
        let (_, beacon) = heard.first().expect("the farewell went out");
        assert!(matches!(beacon, Beacon::Closing { .. }), "{beacon:?}");
    }

    /// Several beaches can be on the air at once, each aging on its own.
    #[test]
    fn hosts_age_independently() {
        let mut hosts = Vec::new();
        refresh_hosts(&mut hosts, &[open(1), open(2)], 0.0);
        assert_eq!(hosts.len(), 2);
        // Only the first keeps talking.
        refresh_hosts(&mut hosts, &[open(1)], HOST_TTL - 0.1);
        assert_eq!(hosts.len(), 2, "the quiet one is on its last legs");
        refresh_hosts(&mut hosts, &[open(1)], 0.2);
        assert_eq!(hosts.len(), 1);
        assert_eq!(hosts[0].addr, addr(1));
    }
}

#[cfg(test)]
mod homecoming_tests {
    use super::*;
    use crate::app::i18n::EN;
    use crate::app::net::PeerBook;

    use crate::app::lobby::hosting::peers_named;

    /// A hosting socket with `peers` joiners registered on it, as the one
    /// coming back from a match really is: the count is the socket's own,
    /// so a table walking home has to arrive with its peers still on it.
    /// The joiner sockets are handed back to be kept alive; dropping them
    /// would close the far end mid-test.
    fn with_peers(peers: usize) -> (UdpTransport, Vec<UdpTransport>) {
        let mut transport = UdpTransport::host(0).expect("game socket");
        let port = transport.local_addr().expect("addr").port();
        let mut joiners = Vec::new();
        for want in 1..=peers {
            let joiner = UdpTransport::join(("127.0.0.1", port)).expect("join");
            joiner.send(NetMsg::hello("someone"));
            for _ in 0..40 {
                std::thread::sleep(std::time::Duration::from_millis(5));
                let _ = transport.recv_all();
                if transport.peer_count() >= want {
                    break;
                }
            }
            assert_eq!(transport.peer_count(), want, "peer {want} registered");
            joiners.push(joiner);
        }
        (transport, joiners)
    }

    /// A host walks back in still on the air: the same socket, the same
    /// beach name, the peers still counted, and the list it does not read
    /// while hosting left unbound.
    #[test]
    fn a_host_comes_home_still_hosting() {
        let (transport, _joiners) = with_peers(2);
        let port = transport.local_addr().expect("addr").port();
        let mut state = LobbyState::default();
        settle_back_in(
            &mut state,
            LobbyReturn {
                announcer: Some(Announcer::new(0xB0A7).expect("announcer")),
                transport,
                game_name: "Room 3".into(),
                peers: peers_named(&["Bo", "Cy"], &[1]),
                watching: false,
                host: true,
                played_seed: 42,
                bot: None,
            },
            &EN,
        );
        assert!(state.hosting());
        assert_eq!(state.game_name, "Room 3");
        let hosted = state.hosted().expect("hosting");
        assert_eq!(
            hosted.transport.local_addr().expect("addr").port(),
            port,
            "the socket the table is still talking to"
        );
        assert_eq!(hosted.announce_in, 0.0, "back on the air this frame");
        assert_eq!(
            state.roster(&EN, "Anna"),
            ["Anna", "Bo"],
            "the table as it stood, minus the one watching"
        );
    }

    /// The rows a host is handed back have to be one per peer the socket
    /// still has, or a row and the peer it was kept for come apart the
    /// first time somebody leaves.
    #[test]
    fn a_short_name_list_is_padded_to_the_peers_it_indexes() {
        let (transport, _joiners) = with_peers(2);
        let mut state = LobbyState::default();
        settle_back_in(
            &mut state,
            LobbyReturn {
                announcer: Some(Announcer::new(1).expect("announcer")),
                transport,
                game_name: String::new(),
                // Fewer names than the socket knows peers.
                peers: peers_named(&["Bo"], &[0]),
                watching: false,
                host: true,
                played_seed: 0,
                bot: None,
            },
            &EN,
        );
        let hosted = state.hosted().expect("hosting");
        assert_eq!(
            hosted.peers.len(),
            hosted.transport.peer_count(),
            "one row per peer the socket knows"
        );
    }

    /// A joiner walks back in already aboard: the socket it played over,
    /// the seed it played on, and no "calling..." for a host that was
    /// talking to it a moment ago.
    #[test]
    fn a_joiner_comes_home_aboard() {
        let mut state = LobbyState::default();
        settle_back_in(
            &mut state,
            LobbyReturn {
                announcer: None,
                transport: UdpTransport::join(("127.0.0.1", 47999)).expect("join"),
                game_name: String::new(),
                peers: PeerBook::default(),
                watching: true,
                host: false,
                played_seed: 42,
                bot: None,
            },
            &EN,
        );
        let joined = state.joined().expect("joining");
        assert!(joined.watching, "still watching");
        assert_eq!(joined.played_seed(), Some(42));
        assert!(joined.host_answered, "the host was talking a moment ago");
        assert_eq!(state.feedback, EN.lobby_watching);
    }
}

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

    /// The feed keeps the last few lines and no more: a lobby is a place to
    /// say "ready?", not a place to scroll back through.
    #[test]
    fn the_feed_keeps_the_last_few_lines() {
        let mut state = LobbyState::default();
        for n in 0..CHAT_LINES + 4 {
            state.say("Anna", &format!("line {n}"));
        }
        assert_eq!(state.chat.len(), CHAT_LINES);
        assert_eq!(state.chat[0].line, "line 4", "{:?}", state.chat);
        assert_eq!(
            state.chat.last().unwrap().who,
            "Anna",
            "each line remembers who said it"
        );
        // Nothing said is nothing shown: an empty line is not a turn.
        state.say("Anna", "");
        assert_eq!(state.chat.len(), CHAT_LINES);
    }

    /// A notice is the lobby speaking. Nobody said it, and that is the
    /// whole of what tells the feed to slant it.
    #[test]
    fn a_notice_has_nobody_behind_it() {
        let mut state = LobbyState::default();
        state.say("", "Anna joined");
        state.say("Anna", "ready?");
        assert!(state.chat[0].is_notice(), "nobody said it");
        assert!(!state.chat[1].is_notice(), "Anna did");
    }

    /// Chat needs someone to chat with. Alone in the lobby, watching the
    /// list, there is nobody on the other end and the key does nothing.
    #[test]
    fn there_is_nobody_to_talk_to_until_there_is() {
        let mut state = LobbyState::default();
        assert!(!state.can_chat(), "browsing the list is not a conversation");
        state.standing = Standing::hosting(
            Announcer::new(0xB0A7).expect("announcer"),
            UdpTransport::host(0).expect("socket"),
        );
        assert!(state.can_chat(), "a host has a table to address");
        state.standing = Standing::Joining(Joined::dialled(
            UdpTransport::join(("127.0.0.1", 47999)).expect("join"),
            false,
        ));
        assert!(state.can_chat(), "and a joiner has a host");
    }
}

#[cfg(test)]
mod table_tests {
    use super::*;
    use crate::app::i18n::EN;
    use crate::app::lobby::hosting::peers_named;

    /// A hosting lobby with these peers on it, as greeted.
    fn seated(names: &[&str], watchers: &[usize]) -> LobbyState {
        let mut state = LobbyState {
            standing: Standing::hosting(
                Announcer::new(0xB0A7).expect("announcer"),
                UdpTransport::host(0).expect("socket"),
            ),
            ..LobbyState::default()
        };
        state.hosted_mut().expect("hosting").peers = peers_named(names, watchers);
        state
    }

    /// The table is the host and everyone who came to play, in peer order.
    /// Onlookers are not at it, they are watching it, and a peer that has
    /// not said what to call it yet still holds its chair.
    #[test]
    fn the_table_is_the_host_and_the_players() {
        let state = seated(&["Bo", "Cy"], &[]);
        assert_eq!(state.roster(&EN, "Anna"), ["Anna", "Bo", "Cy"]);

        // Peer 0 came to watch, so the table is the host and Cy.
        let state = seated(&["Bo", "Cy"], &[0]);
        assert_eq!(state.roster(&EN, "Anna"), ["Anna", "Cy"]);

        // A nameless host, and a nameless peer, fall back to seat labels
        // rather than to blanks.
        let state = seated(&[""], &[]);
        let table = state.roster(&EN, "");
        assert_eq!(table.len(), 2);
        assert!(table.iter().all(|who| !who.is_empty()), "{table:?}");

        // And a lobby that is not hosting seats nobody but its owner.
        let state = LobbyState::default();
        assert_eq!(state.roster(&EN, "Anna"), ["Anna"]);
    }

    /// Dropping a peer has to move the rows behind it with the socket's
    /// own list, or the row after it silently takes its name and its wish
    /// to watch, and nobody notices until somebody is labelled as somebody
    /// else.
    #[test]
    fn forgetting_a_peer_moves_everything_that_indexed_it() {
        let mut state = seated(&["Bo", "Cy", "Dee"], &[2]);
        assert_eq!(
            state.roster(&EN, "Anna"),
            ["Anna", "Bo", "Cy"],
            "Dee watches"
        );

        // Bo leaves. Cy and Dee shift down, and Dee is still the watcher.
        state.hosted_mut().expect("hosting").forget_peer(0);
        let hosted = state.hosted().expect("hosting");
        let names: Vec<&str> = hosted.peers.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(names, ["Cy", "Dee"]);
        assert_eq!(hosted.watchers_aboard(), 1, "the wish followed Dee down");
        assert_eq!(hosted.players_aboard(), 1);
        assert_eq!(
            state.roster(&EN, "Anna"),
            ["Anna", "Cy"],
            "Dee still watches"
        );

        // The watcher itself leaves, and takes only its own wish.
        state.hosted_mut().expect("hosting").forget_peer(1);
        let hosted = state.hosted().expect("hosting");
        assert_eq!(hosted.peers.len(), 1);
        assert_eq!(hosted.watchers_aboard(), 0);
        assert_eq!(state.roster(&EN, "Anna"), ["Anna", "Cy"]);
    }
}

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

    /// Where the player stands is one value, and the wish to watch rides
    /// with it: armed while choosing, carried onto the greeting, and
    /// meaningless to a host, who plays.
    #[test]
    fn the_standing_carries_the_wish_to_watch_with_it() {
        let mut state = LobbyState::default();
        assert!(!state.standing().at_a_beach(), "nobody to talk to yet");
        assert!(!state.watching());

        state.set_watching(true);
        assert!(state.watching());
        assert!(!state.standing().at_a_beach());

        let watching = state.watching();
        state.standing = Standing::Joining(Joined::dialled(
            UdpTransport::join(("127.0.0.1", 47999)).expect("join"),
            watching,
        ));
        assert!(state.joined().is_some());
        assert!(state.watching(), "the wish went with the greeting");
        assert!(state.standing().at_a_beach());

        // Letting the beach go keeps W armed as it was.
        state.let_go();
        assert!(state.joined().is_none());
        assert!(state.watching());

        state.standing = Standing::hosting(
            Announcer::new(1).expect("announcer"),
            UdpTransport::host(0).expect("socket"),
        );
        assert!(state.hosting());
        assert!(!state.watching(), "a host plays");
        assert!(state.standing().at_a_beach());
    }

    /// The point of naming the standing: four places used to ask this
    /// question and each spelled it differently.
    #[test]
    fn everything_that_asks_gets_the_same_answer() {
        let mut state = LobbyState::default();
        for watching in [false, true] {
            state.set_watching(watching);
            assert_eq!(state.can_chat(), state.standing().at_a_beach());
        }
        state.standing = Standing::Joining(Joined::dialled(
            UdpTransport::join(("127.0.0.1", 47998)).expect("join"),
            false,
        ));
        assert_eq!(state.can_chat(), state.standing().at_a_beach());
    }
}