ghast-client 0.5.5

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
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
//! What the vanilla in-game HUD shows (`Interests::HUD`): boss bars, the title and subtitle
//! with their fade times, the action bar (overlay message) and the tab list's header and
//! footer, kept and counted down per client tick the way each version's HUD does it; and the
//! server's answers to command tab-completion requests ([`TabCompletion`], always decoded:
//! they only arrive after a [`crate::TickContext::tab_complete`]).
//!
//! The state is [`Hud`] ([`crate::TickContext::hud`]); the changes are [`HudEvent`]s
//! ([`crate::TickEvents::hud`]). Without the interest the packets are dropped by the frame
//! decoder undecoded and no state is kept.
//!
//! ```
//! let hud = ghast_client::hud::Hud::default();
//! assert!(hud.title().is_none());
//! assert_eq!(hud.title_times().stay, 70);
//! ```
//!
//! Version quirks kept (read in each version's client jar):
//!
//! - A subtitle never shows by itself: it is stored and shown with the next title (every
//!   version). Title times apply to the next title, or restart a title that is showing.
//! - 1.8 – 1.16.5 `clear` sets all three times to 0 (the client applies the packet's unset
//!   times), so a later title is not shown until new times or a reset arrive; 26.x
//!   `clear_titles` keeps the times.
//! - 1.8 / 1.12 `reset` starts an empty title with the old times (a subtitle on screen stays
//!   for that long) and then restores the default times; 1.16.5 `reset` and 26.x
//!   `clear_titles` with `reset` clear everything and restore the defaults.
//! - 1.8 – 1.16.5 `times` with all three negative clears the titles; 26.x ignores each
//!   negative time but still restarts a title that is showing.
//! - 1.8: a header or footer is never "empty" (the client's formatted string always holds a
//!   reset code); 1.12 (whose formatted string skips empty parts), 1.16.5 and 26.x drop one
//!   whose text is empty.
//! - Boss bar flags: 1.12 reads "create fog" from the music bit, and 1.12 / 1.16.5 property
//!   updates keep the fog flag; 26.x updates all three.
//! - 26.x: the start of a reconfiguration resets the HUD (`Hud.onDisconnected`: boss bars,
//!   titles and their times, header and footer; the action bar stays).
//!
//! Not modelled: messages the client makes itself (the "press shift to dismount" action bar
//! when mounting, a jukebox's "now playing"), and the boss bars' progress animation (vanilla
//! eases a new value in over 100 ms of wall time; [`BossBar::progress`] is the target).

use ghast_protocol::types::ByteString;
use uuid::Uuid;

/// A text component as one HUD element shows it.
///
/// 1.8 – 1.16.5 send JSON components (kept as sent, rendered on demand); 26.x components are
/// NBT and rendered to text when decoded.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Text {
    json: ByteString,
    /// A boxed `str` (not a `String`): two texts in [`crate::common::Inbound::TabList`] then
    /// keep `Inbound` at its old size with a plain tag byte (a larger variant moved the tag
    /// into a niche, which every packet match paid for).
    rendered: Option<Box<str>>,
}

impl Text {
    /// A text from its JSON chat component (1.8 – 1.16.5).
    #[must_use]
    pub fn from_json(json: ByteString) -> Self {
        Text {
            json,
            rendered: None,
        }
    }

    /// A text already rendered (26.x NBT components, or plain text).
    #[must_use]
    pub fn from_text(text: impl Into<String>) -> Self {
        Text {
            json: ByteString::from_static(""),
            rendered: Some(text.into().into_boxed_str()),
        }
    }

    /// The JSON component as the server sent it (1.8 – 1.16.5); `None` for a text rendered
    /// when decoded (26.x).
    #[must_use]
    pub fn json(&self) -> Option<&str> {
        if self.rendered.is_some() {
            None
        } else {
            Some(&self.json)
        }
    }

    /// The text with legacy `§` formatting codes kept.
    #[must_use]
    pub fn text(&self) -> String {
        match &self.rendered {
            Some(t) => t.to_string(),
            None => ghast_protocol::chat::to_plain_text(&self.json),
        }
    }

    /// The text without `§` formatting codes.
    #[must_use]
    pub fn plain(&self) -> String {
        ghast_protocol::chat::strip_formatting(&self.text())
    }

