use std::sync::Arc;
use ghast_protocol::nbt::{AnonNbt, Compound, List, Tag};
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Dialog {
pub kind: DialogKind,
pub title: String,
pub external_title: Option<String>,
pub can_close_with_escape: bool,
pub pause: bool,
pub after_action: AfterAction,
pub body: Vec<DialogBody>,
pub inputs: Vec<DialogInput>,
pub buttons: Vec<DialogButton>,
pub exit: Option<DialogButton>,
pub on_cancel: Option<DialogAction>,
pub registry_name: Option<String>,
pub nbt: Option<AnonNbt>,
registry: Option<Arc<DialogRegistry>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DialogKind {
Notice,
Confirmation,
MultiAction {
columns: i32,
},
DialogList {
columns: i32,
},
ServerLinks {
columns: i32,
},
Unresolved,
Other(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum AfterAction {
#[default]
Close,
None,
WaitForResponse,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum DialogBody {
Text(String),
Item {
id: String,
count: i32,
description: Option<String>,
},
Other(String),
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct DialogInput {
pub key: String,
pub label: String,
pub kind: InputKind,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum InputKind {
Text {
initial: String,
max_length: i32,
multiline: bool,
},
Bool {
initial: bool,
on_true: String,
on_false: String,
},
SingleOption {
options: Vec<(String, String)>,
initial: usize,
},
NumberRange {
start: f32,
end: f32,
initial: Option<f32>,
step: Option<f32>,
},
Other(String),
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct DialogButton {
pub label: String,
pub tooltip: Option<String>,
pub width: i32,
pub action: Option<DialogAction>,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum DialogAction {
RunCommand(String),
CommandTemplate(String),
Custom {
id: String,
payload: Option<AnonNbt>,
},
CustomTemplate {
id: String,
additions: Option<AnonNbt>,
},
ShowDialog(DialogTarget),
OpenUrl(String),
CopyToClipboard(String),
SuggestCommand(String),
ChangePage(i32),
Other(String),
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum DialogTarget {
Inline(Box<Dialog>),
Named(String),
}
#[derive(Debug, Clone, PartialEq, Default)]
pub(crate) struct DialogRegistry(pub(crate) Vec<(String, Option<Tag>)>);
impl DialogRegistry {
#[cfg_attr(not(ghast_modern), allow(dead_code))]
pub(crate) fn new(entries: impl Iterator<Item = (String, Option<AnonNbt>)>) -> Self {
DialogRegistry(
entries
.map(|(k, v)| (k, v.and_then(|n| n.parse().ok().flatten())))
.collect(),
)
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum DialogEvent {
Shown(Arc<Dialog>),
Cleared,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum InputValue {
Text(String),
Bool(bool),
Option(String),
Number(f32),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Pick {
Button(usize),
Exit,
Close,
}
#[derive(Debug, Clone, PartialEq)]
pub struct DialogAnswer {
pick: Pick,
values: Vec<(String, InputValue)>,
confirm_commands: bool,
}
impl DialogAnswer {
#[must_use]
pub fn button(index: usize) -> Self {
Self::new(Pick::Button(index))
}
#[must_use]
pub fn exit() -> Self {
Self::new(Pick::Exit)
}
#[must_use]
pub fn close() -> Self {
Self::new(Pick::Close)
}
fn new(pick: Pick) -> Self {
DialogAnswer {
pick,
values: Vec::new(),
confirm_commands: false,
}
}
#[must_use]
pub fn with_value(mut self, key: impl Into<String>, value: InputValue) -> Self {
self.values.push((key.into(), value));
self
}
#[must_use]
pub fn confirm_commands(mut self, on: bool) -> Self {
self.confirm_commands = on;
self
}
pub(crate) fn confirms(&self) -> bool {
self.confirm_commands
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DialogRefused {
NoDialog,
NoButton(usize),
NoExit,
CannotClose,
UnknownInput(String),
BadValue(String),
}
impl std::fmt::Display for DialogRefused {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
DialogRefused::NoDialog => f.write_str("no dialog is open"),
DialogRefused::NoButton(i) => write!(f, "the dialog has no button {i}"),
DialogRefused::NoExit => f.write_str("the dialog has no exit button"),
DialogRefused::CannotClose => f.write_str("the dialog cannot be closed with Escape"),
DialogRefused::UnknownInput(k) => write!(f, "the dialog has no input {k:?}"),
DialogRefused::BadValue(k) => write!(f, "the value does not fit input {k:?}"),
}
}
}
impl std::error::Error for DialogRefused {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CommandCheck {
NoIssues,
ParseErrors,
SignatureRequired,
PermissionsRequired,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum DialogSent {
Nothing,
Command(String),
CommandHeld {
command: String,
check: CommandCheck,
},
CommandNotSupported(String),
Custom(String),
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct DialogOutcome {
pub sent: DialogSent,
pub open: Option<Arc<Dialog>>,
pub waiting: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Effect {
Nothing,
Command(String),
Custom { id: String, payload: Option<Tag> },
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Next {
Stay,
Closed,
Waiting,
Open(Arc<Dialog>),
}
pub(crate) fn resolve(
dialog: &Dialog,
answer: &DialogAnswer,
) -> Result<(Effect, Next), DialogRefused> {
let (action, after) = match answer.pick {
Pick::Button(i) => {
let b = dialog.buttons.get(i).ok_or(DialogRefused::NoButton(i))?;
(b.action.as_ref(), dialog.after_action)
}
Pick::Exit => {
let b = dialog.exit.as_ref().ok_or(DialogRefused::NoExit)?;
(b.action.as_ref(), dialog.after_action)
}
Pick::Close => {
if !dialog.can_close_with_escape {
return Err(DialogRefused::CannotClose);
}
(dialog.on_cancel.as_ref(), AfterAction::Close)
}
};
let values = values(dialog, &answer.values)?;
let next = match after {
AfterAction::Close => Next::Closed,
AfterAction::None => Next::Stay,
AfterAction::WaitForResponse => Next::Waiting,
};
let Some(action) = action else {
return Ok((Effect::Nothing, next));
};
Ok(match action {
DialogAction::RunCommand(c) => (Effect::Command(trim_slash(c).to_owned()), next),
DialogAction::CommandTemplate(t) => {
let line = instantiate(t, &values);
(Effect::Command(trim_slash(&line).to_owned()), next)
}
DialogAction::Custom { id, payload } => (
Effect::Custom {
id: id.clone(),
payload: payload
.as_ref()
.and_then(|p| p.parse().ok().flatten())
.map(java_order),
},
next,
),
DialogAction::CustomTemplate { id, additions } => {
let mut c = match additions.as_ref().and_then(|a| a.parse().ok().flatten()) {
Some(Tag::Compound(c)) => java_order_compound(c),
_ => Compound::default(),
};
for (k, v) in java_iteration(values.iter().map(|(k, v)| (k.clone(), v.tag.clone()))) {
match c.0.iter_mut().find(|(n, _)| *n == k) {
Some(e) => e.1 = v,
None => c.0.push((k, v)),
}
}
(
Effect::Custom {
id: id.clone(),
payload: Some(Tag::Compound(java_order_compound(c))),
},
next,
)
}
DialogAction::ShowDialog(target) => {
let opened = match target {
DialogTarget::Inline(d) => Some((**d).clone()),
DialogTarget::Named(name) => dialog.registry.as_ref().and_then(|r| {
let i = r.0.iter().position(|(n, _)| n == name)?;
Some(from_registry(r, i))
}),
};
match opened {
Some(d) => (Effect::Nothing, Next::Open(Arc::new(d))),
None => {
log::warn!("dialog: cannot open the unknown dialog {target:?}");
(Effect::Nothing, next)
}
}
}
DialogAction::OpenUrl(_)
| DialogAction::CopyToClipboard(_)
| DialogAction::SuggestCommand(_)
| DialogAction::ChangePage(_)
| DialogAction::Other(_) => (Effect::Nothing, next),
})
}
fn trim_slash(s: &str) -> &str {
s.strip_prefix('/').unwrap_or(s)
}
#[derive(Debug, Clone)]
struct Value {
text: String,
tag: Tag,
}
fn values(
dialog: &Dialog,
given: &[(String, InputValue)],
) -> Result<Vec<(String, Value)>, DialogRefused> {
for (k, _) in given {
if !dialog.inputs.iter().any(|i| i.key == *k) {
return Err(DialogRefused::UnknownInput(k.clone()));
}
}
let mut out: Vec<(String, Value)> = Vec::new();
for input in &dialog.inputs {
let v = given
.iter()
.rev()
.find(|(k, _)| *k == input.key)
.map(|(_, v)| v);
let bad = || DialogRefused::BadValue(input.key.clone());
let value = match &input.kind {
InputKind::Text {
initial,
max_length,
multiline,
} => {
let text = match v {
None => truncate_utf16(initial, *max_length),
Some(InputValue::Text(t)) => typed(t, *max_length, *multiline),
Some(_) => return Err(bad()),
};
Value {
text: escape_without_quotes(&text),
tag: Tag::String(text),
}
}
InputKind::Bool {
initial,
on_true,
on_false,
} => {
let on = match v {
None => *initial,
Some(InputValue::Bool(b)) => *b,
Some(_) => return Err(bad()),
};
Value {
text: if on {
on_true.clone()
} else {
on_false.clone()
},
tag: Tag::Byte(i8::from(on)),
}
}
InputKind::SingleOption { options, initial } => {
let id = match v {
None => options.get(*initial).map(|o| o.0.clone()).ok_or_else(bad)?,
Some(InputValue::Option(id)) if options.iter().any(|o| o.0 == *id) => {
id.clone()
}
Some(_) => return Err(bad()),
};
Value {
text: id.clone(),
tag: Tag::String(id),
}
}
InputKind::NumberRange {
start,
end,
initial,
step,
} => {
let r = Range {
start: *start,
end: *end,
initial: *initial,
step: *step,
};
let slider = match v {
None => r.initial_slider(),
Some(InputValue::Number(n)) => r.to_slider(*n).clamp(0.0, 1.0),
Some(_) => return Err(bad()),
};
let n = r.scaled(slider);
Value {
text: number_text(n),
tag: Tag::Float(n),
}
}
InputKind::Other(_) => continue,
};
match out.iter_mut().find(|(k, _)| *k == input.key) {
Some(e) => e.1 = value,
None => out.push((input.key.clone(), value)),
}
}
Ok(out)
}
fn typed(s: &str, max: i32, multiline: bool) -> String {
let filtered: String = s
.chars()
.filter(|&c| (c != '§' && c >= ' ' && c != '\u{7f}') || (multiline && c == '\n'))
.collect();
truncate_utf16(&filtered, max)
}
fn truncate_utf16(s: &str, max: i32) -> String {
let max = usize::try_from(max).unwrap_or(0);
let mut n = 0;
let mut out = String::new();
for c in s.chars() {
n += c.len_utf16();
if n > max {
break;
}
out.push(c);
}
out
}
fn escape_without_quotes(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'"' | '\'' | '\\' => {
out.push('\\');
out.push(c);
}
'\u{8}' => out.push_str("\\b"),
'\t' => out.push_str("\\t"),
'\n' => out.push_str("\\n"),
'\u{c}' => out.push_str("\\f"),
'\r' => out.push_str("\\r"),
c if c < ' ' => out.push_str(&format!("\\x{:02X}", c as u32)),
c => out.push(c),
}
}
out
}
fn instantiate(template: &str, values: &[(String, Value)]) -> String {
let b = template.as_bytes();
let mut out = String::new();
let mut start = 0;
let mut i = 0;
let mut any = false;
while let Some(off) = template[i..].find('$') {
let at = i + off;
if at + 1 < b.len() && b[at + 1] == b'(' {
let Some(close) = template[at + 1..].find(')').map(|c| at + 1 + c) else {
return template.to_owned();
};
let name = &template[at + 2..close];
if !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
return template.to_owned();
}
out.push_str(&template[start..at]);
if let Some((_, v)) = values.iter().find(|(k, _)| k == name) {
out.push_str(&v.text);
}
any = true;
start = close + 1;
i = start;
} else {
i = at + 1;
}
}
if !any {
return template.to_owned();
}
out.push_str(&template[start..]);
out
}
struct Range {
start: f32,
end: f32,
initial: Option<f32>,
step: Option<f32>,
}
impl Range {
fn initial_value(&self) -> f32 {
self.initial.unwrap_or((self.start + self.end) / 2.0)
}
fn to_slider(&self, v: f32) -> f32 {
if self.start == self.end {
0.5
} else {
(v - self.start) / (self.end - self.start)
}
}
fn initial_slider(&self) -> f32 {
self.to_slider(self.initial_value())
}
fn scaled(&self, slider: f32) -> f32 {
let in_range = self.start + slider * (self.end - self.start);
let Some(step) = self.step else {
return in_range;
};
let initial = self.initial_value();
let steps = java_round((in_range - initial) / step);
let result = initial + steps as f32 * step;
let s = self.to_slider(result);
if (0.0..=1.0).contains(&s) {
result
} else {
initial + (steps - steps.signum()) as f32 * step
}
}
}
fn java_round(x: f32) -> i32 {
if x.is_nan() {
0
} else {
(f64::from(x) + 0.5).floor() as i32
}
}
fn number_text(v: f32) -> String {
let i = v as i32;
if i as f32 == v {
i.to_string()
} else {
java_float_string(v)
}
}
fn java_float_string(v: f32) -> String {
if v.is_nan() {
return "NaN".into();
}
if v.is_infinite() {
return if v > 0.0 { "Infinity" } else { "-Infinity" }.into();
}
if v == 0.0 {
return if v.is_sign_negative() { "-0.0" } else { "0.0" }.into();
}
let sign = if v < 0.0 { "-" } else { "" };
let a = v.abs();
let e = format!("{a:e}");
let (mant, exp) = e.split_once('e').unwrap_or((&e, "0"));
let exp: i32 = exp.parse().unwrap_or(0);
let digits: String = mant.chars().filter(char::is_ascii_digit).collect();
if (1e-3..1e7).contains(&a) {
let point = exp + 1;
let s = if point <= 0 {
format!("0.{}{digits}", "0".repeat((-point) as usize))
} else if point as usize >= digits.len() {
format!("{digits}{}.0", "0".repeat(point as usize - digits.len()))
} else {
format!(
"{}.{}",
&digits[..point as usize],
&digits[point as usize..]
)
};
format!("{sign}{s}")
} else {
let rest = if digits.len() > 1 { &digits[1..] } else { "0" };
format!("{sign}{}.{rest}E{exp}", &digits[..1])
}
}
fn java_hash(s: &str) -> i32 {
s.encode_utf16()
.fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c)))
}
fn java_iteration<V>(entries: impl Iterator<Item = (String, V)>) -> Vec<(String, V)> {
let mut v: Vec<(String, V)> = entries.collect();
let mut cap = 16usize;
while v.len() > cap / 4 * 3 {
cap *= 2;
}
v.sort_by_key(|(k, _)| {
let h = java_hash(k) as u32;
(h ^ (h >> 16)) as usize & (cap - 1)
});
v
}
fn java_order_compound(c: Compound) -> Compound {
Compound(java_iteration(
c.0.into_iter().map(|(k, t)| (k, java_order(t))),
))
}
fn java_order(t: Tag) -> Tag {
match t {
Tag::Compound(c) => Tag::Compound(java_order_compound(c)),
Tag::List(l) => Tag::List(List {
elem_type: l.elem_type,
items: l.items.into_iter().map(java_order).collect(),
}),
t => t,
}
}
#[cfg_attr(not(ghast_modern), allow(dead_code))]
pub(crate) fn custom_click_body(
id: &str,
payload: Option<&AnonNbt>,
) -> Result<bytes::Bytes, ghast_protocol::EncodeError> {
use ghast_protocol::McWrite;
let mut b = bytes::BytesMut::new();
b.put_string(id)?;
let nbt = payload.map_or(&[0u8][..], |p| &p.as_bytes()[..]);
b.put_len_varint(nbt.len())?;
b.extend_from_slice(nbt);
Ok(b.freeze())
}
pub(crate) fn payload_nbt(payload: Option<&Tag>) -> Option<AnonNbt> {
payload.and_then(|t| AnonNbt::from_tag(t).ok())
}
#[cfg_attr(not(ghast_modern), allow(dead_code))]
pub(crate) fn decode(nbt: &AnonNbt, registry: Option<&Arc<DialogRegistry>>) -> Dialog {
let tag = nbt.parse().ok().flatten();
let mut d = match &tag {
Some(Tag::Compound(c)) => from_compound(c, registry),
_ => unresolved(None, registry),
};
d.nbt = Some(nbt.clone());
d
}
#[cfg_attr(not(ghast_modern), allow(dead_code))]
pub(crate) fn decode_reference(id: i32, registry: Option<&Arc<DialogRegistry>>) -> Dialog {
match (registry, usize::try_from(id)) {
(Some(r), Ok(i)) if i < r.0.len() => from_registry(r, i),
_ => unresolved(Some(format!("#{id}")), registry),
}
}
fn from_registry(r: &Arc<DialogRegistry>, i: usize) -> Dialog {
let (name, data) = &r.0[i];
let mut d = match data {
Some(Tag::Compound(c)) => {
let mut d = from_compound(c, Some(r));
d.nbt = data.as_ref().and_then(|t| AnonNbt::from_tag(t).ok());
d
}
_ => unresolved(None, Some(r)),
};
d.registry_name = Some(name.clone());
d
}
fn unresolved(name: Option<String>, registry: Option<&Arc<DialogRegistry>>) -> Dialog {
Dialog {
kind: DialogKind::Unresolved,
title: String::new(),
external_title: None,
can_close_with_escape: true,
pause: true,
after_action: AfterAction::Close,
body: Vec::new(),
inputs: Vec::new(),
buttons: Vec::new(),
exit: None,
on_cancel: None,
registry_name: name,
nbt: None,
registry: registry.cloned(),
}
}
fn element(t: &Tag) -> &Tag {
match t {
Tag::Compound(c) if c.0.len() == 1 && c.0[0].0.is_empty() => &c.0[0].1,
t => t,
}
}
fn short(id: &str) -> &str {
id.strip_prefix("minecraft:").unwrap_or(id)
}
fn text(t: Option<&Tag>) -> String {
match t {
Some(Tag::String(s)) => s.clone(),
Some(t) => AnonNbt::from_tag(t)
.map(|n| ghast_protocol::chat::nbt_to_plain_text(&n))
.unwrap_or_default(),
None => String::new(),
}
}
fn string(c: &Compound, k: &str) -> Option<String> {
match c.get(k) {
Some(Tag::String(s)) => Some(s.clone()),
_ => None,
}
}
fn number(c: &Compound, k: &str) -> Option<f64> {
Some(match c.get(k)? {
Tag::Byte(v) => f64::from(*v),
Tag::Short(v) => f64::from(*v),
Tag::Int(v) => f64::from(*v),
Tag::Long(v) => *v as f64,
Tag::Float(v) => f64::from(*v),
Tag::Double(v) => *v,
_ => return None,
})
}
fn boolean(c: &Compound, k: &str, default: bool) -> bool {
match c.get(k) {
Some(Tag::String(s)) => s == "true",
Some(_) => number(c, k).is_some_and(|v| v != 0.0),
None => default,
}
}
fn int(c: &Compound, k: &str, default: i32) -> i32 {
number(c, k).map_or(default, |v| v as i32)
}
fn float(c: &Compound, k: &str) -> Option<f32> {
number(c, k).map(|v| v as f32)
}
fn nbt_of(t: Option<&Tag>) -> Option<AnonNbt> {
t.and_then(|t| AnonNbt::from_tag(t).ok())
}
fn from_compound(c: &Compound, registry: Option<&Arc<DialogRegistry>>) -> Dialog {
let ty = string(c, "type").unwrap_or_default();
let button = |t: Option<&Tag>| match t {
Some(Tag::Compound(b)) => Some(button_of(b, registry)),
_ => None,
};
let exit = button(c.get("exit_action"));
let columns = int(c, "columns", 2);
let (kind, buttons, on_cancel) = match short(&ty) {
"notice" => {
let b = button(c.get("action")).unwrap_or_else(|| DialogButton {
label: "gui.ok".into(),
tooltip: None,
width: 150,
action: None,
});
let cancel = b.action.clone();
(DialogKind::Notice, vec![b], cancel)
}
"confirmation" => {
let yes = button(c.get("yes"));
let no = button(c.get("no"));
let cancel = no.as_ref().and_then(|b| b.action.clone());
(
DialogKind::Confirmation,
yes.into_iter().chain(no).collect(),
cancel,
)
}
"multi_action" => {
let actions = match c.get("actions") {
Some(Tag::List(l)) => l
.items
.iter()
.filter_map(|t| button(Some(element(t))))
.collect(),
_ => Vec::new(),
};
let cancel = exit.as_ref().and_then(|b| b.action.clone());
(DialogKind::MultiAction { columns }, actions, cancel)
}
"dialog_list" => {
let width = int(c, "button_width", 150);
let buttons = list_targets(c.get("dialogs"), registry)
.into_iter()
.map(|t| {
let label = match &t {
DialogTarget::Inline(d) => {
d.external_title.clone().unwrap_or_else(|| d.title.clone())
}
DialogTarget::Named(n) => registry
.and_then(|r| r.0.iter().find(|(k, _)| k == n))
.and_then(|(_, t)| t.as_ref()?.as_compound())
.map_or_else(
|| n.clone(),
|d| text(d.get("external_title").or_else(|| d.get("title"))),
),
};
DialogButton {
label,
tooltip: None,
width,
action: Some(DialogAction::ShowDialog(t)),
}
})
.collect();
let cancel = exit.as_ref().and_then(|b| b.action.clone());
(DialogKind::DialogList { columns }, buttons, cancel)
}
"server_links" => {
let cancel = exit.as_ref().and_then(|b| b.action.clone());
(DialogKind::ServerLinks { columns }, Vec::new(), cancel)
}
other => (DialogKind::Other(other.to_owned()), Vec::new(), None),
};
let after_action = match string(c, "after_action").as_deref() {
Some("none") => AfterAction::None,
Some("wait_for_response") => AfterAction::WaitForResponse,
_ => AfterAction::Close,
};
let body = match c.get("body") {
Some(Tag::List(l)) => l.items.iter().map(|t| body_of(element(t))).collect(),
Some(t) => vec![body_of(t)],
None => Vec::new(),
};
let inputs = match c.get("inputs") {
Some(Tag::List(l)) => l
.items
.iter()
.filter_map(|t| element(t).as_compound().map(input_of))
.collect(),
_ => Vec::new(),
};
Dialog {
kind,
title: text(c.get("title")),
external_title: c.get("external_title").map(|t| text(Some(t))),
can_close_with_escape: boolean(c, "can_close_with_escape", true),
pause: boolean(c, "pause", true),
after_action,
body,
inputs,
buttons,
exit: if matches!(short(&ty), "notice" | "confirmation") {
None
} else {
exit
},
on_cancel,
registry_name: None,
nbt: None,
registry: registry.cloned(),
}
}
fn list_targets(t: Option<&Tag>, registry: Option<&Arc<DialogRegistry>>) -> Vec<DialogTarget> {
let one = |t: &Tag| match t {
Tag::String(s) if !s.starts_with('#') => Some(DialogTarget::Named(qualified(s))),
Tag::Compound(c) => Some(DialogTarget::Inline(Box::new(from_compound(c, registry)))),
_ => None,
};
match t {
Some(Tag::List(l)) => l.items.iter().filter_map(|t| one(element(t))).collect(),
Some(t) => one(t).into_iter().collect(),
None => Vec::new(),
}
}
fn qualified(id: &str) -> String {
if id.contains(':') {
id.to_owned()
} else {
format!("minecraft:{id}")
}
}
fn button_of(b: &Compound, registry: Option<&Arc<DialogRegistry>>) -> DialogButton {
DialogButton {
label: text(b.get("label")),
tooltip: b.get("tooltip").map(|t| text(Some(t))),
width: int(b, "width", 150),
action: match b.get("action") {
Some(Tag::Compound(a)) => Some(action_of(a, registry)),
_ => None,
},
}
}
fn action_of(a: &Compound, registry: Option<&Arc<DialogRegistry>>) -> DialogAction {
let ty = string(a, "type").unwrap_or_default();
let s = |k| string(a, k).unwrap_or_default();
match short(&ty) {
"run_command" => DialogAction::RunCommand(s("command")),
"dynamic/run_command" => DialogAction::CommandTemplate(s("template")),
"custom" => DialogAction::Custom {
id: qualified(&s("id")),
payload: nbt_of(a.get("payload")),
},
"dynamic/custom" => DialogAction::CustomTemplate {
id: qualified(&s("id")),
additions: nbt_of(a.get("additions")),
},
"show_dialog" => match a.get("dialog") {
Some(Tag::String(n)) => DialogAction::ShowDialog(DialogTarget::Named(qualified(n))),
Some(Tag::Compound(c)) => {
let mut d = from_compound(c, registry);
d.nbt = nbt_of(a.get("dialog"));
DialogAction::ShowDialog(DialogTarget::Inline(Box::new(d)))
}
_ => DialogAction::Other(ty.clone()),
},
"open_url" => DialogAction::OpenUrl(s("url")),
"copy_to_clipboard" => DialogAction::CopyToClipboard(s("value")),
"suggest_command" => DialogAction::SuggestCommand(s("command")),
"change_page" => DialogAction::ChangePage(int(a, "page", 1)),
_ => DialogAction::Other(ty.clone()),
}
}
fn body_of(t: &Tag) -> DialogBody {
let Some(c) = t.as_compound() else {
return DialogBody::Other(String::new());
};
let ty = string(c, "type").unwrap_or_default();
match short(&ty) {
"plain_message" => DialogBody::Text(text(c.get("contents"))),
"item" => {
let (id, count) = match c.get("item") {
Some(Tag::Compound(i)) => (string(i, "id").unwrap_or_default(), int(i, "count", 1)),
Some(Tag::String(s)) => (s.clone(), 1),
_ => (String::new(), 1),
};
let description = match c.get("description") {
Some(Tag::Compound(d)) if d.get("contents").is_some() => {
Some(text(d.get("contents")))
}
Some(t) => Some(text(Some(t))),
None => None,
};
DialogBody::Item {
id,
count,
description,
}
}
other => DialogBody::Other(other.to_owned()),
}
}
fn input_of(c: &Compound) -> DialogInput {
let ty = string(c, "type").unwrap_or_default();
let kind = match short(&ty) {
"text" => InputKind::Text {
initial: string(c, "initial").unwrap_or_default(),
max_length: int(c, "max_length", 32),
multiline: c.get("multiline").is_some(),
},
"boolean" => InputKind::Bool {
initial: boolean(c, "initial", false),
on_true: string(c, "on_true").unwrap_or_else(|| "true".into()),
on_false: string(c, "on_false").unwrap_or_else(|| "false".into()),
},
"single_option" => {
let options: Vec<(String, String, bool)> = match c.get("options") {
Some(Tag::List(l)) => l
.items
.iter()
.filter_map(|t| match element(t) {
Tag::String(id) => Some((id.clone(), id.clone(), false)),
Tag::Compound(o) => {
let id = string(o, "id")?;
let display = o
.get("display")
.map_or_else(|| id.clone(), |t| text(Some(t)));
Some((id, display, boolean(o, "initial", false)))
}
_ => None,
})
.collect(),
_ => Vec::new(),
};
let initial = options.iter().position(|o| o.2).unwrap_or(0);
InputKind::SingleOption {
options: options.into_iter().map(|(id, d, _)| (id, d)).collect(),
initial,
}
}
"number_range" => InputKind::NumberRange {
start: float(c, "start").unwrap_or(0.0),
end: float(c, "end").unwrap_or(0.0),
initial: float(c, "initial"),
step: float(c, "step"),
},
other => InputKind::Other(other.to_owned()),
};
DialogInput {
key: string(c, "key").unwrap_or_default(),
label: text(c.get("label")),
kind,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn hex(s: &str) -> Vec<u8> {
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
.collect()
}
fn nbt(s: &str) -> AnonNbt {
AnonNbt::from_bytes(bytes::Bytes::from(hex(s))).unwrap()
}
#[test]
fn answers_match_the_vanilla_client() {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../tests/golden/26.2/dialog_answers.txt"
);
let text = std::fs::read_to_string(path).unwrap();
let mut n = 0;
for line in text
.lines()
.filter(|l| !l.starts_with('#') && !l.is_empty())
{
let f: Vec<&str> = line.split(' ').collect();
let (name, dialog, pick, given) = (f[0], nbt(f[1]), f[2], nbt(f[3]));
let d = decode(&dialog, None);
let mut answer = match pick {
"exit" => DialogAnswer::exit(),
"close" => DialogAnswer::close(),
p => DialogAnswer::button(p.strip_prefix("button_").unwrap().parse().unwrap()),
};
let Some(Tag::Compound(given)) = given.parse().unwrap() else {
panic!("{name}: values")
};
for (k, v) in given.0 {
let kind = &d.inputs.iter().find(|i| i.key == k).unwrap().kind;
let v = match (kind, v) {
(InputKind::Text { .. }, Tag::String(s)) => InputValue::Text(s),
(InputKind::SingleOption { .. }, Tag::String(s)) => InputValue::Option(s),
(InputKind::Bool { .. }, Tag::Byte(b)) => InputValue::Bool(b != 0),
(InputKind::NumberRange { .. }, Tag::Float(x)) => InputValue::Number(x),
(k, v) => panic!("{name}: {k:?} {v:?}"),
};
answer = answer.with_value(k, v);
}
let (effect, _) = resolve(&d, &answer).unwrap();
let got = match effect {
Effect::Nothing => None,
Effect::Custom { id, payload } => Some((
"custom_click_action",
custom_click_body(&id, payload_nbt(payload.as_ref()).as_ref()).unwrap(),
)),
Effect::Command(c) => {
use ghast_protocol::McWrite;
let mut b = bytes::BytesMut::new();
b.put_string(&c).unwrap();
Some(("chat_command", b.freeze()))
}
};
match (f[4], got) {
("none" | "client", None) => {}
(kind, Some((k, body))) => {
assert_eq!(kind, k, "{name}");
assert_eq!(hex(f[5]), body.to_vec(), "{name}");
}
(kind, got) => panic!("{name}: vanilla {kind}, ours {got:?}"),
}
n += 1;
}
assert!(n >= 12, "{n}");
}
#[test]
fn decodes_the_dialog_model() {
let text = std::fs::read_to_string(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../tests/golden/26.2/dialog_answers.txt"
))
.unwrap();
let line = text
.lines()
.find(|l| l.starts_with("template_login "))
.unwrap();
let d = decode(&nbt(line.split(' ').nth(1).unwrap()), None);
assert_eq!(d.kind, DialogKind::MultiAction { columns: 2 });
assert_eq!(d.title, "Login");
assert!(d.can_close_with_escape && d.pause);
assert_eq!(d.after_action, AfterAction::Close);
assert_eq!(d.buttons.len(), 6);
assert_eq!(d.buttons[0].label, "Run");
assert_eq!(d.buttons[0].width, 150);
assert_eq!(
d.buttons[0].action,
Some(DialogAction::RunCommand("/login fixed".into()))
);
assert_eq!(d.buttons[3].action, None);
assert_eq!(
d.buttons[5].action,
Some(DialogAction::OpenUrl("https://example.com".into()))
);
assert_eq!(d.exit.as_ref().unwrap().label, "Exit");
assert!(matches!(
d.on_cancel,
Some(DialogAction::CustomTemplate { .. })
));
let keys: Vec<&str> = d.inputs.iter().map(|i| i.key.as_str()).collect();
assert_eq!(keys, ["pw", "n", "big", "keep"]);
assert_eq!(
d.inputs[3].kind,
InputKind::Bool {
initial: true,
on_true: "yes".into(),
on_false: "no".into()
}
);
let mut c = Compound::default();
c.0.push(("type".into(), Tag::String("minecraft:notice".into())));
c.0.push(("title".into(), Tag::String("Hi".into())));
let d = decode(&AnonNbt::from_tag(&Tag::Compound(c)).unwrap(), None);
assert_eq!(d.buttons.len(), 1);
assert_eq!(d.buttons[0].label, "gui.ok");
assert_eq!(d.on_cancel, None);
let mut d2 = d.clone();
d2.can_close_with_escape = false;
assert_eq!(
resolve(&d2, &DialogAnswer::close()),
Err(DialogRefused::CannotClose)
);
assert_eq!(
resolve(&d, &DialogAnswer::button(1)),
Err(DialogRefused::NoButton(1))
);
assert_eq!(
resolve(
&d,
&DialogAnswer::button(0).with_value("x", InputValue::Bool(true))
),
Err(DialogRefused::UnknownInput("x".into()))
);
}
#[test]
fn registry_dialogs() {
let notice = |title: &str, action: Option<Tag>| {
let mut c = Compound::default();
c.0.push(("type".into(), Tag::String("notice".into())));
c.0.push(("title".into(), Tag::String(title.into())));
if let Some(a) = action {
let mut b = Compound::default();
b.0.push(("label".into(), Tag::String("Go".into())));
b.0.push(("action".into(), a));
c.0.push(("action".into(), Tag::Compound(b)));
}
Tag::Compound(c)
};
let mut show = Compound::default();
show.0
.push(("type".into(), Tag::String("show_dialog".into())));
show.0
.push(("dialog".into(), Tag::String("test:second".into())));
let reg = Arc::new(DialogRegistry(vec![
("minecraft:server_links".into(), None),
(
"test:first".into(),
Some(notice("First", Some(Tag::Compound(show)))),
),
("test:second".into(), Some(notice("Second", None))),
]));
let d = decode_reference(0, Some(®));
assert_eq!(d.kind, DialogKind::Unresolved);
assert_eq!(d.registry_name.as_deref(), Some("minecraft:server_links"));
let d = decode_reference(1, Some(®));
assert_eq!(
(d.kind.clone(), d.title.as_str()),
(DialogKind::Notice, "First")
);
let (effect, next) = resolve(&d, &DialogAnswer::button(0)).unwrap();
assert_eq!(effect, Effect::Nothing);
let Next::Open(second) = next else {
panic!("{next:?}")
};
assert_eq!(second.title, "Second");
assert_eq!(second.registry_name.as_deref(), Some("test:second"));
assert_eq!(decode_reference(7, Some(®)).kind, DialogKind::Unresolved);
}
#[test]
fn java_helpers() {
for (v, s) in [
(1.0f32, "1"),
(2.5, "2.5"),
(0.0004, "4.0E-4"),
(0.001, "0.001"),
(1.5e7, "15000000"),
(1.5e10, "15000000000"),
(-0.25, "-0.25"),
(1234567.5, "1234567.5"),
(1.25e-5, "1.25E-5"),
(3.4e38, "3.4E38"),
] {
let got = if v.abs() > 2.2e9 {
java_float_string(v)
} else {
number_text(v)
};
if s == "15000000000" {
assert_eq!(java_float_string(v), "1.5E10");
continue;
}
assert_eq!(got, s, "{v}");
}
assert_eq!(java_round(2.5), 3);
assert_eq!(java_round(-2.5), -2);
assert_eq!(java_round(0.499_999_97), 0);
assert_eq!(java_hash("Aa"), java_hash("BB"));
assert_eq!(java_hash("hello"), 99_162_322);
assert_eq!(
escape_without_quotes("a\"b'c\\d\n\u{1}"),
"a\\\"b\\'c\\\\d\\n\\x01"
);
let v = |k: &str, t: &str| {
(
k.to_owned(),
Value {
text: t.into(),
tag: Tag::Byte(0),
},
)
};
let vals = [v("a", "1"), v("b", "2")];
assert_eq!(instantiate("x $(a) $(b)$(c) y", &vals), "x 1 2 y");
assert_eq!(instantiate("no vars", &vals), "no vars");
assert_eq!(instantiate("$(a", &vals), "$(a");
assert_eq!(typed("a§b\nc\u{7f}d", 10, false), "abcd");
assert_eq!(typed("a\nb", 10, true), "a\nb");
assert_eq!(typed("ab😀c", 3, false), "ab");
}
}