ghast 0.5.6

Headless Minecraft Java Edition client / bot library (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3) with vanilla-exact behaviour: facade crate re-exporting the ghast-* crates
Documentation
//! The HUD and tab completion with the `ghast-ext` helpers: completes a command line once
//! (`Bot::tab_complete`, `--complete TEXT`, default `/ti`), then prints every HUD change the
//! server sends (boss bars, titles, the action bar, the tab list's header and footer) and what
//! the HUD shows at each change, for `--watch` ticks. `lab/hud.sh` drives it on a lab server.
//!
//! Output lines (for scripts): `TAB <start> <length> <match>,<match>,...` once, `HUD <event>`
//! per change, `TITLE_LIFE <ticks>` for every title from its start to the end of its countdown,
//! and a final `RESULT` line with what was seen.
//!
//! ```text
//! cargo run -p ghast --release --features ext --example hud -- \
//!     --host 127.0.0.1 --port 25636 --username GhastBot11 --version 26.3 --minutes 1
//! ```

mod support;

use ghast::Interests;
use ghast::ext::{Bot, Error, Event, Ext, WhenDone};
use ghast::hud::HudEvent;

/// The example's own options (the rest are the examples' common ones).
#[derive(Debug, Clone)]
struct HudOpts {
    complete: String,
    watch: u64,
}

impl HudOpts {
    fn take(args: Vec<String>) -> (HudOpts, Vec<String>) {
        let mut o = HudOpts {
            complete: "/ti".into(),
            watch: 600,
        };
        let mut rest = Vec::new();
        let mut it = args.into_iter();
        while let Some(a) = it.next() {
            match a.as_str() {
                "--complete" => o.complete = it.next().expect("--complete TEXT"),
                "--watch" => {
                    o.watch = it
                        .next()
                        .and_then(|v| v.parse().ok())
                        .expect("--watch TICKS");
                }
                _ => rest.push(a),
            }
        }
        (o, rest)
    }
}

async fn run(bot: Bot, o: HudOpts) -> Result<(), Error> {
    let mut events = bot.events();
    // a moment for the join's packets
    bot.wait_ticks(20).await;
    match bot.tab_complete(o.complete.clone()).await {
        Ok(c) => {
            let m: Vec<&str> = c.matches.iter().map(|m| m.text.as_str()).collect();
            println!("TAB {} {} {}", c.start, c.length, m.join(","));
        }
        Err(e) => println!("TAB failed: {e}"),
    }
    let start = bot.tick();
    let mut title_start: Option<u64> = None;
    let (mut bars, mut titles, mut subtitles, mut bar_msgs, mut lists) = (0, 0, 0, 0, 0);
    while bot.tick() < start + o.watch {
        let Some(e) = bot.timeout(o.watch, events.recv()).await.ok().flatten() else {
            break;
        };
        let Event::Hud(h) = e else { continue };
        let now = bot.tick();
        let hud = bot.hud().await?.unwrap_or_default();
        match &h {
            HudEvent::BossBarAdded(_) | HudEvent::BossBarChanged(_) => {
                bars += 1;
                for b in hud.boss_bars() {
                    println!(
                        "HUD bossbar {} \"{}\" {:.2} {:?} {:?}",
                        b.id,
                        b.title.plain(),
                        b.progress,
                        b.color,
                        b.style
                    );
                }
            }
            HudEvent::BossBarRemoved(id) => println!("HUD bossbar removed {id}"),
            HudEvent::Title(t) => {
                titles += 1;
                title_start = Some(now);
                println!(
                    "HUD title \"{}\" subtitle {:?} ticks {} times {:?}",
                    t.plain(),
                    hud.subtitle().map(|s| s.plain()),
                    hud.title_ticks(),
                    hud.title_times()
                );
            }
            HudEvent::Subtitle(t) => {
                subtitles += 1;
                println!("HUD subtitle \"{}\"", t.plain());
            }
            HudEvent::TitleTimes(t) => println!("HUD times {t:?}"),
            HudEvent::TitleEnded => {
                if let Some(s) = title_start.take() {
                    println!("TITLE_LIFE {}", now - s);
                }
                println!("HUD title ended");
            }
            HudEvent::ActionBar(t) => {
                bar_msgs += 1;
                println!("HUD actionbar \"{}\"", t.plain());
            }
            HudEvent::TabList => {
                lists += 1;
                println!(
                    "HUD tablist {:?} / {:?}",
                    hud.header().map(|t| t.plain()),
                    hud.footer().map(|t| t.plain())
                );
            }
            other => println!("HUD {other:?}"),
        }
    }
    println!(
        "RESULT bossbar_events={bars} titles={titles} subtitles={subtitles} actionbars={bar_msgs} tablists={lists}"
    );
    Ok(())
}

fn main() {
    let (ho, rest) = HudOpts::take(std::env::args().skip(1).collect());
    let opts = support::Options::parse_from(rest);
    support::init_logger(opts.verbose);
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("tokio runtime");
    let mut ext = Ext::new(move |bot| run(bot, ho.clone()))
        .name("hud")
        .interests(Interests::CHAT | Interests::HUD)
        .when_done(WhenDone::Disconnect);
    let limit = opts.limit();
    let ok = rt.block_on(async {
        let client = match opts.client() {
            Ok(c) => c,
            Err(e) => {
                log::error!("{e}");
                std::process::exit(2);
            }
        };
        let shutdown = async {
            let stop = async {
                #[cfg(unix)]
                {
                    let mut term =
                        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
                            .expect("SIGTERM handler");
                    tokio::select! {
                        _ = tokio::signal::ctrl_c() => {}
                        _ = term.recv() => {}
                    }
                }
                #[cfg(not(unix))]
                let _ = tokio::signal::ctrl_c().await;
            };
            match limit {
                Some(l) => {
                    tokio::select! {
                        () = stop => {}
                        () = tokio::time::sleep(l) => log::warn!("time limit reached"),
                    }
                }
                None => stop.await,
            }
        };
        match client.run_until(&mut ext, shutdown).await {
            Ok(e) => {
                log::info!("session ended: {e:?}; result {:?}", ext.result());
                matches!(ext.result(), Some(Ok(())))
            }
            Err(e) => {
                log::error!("session failed: {e}");
                false
            }
        }
    });
    std::process::exit(if ok { 0 } else { 1 });
}