    /// `true` when the text is empty (`Component.getString().isEmpty()`).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        match &self.rendered {
            Some(t) => t.is_empty(),
            None => ghast_protocol::chat::to_plain_text(&self.json).is_empty(),
        }
    }
}

/// A boss bar's colour (`BossEvent.BossBarColor`, network ids 0 – 6).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BossBarColor {
    /// 0.
    Pink,
    /// 1.
    Blue,
    /// 2.
    Red,
    /// 3.
    Green,
    /// 4.
    Yellow,
    /// 5.
    Purple,
    /// 6.
    White,
}

impl BossBarColor {
    /// From the network id (`None` for an id the client does not know: vanilla fails to read
    /// the packet).
    #[must_use]
    pub fn from_wire(id: i32) -> Option<Self> {
        Some(match id {
            0 => Self::Pink,
            1 => Self::Blue,
            2 => Self::Red,
            3 => Self::Green,
            4 => Self::Yellow,
            5 => Self::Purple,
            6 => Self::White,
            _ => return None,
        })
    }
}

/// How a boss bar is divided (`BossEvent.BossBarOverlay`, network ids 0 – 4).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BossBarStyle {
    /// 0: one solid bar.
    Progress,
    /// 1: 6 notches.
    Notched6,
    /// 2: 10 notches.
    Notched10,
    /// 3: 12 notches.
    Notched12,
    /// 4: 20 notches.
    Notched20,
}

impl BossBarStyle {
    /// From the network id (`None` for an unknown one).
    #[must_use]
    pub fn from_wire(id: i32) -> Option<Self> {
        Some(match id {
            0 => Self::Progress,
            1 => Self::Notched6,
            2 => Self::Notched10,
            3 => Self::Notched12,
            4 => Self::Notched20,
            _ => return None,
        })
    }
}

/// One boss bar (1.9+; `#[non_exhaustive]`: read-only, fields may be added).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct BossBar {
    /// The bar's id (its key).
    pub id: Uuid,
    /// The text above the bar.
    pub title: Text,
    /// Fill, 0 – 1 as the server sent it (the value vanilla eases towards).
    pub progress: f32,
    /// Colour.
    pub color: BossBarColor,
    /// Division.
    pub style: BossBarStyle,
    /// The sky darkens (flag bit 0).
    pub darken_screen: bool,
    /// Boss music plays (flag bit 1, the ender dragon's).
    pub play_music: bool,
    /// The world fog thickens (flag bit 2; 1.12 reads bit 1, see the module docs).
    pub create_fog: bool,
}

impl BossBar {
    /// A bar as the client adds it.
    #[must_use]
    pub fn new(
        id: Uuid,
        title: Text,
        progress: f32,
        color: BossBarColor,
        style: BossBarStyle,
    ) -> Self {
        BossBar {
            id,
            title,
            progress,
            color,
            style,
            darken_screen: false,
            play_music: false,
            create_fog: false,
        }
    }
}

/// One boss bar operation (`boss_bar` / `ClientboundBossEventPacket`), as the version's client
/// reads it.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum BossBarOp {
    /// Add a bar (an existing id is replaced in place).
    Add(BossBar),
    /// Remove a bar.
    Remove(Uuid),
    /// New progress.
    Progress(Uuid, f32),
    /// New title.
    Title(Uuid, Text),
    /// New colour and division.
    Style {
        /// The bar.
        id: Uuid,
        /// Colour.
        color: BossBarColor,
        /// Division.
        style: BossBarStyle,
    },
    /// New flags.
    Flags {
        /// The bar.
        id: Uuid,
        /// Darken the sky.
        darken_screen: bool,
        /// Boss music.
        play_music: bool,
        /// Thicken the fog; `None` where the version's client keeps the old value (1.12,
        /// 1.16.5).
        create_fog: Option<bool>,
    },
}

/// Fade-in, stay and fade-out of titles, in ticks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct TitleTimes {
    /// Fade-in ticks.
    pub fade_in: i32,
    /// Ticks fully shown.
    pub stay: i32,
    /// Fade-out ticks.
    pub fade_out: i32,
}

impl TitleTimes {
    /// The default times (10, 70, 20), as a new client and a reset have them.
    pub const DEFAULT: TitleTimes = TitleTimes {
        fade_in: 10,
        stay: 70,
        fade_out: 20,
    };

