use ghast_protocol::types::ByteString;
use uuid::Uuid;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Text {
json: ByteString,
rendered: Option<Box<str>>,
}
impl Text {
#[must_use]
pub fn from_json(json: ByteString) -> Self {
Text {
json,
rendered: None,
}
}
#[must_use]
pub fn from_text(text: impl Into<String>) -> Self {
Text {
json: ByteString::from_static(""),
rendered: Some(text.into().into_boxed_str()),
}
}
#[must_use]
pub fn json(&self) -> Option<&str> {
if self.rendered.is_some() {
None
} else {
Some(&self.json)
}
}
#[must_use]
pub fn text(&self) -> String {
match &self.rendered {
Some(t) => t.to_string(),
None => ghast_protocol::chat::to_plain_text(&self.json),
}
}
#[must_use]
pub fn plain(&self) -> String {
ghast_protocol::chat::strip_formatting(&self.text())
}
#[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(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BossBarColor {
Pink,
Blue,
Red,
Green,
Yellow,
Purple,
White,
}
impl BossBarColor {
#[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,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BossBarStyle {
Progress,
Notched6,
Notched10,
Notched12,
Notched20,
}
impl BossBarStyle {
#[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,
})
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct BossBar {
pub id: Uuid,
pub title: Text,
pub progress: f32,
pub color: BossBarColor,
pub style: BossBarStyle,
pub darken_screen: bool,
pub play_music: bool,
pub create_fog: bool,
}
impl BossBar {
#[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,
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum BossBarOp {
Add(BossBar),
Remove(Uuid),
Progress(Uuid, f32),
Title(Uuid, Text),
Style {
id: Uuid,
color: BossBarColor,
style: BossBarStyle,
},
Flags {
id: Uuid,
darken_screen: bool,
play_music: bool,
create_fog: Option<bool>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct TitleTimes {
pub fade_in: i32,
pub stay: i32,
pub fade_out: i32,
}
impl TitleTimes {
pub const DEFAULT: TitleTimes = TitleTimes {
fade_in: 10,
stay: 70,
fade_out: 20,
};
#[must_use]
pub const fn new(fade_in: i32, stay: i32, fade_out: i32) -> Self {
TitleTimes {
fade_in,
stay,
fade_out,
}
}
#[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
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum TitleOp {
Title(Text),
Subtitle(Text),
Times(TitleTimes),
Clear,
Reset,
LegacyReset,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum HudEvent {
BossBarAdded(Uuid),
BossBarRemoved(Uuid),
BossBarChanged(Uuid),
Title(Text),
Subtitle(Text),
TitleTimes(TitleTimes),
TitlesCleared {
reset_times: bool,
},
TitleEnded,
ActionBar(Text),
ActionBarEnded,
TabList,
Reset,
}
pub const ACTION_BAR_TICKS: i32 = 60;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TitlePhase {
FadeIn,
Stay,
FadeOut,
}
#[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 {
#[must_use]
pub fn boss_bars(&self) -> &[BossBar] {
&self.bars
}
#[must_use]
pub fn boss_bar(&self, id: Uuid) -> Option<&BossBar> {
self.bars.iter().find(|b| b.id == id)
}
#[must_use]
pub fn title(&self) -> Option<&Text> {
if self.title_ticks > 0 {
self.title.as_ref()
} else {
None
}
}
#[must_use]
pub fn subtitle(&self) -> Option<&Text> {
if self.title().is_some() {
self.subtitle.as_ref()
} else {
None
}
}
#[must_use]
pub fn title_text(&self) -> Option<&Text> {
self.title.as_ref()
}
#[must_use]
pub fn subtitle_text(&self) -> Option<&Text> {
self.subtitle.as_ref()
}
#[must_use]
pub fn title_ticks(&self) -> i32 {
self.title_ticks.max(0)
}
#[must_use]
pub fn title_times(&self) -> TitleTimes {
self.times
}
#[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
})
}
#[must_use]
pub fn action_bar(&self) -> Option<&Text> {
if self.overlay_ticks > 0 {
self.overlay.as_ref()
} else {
None
}
}
#[must_use]
pub fn action_bar_ticks(&self) -> i32 {
self.overlay_ticks.max(0)
}
#[must_use]
pub fn header(&self) -> Option<&Text> {
self.header.as_ref()
}
#[must_use]
pub fn footer(&self) -> Option<&Text> {
self.footer.as_ref()
}
#[inline]
pub(crate) fn counting(&self) -> bool {
self.title_ticks > 0 || self.overlay_ticks > 0
}
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);
}
}
}
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;
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
}
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));
}
}
}
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));
}
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);
}
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);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Suggestion {
pub text: String,
pub tooltip: Option<Text>,
}
impl Suggestion {
#[must_use]
pub fn new(text: impl Into<String>, tooltip: Option<Text>) -> Self {
Suggestion {
text: text.into(),
tooltip,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TabCompletion {
pub request: Option<u32>,
pub transaction_id: Option<i32>,
pub start: i32,
pub length: i32,
pub matches: Vec<Suggestion>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TabCompleteResponse {
pub transaction_id: Option<i32>,
pub range: Option<(i32, i32)>,
pub matches: Vec<Suggestion>,
}
impl TabCompleteResponse {
#[must_use]
pub fn new(
transaction_id: Option<i32>,
range: Option<(i32, i32)>,
matches: Vec<Suggestion>,
) -> Self {
TabCompleteResponse {
transaction_id,
range,
matches,
}
}
}
#[derive(Debug, Clone, Copy)]
struct Waiting {
request: u32,
wire: i32,
start: i32,
length: i32,
}
const MAX_WAITING: usize = 32;
#[derive(Debug, Clone)]
pub(crate) struct TabCompleter {
next_request: u32,
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 {
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);
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)
}
pub(crate) fn answer(&mut self, r: TabCompleteResponse) -> TabCompletion {
let at = match r.transaction_id {
Some(id) => {
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,
}
}
}
#[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
}
#[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")));
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());
}
#[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))
);
run(&mut h, vec![TitleOp::Times(TitleTimes::new(0, 0, 0))]);
assert!(h.title().is_none());
assert_eq!(h.title_text(), Some(&t("a")));
run(&mut h, vec![TitleOp::Title(t("b"))]);
assert!(h.title().is_none());
}
#[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")));
assert_eq!(h.title_phase(), Some(TitlePhase::FadeOut));
}
#[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);
}
#[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());
}
#[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);
}
#[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));
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));
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);
}
}