    /// Times from their three values.
    #[must_use]
    pub const fn new(fade_in: i32, stay: i32, fade_out: i32) -> Self {
        TitleTimes {
            fade_in,
            stay,
            fade_out,
        }
    }

    /// The whole display time.
    #[must_use]
    pub const fn total(self) -> i32 {
        self.fade_in
            .wrapping_add(self.stay)
            .wrapping_add(self.fade_out)
    }
}

impl Default for TitleTimes {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// One title operation, as the version's client applies a title packet (the wire layer maps
/// each version's actions onto these).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum TitleOp {
    /// Show a title: (re)starts the countdown with the current times (`setTitle`).
    Title(Text),
    /// Store the subtitle (shown with the current or the next title).
    Subtitle(Text),
    /// New times: each negative one is kept; a title that is showing restarts with them
    /// (`setTimes`).
    Times(TitleTimes),
    /// Clear the title and subtitle and stop the countdown; the times stay
    /// (`clearTitles`; 1.8 – 1.16.5 `times` with all three negative).
    Clear,
    /// [`TitleOp::Clear`] and the default times (26.x `clear_titles` with `reset`, 1.16.5
    /// `reset`).
    Reset,
    /// 1.8 / 1.12 `reset`: an empty title restarts the countdown with the old times, then the
    /// default times are restored.
    LegacyReset,
}

/// A change of the HUD, in arrival order ([`crate::TickEvents::hud`]).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum HudEvent {
    /// A boss bar was added (or replaced by an add with the same id).
    BossBarAdded(Uuid),
    /// A boss bar was removed.
    BossBarRemoved(Uuid),
    /// A boss bar's progress, title, style or flags changed.
    BossBarChanged(Uuid),
    /// A title started showing (also the empty title of a 1.8 / 1.12 reset).
    Title(Text),
    /// A subtitle was set.
    Subtitle(Text),
    /// The title times changed (the times now in effect).
    TitleTimes(TitleTimes),
    /// The titles were cleared (`reset_times`: the default times are back).
    TitlesCleared {
        /// The times were reset to the defaults as well.
        reset_times: bool,
    },
    /// The title's countdown ran out (title and subtitle are gone).
    TitleEnded,
    /// An action bar message was shown.
    ActionBar(Text),
    /// The action bar message's countdown ran out.
    ActionBarEnded,
    /// The tab list's header or footer changed.
    TabList,
    /// The whole HUD was reset (26.x reconfiguration: boss bars, titles and their times,
    /// header and footer).
    Reset,
}

/// Ticks an action bar message stays (`setOverlayMessage`).
pub const ACTION_BAR_TICKS: i32 = 60;

/// Where the title countdown is ([`Hud::title_phase`]), as the HUD's renderer reads it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TitlePhase {
    /// Fading in (more than fade-out + stay ticks left).
    FadeIn,
    /// Fully shown.
    Stay,
    /// Fading out (fade-out ticks or fewer left).
    FadeOut,
}

/// The HUD state ([`crate::TickContext::hud`], with [`crate::Interests::HUD`]).
#[derive(Debug, Clone, PartialEq)]
pub struct Hud {
    bars: Vec<BossBar>,
    title: Option<Text>,
    subtitle: Option<Text>,
    title_ticks: i32,
    times: TitleTimes,
    overlay: Option<Text>,
    overlay_ticks: i32,
    header: Option<Text>,
    footer: Option<Text>,
}

impl Default for Hud {
    fn default() -> Self {
        Hud {
            bars: Vec::new(),
            title: None,
            subtitle: None,
            title_ticks: 0,
            times: TitleTimes::DEFAULT,
            overlay: None,
            overlay_ticks: 0,
            header: None,
            footer: None,
        }
    }
}

impl Hud {
    /// The boss bars, top to bottom (the order they were added in).
    #[must_use]
    pub fn boss_bars(&self) -> &[BossBar] {
        &self.bars
    }

    /// The boss bar with this id.
    #[must_use]
    pub fn boss_bar(&self, id: Uuid) -> Option<&BossBar> {
        self.bars.iter().find(|b| b.id == id)
    }

    /// The title on screen now (`None` when none shows).
    #[must_use]
    pub fn title(&self) -> Option<&Text> {
        if self.title_ticks > 0 {
            self.title.as_ref()
        } else {
            None
        }
    }

    /// The subtitle on screen now (only with a title).
    #[must_use]
    pub fn subtitle(&self) -> Option<&Text> {
        if self.title().is_some() {
            self.subtitle.as_ref()
        } else {
            None
        }
    }

    /// The title text the HUD keeps, shown or not (a cleared 1.8 – 1.16.5 countdown keeps it
    /// hidden).
    #[must_use]
    pub fn title_text(&self) -> Option<&Text> {
        self.title.as_ref()
    }

    /// The subtitle text the HUD keeps: set before a title, it shows with the next one.
    #[must_use]
    pub fn subtitle_text(&self) -> Option<&Text> {
        self.subtitle.as_ref()
    }

    /// Ticks the title has left on screen (0 when none shows).
    #[must_use]
    pub fn title_ticks(&self) -> i32 {
        self.title_ticks.max(0)
    }

    /// The title times in effect (for the next title, and the one showing).
    #[must_use]
    pub fn title_times(&self) -> TitleTimes {
        self.times
    }

    /// Where the title showing now is in its fade (`None` when none shows).
    #[must_use]
    pub fn title_phase(&self) -> Option<TitlePhase> {
        self.title()?;
        let t = self.title_ticks;
        Some(if t <= self.times.fade_out {
            TitlePhase::FadeOut
        } else if t > self.times.fade_out.wrapping_add(self.times.stay) {
            TitlePhase::FadeIn
        } else {
            TitlePhase::Stay
        })
    }

    /// The action bar message on screen now.
    #[must_use]
    pub fn action_bar(&self) -> Option<&Text> {
        if self.overlay_ticks > 0 {
            self.overlay.as_ref()
        } else {
            None
        }
    }

    /// Ticks the action bar message has left (it shows for 60).
    #[must_use]
    pub fn action_bar_ticks(&self) -> i32 {
        self.overlay_ticks.max(0)
    }

    /// The tab list's header.
    #[must_use]
    pub fn header(&self) -> Option<&Text> {
        self.header.as_ref()
    }

    /// The tab list's footer.
    #[must_use]
    pub fn footer(&self) -> Option<&Text> {
        self.footer.as_ref()
    }

    /// Whether the per-tick countdown has anything to do.
    #[inline]
    pub(crate) fn counting(&self) -> bool {
        self.title_ticks > 0 || self.overlay_ticks > 0
    }

    /// One HUD tick (`Gui.tick` / `InGameHud.tick`): the action bar and the title count down;
    /// a title that runs out loses its texts.
    pub(crate) fn tick(&mut self, mut emit: impl FnMut(HudEvent)) {
        if self.overlay_ticks > 0 {
            self.overlay_ticks -= 1;
            if self.overlay_ticks == 0 {
                emit(HudEvent::ActionBarEnded);
            }
        }
        if self.title_ticks > 0 {
            self.title_ticks -= 1;
            if self.title_ticks <= 0 {
                self.title = None;
                self.subtitle = None;
                emit(HudEvent::TitleEnded);
            }
        }
    }

    /// Applies a boss bar operation (`BossHealthOverlay.update`). An update of an unknown bar
    /// is ignored (vanilla fails on it) and returns `false`.
    pub(crate) fn boss_bar_op(&mut self, op: BossBarOp, mut emit: impl FnMut(HudEvent)) -> bool {
        let find = |bars: &mut Vec<BossBar>, id: Uuid| bars.iter_mut().position(|b| b.id == id);
        match op {
            BossBarOp::Add(bar) => {
                let id = bar.id;
                // LinkedHashMap.put: a known key keeps its place.
                match find(&mut self.bars, id) {
                    Some(i) => self.bars[i] = bar,
                    None => self.bars.push(bar),
                }
                emit(HudEvent::BossBarAdded(id));
            }
            BossBarOp::Remove(id) => {
                if let Some(i) = find(&mut self.bars, id) {
                    self.bars.remove(i);
                    emit(HudEvent::BossBarRemoved(id));
                }
            }
            BossBarOp::Progress(id, p) => {
                let Some(i) = find(&mut self.bars, id) else {
                    return false;
                };
                self.bars[i].progress = p;
                emit(HudEvent::BossBarChanged(id));
            }
            BossBarOp::Title(id, t) => {
                let Some(i) = find(&mut self.bars, id) else {
                    return false;
                };
                self.bars[i].title = t;
                emit(HudEvent::BossBarChanged(id));
            }
            BossBarOp::Style { id, color, style } => {
                let Some(i) = find(&mut self.bars, id) else {
                    return false;
                };
                self.bars[i].color = color;
                self.bars[i].style = style;
                emit(HudEvent::BossBarChanged(id));
            }
            BossBarOp::Flags {
                id,
                darken_screen,
                play_music,
                create_fog,
            } => {
                let Some(i) = find(&mut self.bars, id) else {
                    return false;
                };
                let b = &mut self.bars[i];
                b.darken_screen = darken_screen;
                b.play_music = play_music;
                if let Some(f) = create_fog {
                    b.create_fog = f;
                }
                emit(HudEvent::BossBarChanged(id));
            }
        }
        true
    }

    /// Applies a title operation (`Hud.setTitle` / `setSubtitle` / `setTimes` / `clearTitles`;
    /// 1.8 – 1.16.5 `InGameHud.setTitles` as the wire layer mapped it).
    pub(crate) fn title_op(&mut self, op: TitleOp, mut emit: impl FnMut(HudEvent)) {
        match op {
            TitleOp::Title(t) => {
                self.title = Some(t.clone());
                self.title_ticks = self.times.total();
                emit(HudEvent::Title(t));
            }
            TitleOp::Subtitle(t) => {
                self.subtitle = Some(t.clone());
                emit(HudEvent::Subtitle(t));
            }
            TitleOp::Times(t) => {
                if t.fade_in >= 0 {
                    self.times.fade_in = t.fade_in;
                }
                if t.stay >= 0 {
                    self.times.stay = t.stay;
                }
                if t.fade_out >= 0 {
                    self.times.fade_out = t.fade_out;
                }
                if self.title_ticks > 0 {
                    self.title_ticks = self.times.total();
                }
                emit(HudEvent::TitleTimes(self.times));
            }
            TitleOp::Clear | TitleOp::Reset => {
                self.title = None;
                self.subtitle = None;
                self.title_ticks = 0;
                let reset_times = op == TitleOp::Reset;
                if reset_times {
                    self.times = TitleTimes::DEFAULT;
                }
                emit(HudEvent::TitlesCleared { reset_times });
            }
            TitleOp::LegacyReset => {
                let empty = Text::from_text("");
                self.title = Some(empty.clone());
                self.title_ticks = self.times.total();
                emit(HudEvent::Title(empty));
                self.times = TitleTimes::DEFAULT;
                emit(HudEvent::TitleTimes(self.times));
            }
        }
    }

    /// An action bar message (`setOverlayMessage`): shown for 60 ticks.
    pub(crate) fn action_bar_op(&mut self, t: Text, mut emit: impl FnMut(HudEvent)) {
        self.overlay = Some(t.clone());
        self.overlay_ticks = ACTION_BAR_TICKS;
        emit(HudEvent::ActionBar(t));
    }

    /// The tab list's header and footer (`PlayerTabOverlay.setHeader` / `setFooter`).
    pub(crate) fn tab_list(
        &mut self,
        header: Option<Text>,
        footer: Option<Text>,
        mut emit: impl FnMut(HudEvent),
    ) {
        self.header = header;
        self.footer = footer;
        emit(HudEvent::TabList);
    }

    /// 26.x `Hud.onDisconnected` at the start of a reconfiguration: boss bars, header and
    /// footer, titles and their times (the action bar stays).
    pub(crate) fn reset(&mut self, mut emit: impl FnMut(HudEvent)) {
        let overlay = self.overlay.take();
        let overlay_ticks = self.overlay_ticks;
        *self = Hud {
            overlay,
            overlay_ticks,
            ..Hud::default()
        };
        emit(HudEvent::Reset);
    }
}

/// One suggestion of a [`TabCompletion`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Suggestion {
    /// The text that replaces the completed range.
    pub text: String,
    /// The tooltip (1.13+; `None` when the server sent none).
    pub tooltip: Option<Text>,
}

impl Suggestion {
    /// A suggestion from its text and tooltip.
    #[must_use]
    pub fn new(text: impl Into<String>, tooltip: Option<Text>) -> Self {
        Suggestion {
            text: text.into(),
            tooltip,
        }
    }
}

/// The server's answer to a tab-completion request ([`crate::TickEvents::tab_completions`]).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TabCompletion {
    /// The request it answers, as [`crate::TickContext::tab_complete`] returned it (`None`
    /// for an answer the client did not wait for).
    pub request: Option<u32>,
    /// 1.13+: the transaction id on the wire (`None` on 1.8 – 1.12.2, where answers come in
    /// request order).
    pub transaction_id: Option<i32>,
    /// Start of the replaced range in the request text, in UTF-16 units (1.13+: as the
    /// server sent it; 1.8 – 1.12.2: the start of the last word, as the legacy chat screen
    /// replaces it).
    pub start: i32,
    /// Length of the replaced range, in UTF-16 units.
    pub length: i32,
    /// The suggestions in the order the server sent them (the 1.12.2 chat screen sorts them
    /// before showing them).
    pub matches: Vec<Suggestion>,
}

/// The wire form of an answer before it is matched to its request.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TabCompleteResponse {
    /// 1.13+ transaction id.
    pub transaction_id: Option<i32>,
    /// 1.13+ start and length of the replaced range.
    pub range: Option<(i32, i32)>,
    /// Suggestions.
    pub matches: Vec<Suggestion>,
}

impl TabCompleteResponse {
    /// An answer from its parts.
    #[must_use]
    pub fn new(
        transaction_id: Option<i32>,
        range: Option<(i32, i32)>,
        matches: Vec<Suggestion>,
    ) -> Self {
        TabCompleteResponse {
            transaction_id,
            range,
            matches,
        }
    }
}

/// A request waiting for its answer.
#[derive(Debug, Clone, Copy)]
struct Waiting {
    request: u32,
    wire: i32,
    /// 1.8 – 1.12.2: the replaced range (the last word).
    start: i32,
    length: i32,
}

/// Most requests kept waiting for an answer (older ones are forgotten).
const MAX_WAITING: usize = 32;

/// The client side of tab completion: request numbers, the wire's transaction ids (vanilla's
/// `ClientSuggestionProvider.pendingSuggestionsId`) and the requests waiting for answers.
#[derive(Debug, Clone)]
pub(crate) struct TabCompleter {
    next_request: u32,
    /// `pendingSuggestionsId`: -1 when nothing is pending; a request takes the next id.
    pending_wire: i32,
    waiting: std::collections::VecDeque<Waiting>,
}

impl Default for TabCompleter {
    fn default() -> Self {
        TabCompleter {
            next_request: 0,
            pending_wire: -1,
            waiting: std::collections::VecDeque::new(),
        }
    }
}

impl TabCompleter {
    /// A new request for `text`: its number and the wire transaction id (vanilla
    /// `++pendingSuggestionsId`).
    pub(crate) fn request(&mut self, text: &str) -> (u32, i32) {
        let request = self.next_request;
        self.next_request = self.next_request.wrapping_add(1);
        self.pending_wire = self.pending_wire.wrapping_add(1);
        // The legacy chat screen completes the last word (`getWordSkipPosition(-1)` without
        // skipping spaces): from after the last space to the end.
        let units = |s: &str| s.encode_utf16().count() as i32;
        let start = text.rfind(' ').map_or(0, |i| units(&text[..=i]));
        let length = units(text) - start;
        if self.waiting.len() == MAX_WAITING {
            self.waiting.pop_front();
        }
        self.waiting.push_back(Waiting {
            request,
            wire: self.pending_wire,
            start,
            length,
        });
        (request, self.pending_wire)
    }

    /// Matches an answer to its request: 1.13+ by transaction id (the oldest waiting request
    /// with it), 1.8 – 1.12.2 the oldest waiting one.
    pub(crate) fn answer(&mut self, r: TabCompleteResponse) -> TabCompletion {
        let at = match r.transaction_id {
            Some(id) => {
                // completeCustomSuggestions: the pending request is done.
                if id == self.pending_wire {
                    self.pending_wire = -1;
                }
                self.waiting.iter().position(|w| w.wire == id)
            }
            None => (!self.waiting.is_empty()).then_some(0),
        };
        let w = at.and_then(|i| self.waiting.remove(i));
        let (start, length) = match (r.range, w) {
            (Some(range), _) => range,
            (None, Some(w)) => (w.start, w.length),
            (None, None) => (0, 0),
        };
        TabCompletion {
            request: w.map(|w| w.request),
            transaction_id: r.transaction_id,
            start,
            length,
            matches: r.matches,
        }
    }
}

/// A suggestion list as the 1.8 / 1.12 wire sends it (strings only).
#[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
pub(crate) fn legacy_matches(matches: Vec<ByteString>) -> Vec<Suggestion> {
    matches
        .into_iter()
        .map(|m| Suggestion::new(m.to_string(), None))
        .collect()
}

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

    fn t(s: &str) -> Text {
        Text::from_text(s)
    }

    fn run(h: &mut Hud, ops: Vec<TitleOp>) -> Vec<HudEvent> {
        let mut ev = Vec::new();
        for op in ops {
            h.title_op(op, |e| ev.push(e));
        }
        ev
    }

    fn ticks(h: &mut Hud, n: usize) -> Vec<HudEvent> {
        let mut ev = Vec::new();
        for _ in 0..n {
            h.tick(|e| ev.push(e));
        }
        ev
    }

    /// The default times give 100 ticks; the subtitle shows with the title and both go when
    /// the countdown ends.
    #[test]
    fn title_countdown() {
        let mut h = Hud::default();
        run(&mut h, vec![TitleOp::Subtitle(t("sub"))]);
        assert!(h.title().is_none() && h.subtitle().is_none());
        assert_eq!(h.subtitle_text(), Some(&t("sub")));
        run(&mut h, vec![TitleOp::Title(t("Hi"))]);
        assert_eq!(h.title_ticks(), 100);
        assert_eq!(h.title_phase(), Some(TitlePhase::FadeIn));
        assert_eq!(h.subtitle(), Some(&t("sub")));
        // fading in while more than fade-out + stay (90) ticks are left
        assert!(ticks(&mut h, 9).is_empty());
        assert_eq!(h.title_phase(), Some(TitlePhase::FadeIn));
        ticks(&mut h, 1);
        assert_eq!(h.title_phase(), Some(TitlePhase::Stay));
        ticks(&mut h, 70);
        assert_eq!(
            (h.title_ticks(), h.title_phase()),
            (20, Some(TitlePhase::FadeOut))
        );
        assert_eq!(ticks(&mut h, 20), vec![HudEvent::TitleEnded]);
        assert!(h.title().is_none() && h.title_text().is_none() && h.subtitle_text().is_none());
        assert!(!h.counting());
    }

    /// Times apply to the next title and restart one that shows; negative ones are kept.
    #[test]
    fn times_restart_and_keep() {
        let mut h = Hud::default();
        run(&mut h, vec![TitleOp::Times(TitleTimes::new(1, 2, 3))]);
        assert_eq!(h.title_ticks(), 0);
        run(&mut h, vec![TitleOp::Title(t("a"))]);
        assert_eq!(h.title_ticks(), 6);
        ticks(&mut h, 4);
        run(&mut h, vec![TitleOp::Times(TitleTimes::new(-1, 5, -1))]);
        assert_eq!(
            (h.title_ticks(), h.title_times()),
            (9, TitleTimes::new(1, 5, 3))
        );
        // 1.8 – 1.16.5 clear: times 0, the title stops but its text stays hidden.
        run(&mut h, vec![TitleOp::Times(TitleTimes::new(0, 0, 0))]);
        assert!(h.title().is_none());
        assert_eq!(h.title_text(), Some(&t("a")));
        // ... and the next title does not show.
        run(&mut h, vec![TitleOp::Title(t("b"))]);
        assert!(h.title().is_none());
    }

    /// 1.8 / 1.12 reset: an empty title with the old times, the subtitle stays, then the
    /// default times.
    #[test]
    fn legacy_reset() {
        let mut h = Hud::default();
        run(
            &mut h,
            vec![
                TitleOp::Times(TitleTimes::new(2, 2, 2)),
                TitleOp::Subtitle(t("s")),
                TitleOp::Title(t("T")),
            ],
        );
        ticks(&mut h, 3);
        let ev = run(&mut h, vec![TitleOp::LegacyReset]);
        assert_eq!(
            ev,
            vec![
                HudEvent::Title(t("")),
                HudEvent::TitleTimes(TitleTimes::DEFAULT)
            ]
        );
        assert_eq!(h.title_ticks(), 6);
        assert_eq!(h.title(), Some(&t("")));
        assert_eq!(h.subtitle(), Some(&t("s")));
        // the phase reads the new (default) times
        assert_eq!(h.title_phase(), Some(TitlePhase::FadeOut));
    }

    /// Reset clears everything and restores the default times; clear keeps the times.
    #[test]
    fn clear_and_reset() {
        let mut h = Hud::default();
        run(
            &mut h,
            vec![
                TitleOp::Times(TitleTimes::new(5, 5, 5)),
                TitleOp::Title(t("x")),
                TitleOp::Clear,
            ],
        );
        assert!(h.title_text().is_none());
        assert_eq!(h.title_times(), TitleTimes::new(5, 5, 5));
        run(&mut h, vec![TitleOp::Reset]);
        assert_eq!(h.title_times(), TitleTimes::DEFAULT);
    }

    /// The action bar shows 60 ticks.
    #[test]
    fn action_bar_countdown() {
        let mut h = Hud::default();
        let mut ev = Vec::new();
        h.action_bar_op(t("hp"), |e| ev.push(e));
        assert_eq!(h.action_bar_ticks(), 60);
        assert!(ticks(&mut h, 59).is_empty());
        assert_eq!(h.action_bar(), Some(&t("hp")));
        assert_eq!(ticks(&mut h, 1), vec![HudEvent::ActionBarEnded]);
        assert!(h.action_bar().is_none());
    }

    /// Bars keep their place on a re-add; updates of unknown bars are ignored; the 1.12 /
    /// 1.16.5 property update keeps the fog flag.
    #[test]
    fn boss_bars() {
        let mut h = Hud::default();
        let (a, b) = (Uuid::from_u128(1), Uuid::from_u128(2));
        let bar = |id, p| BossBar::new(id, t("x"), p, BossBarColor::Red, BossBarStyle::Notched6);
        let mut ev = Vec::new();
        let mut emit = |e| ev.push(e);
        assert!(h.boss_bar_op(BossBarOp::Add(bar(a, 0.5)), &mut emit));
        assert!(h.boss_bar_op(BossBarOp::Add(bar(b, 0.5)), &mut emit));
        assert!(h.boss_bar_op(BossBarOp::Add(bar(a, 0.25)), &mut emit));
        assert_eq!(h.boss_bars()[0].progress, 0.25);
        assert!(!h.boss_bar_op(BossBarOp::Progress(Uuid::from_u128(3), 1.0), &mut emit));
        let mut with_fog = bar(b, 1.0);
        with_fog.create_fog = true;
        assert!(h.boss_bar_op(BossBarOp::Add(with_fog), &mut emit));
        let flags = BossBarOp::Flags {
            id: b,
            darken_screen: true,
            play_music: false,
            create_fog: None,
        };
        assert!(h.boss_bar_op(flags, &mut emit));
        let bb = h.boss_bar(b).unwrap();
        assert!(bb.darken_screen && bb.create_fog);
        assert!(h.boss_bar_op(BossBarOp::Remove(a), &mut emit));
        assert_eq!(h.boss_bars().len(), 1);
    }

    /// Answers match requests: 1.13+ by transaction id (vanilla's id restarts at 0 once the
    /// pending one was answered), 1.8 – 1.12 in order with the last word as the range.
    #[test]
    fn tab_completer() {
        let mut c = TabCompleter::default();
        assert_eq!(c.request("/ti"), (0, 0));
        let a = c.answer(TabCompleteResponse::new(Some(0), Some((1, 2)), vec![]));
        assert_eq!((a.request, a.start, a.length), (Some(0), 1, 2));
        // answered: the next request uses id 0 again; two in flight use 0 and 1
        assert_eq!(c.request("/a"), (1, 0));
        assert_eq!(c.request("/b"), (2, 1));
        let b = c.answer(TabCompleteResponse::new(Some(1), Some((1, 1)), vec![]));
        assert_eq!(b.request, Some(2));
        let a = c.answer(TabCompleteResponse::new(Some(0), Some((1, 1)), vec![]));
        assert_eq!(a.request, Some(1));
        assert_eq!(c.request("/x"), (3, 0));
        // legacy: in order, last word
        let mut c = TabCompleter::default();
        c.request("/tp Al");
        c.request("hi ");
        let a = c.answer(TabCompleteResponse::new(None, None, vec![]));
        assert_eq!((a.request, a.start, a.length), (Some(0), 4, 2));
        let b = c.answer(TabCompleteResponse::new(None, None, vec![]));
        assert_eq!((b.request, b.start, b.length), (Some(1), 3, 0));
        let u = c.answer(TabCompleteResponse::new(None, None, vec![]));
        assert_eq!(u.request, None);
    }
}