Tabs to spaces

This commit is contained in:
Thinkofdeath 2015-09-10 11:58:42 +01:00
parent 6f6d3c96ca
commit e392dafd82
3 changed files with 387 additions and 387 deletions

View File

@ -4,251 +4,251 @@ use std::fmt;
#[derive(Debug)] #[derive(Debug)]
pub enum Component { pub enum Component {
Text(TextComponent), Text(TextComponent),
None None
} }
impl Component { impl Component {
pub fn from_value(v: &serde_json::Value) -> Self { pub fn from_value(v: &serde_json::Value) -> Self {
let modifier = Modifier::from_value(v); let modifier = Modifier::from_value(v);
if let Some(val) = v.as_string() { if let Some(val) = v.as_string() {
Component::Text(TextComponent{text: val.to_owned(), modifier: modifier}) Component::Text(TextComponent{text: val.to_owned(), modifier: modifier})
} else if v.find("text").is_some(){ } else if v.find("text").is_some(){
Component::Text(TextComponent::from_value(v, modifier)) Component::Text(TextComponent::from_value(v, modifier))
} else { } else {
Component::None Component::None
} }
} }
pub fn to_value(&self) -> serde_json::Value { pub fn to_value(&self) -> serde_json::Value {
unimplemented!() unimplemented!()
} }
} }
impl fmt::Display for Component { impl fmt::Display for Component {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { match *self {
Component::Text(ref txt) => write!(f, "{}", txt), Component::Text(ref txt) => write!(f, "{}", txt),
Component::None => Result::Ok(()), Component::None => Result::Ok(()),
} }
} }
} }
impl Default for Component { impl Default for Component {
fn default() -> Self { fn default() -> Self {
Component::None Component::None
} }
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Modifier { pub struct Modifier {
pub extra: Option<Vec<Component>>, pub extra: Option<Vec<Component>>,
pub bold: Option<bool>, pub bold: Option<bool>,
pub italic: Option<bool>, pub italic: Option<bool>,
pub underlined: Option<bool>, pub underlined: Option<bool>,
pub strikethrough: Option<bool>, pub strikethrough: Option<bool>,
pub obfuscated: Option<bool>, pub obfuscated: Option<bool>,
pub color: Option<Color>, pub color: Option<Color>,
// click_event // click_event
// hover_event // hover_event
// insertion // insertion
} }
impl Modifier { impl Modifier {
pub fn from_value(v: &serde_json::Value) -> Self { pub fn from_value(v: &serde_json::Value) -> Self {
let mut m = Modifier { let mut m = Modifier {
bold: v.find("bold").map_or(Option::None, |v| v.as_boolean()), bold: v.find("bold").map_or(Option::None, |v| v.as_boolean()),
italic: v.find("italic").map_or(Option::None, |v| v.as_boolean()), italic: v.find("italic").map_or(Option::None, |v| v.as_boolean()),
underlined: v.find("underlined").map_or(Option::None, |v| v.as_boolean()), underlined: v.find("underlined").map_or(Option::None, |v| v.as_boolean()),
strikethrough: v.find("strikethrough").map_or(Option::None, |v| v.as_boolean()), strikethrough: v.find("strikethrough").map_or(Option::None, |v| v.as_boolean()),
obfuscated: v.find("obfuscated").map_or(Option::None, |v| v.as_boolean()), obfuscated: v.find("obfuscated").map_or(Option::None, |v| v.as_boolean()),
color: v.find("color").map_or(Option::None, |v| v.as_string()).map(|v| Color::from_string(&v.to_owned())), color: v.find("color").map_or(Option::None, |v| v.as_string()).map(|v| Color::from_string(&v.to_owned())),
extra: Option::None, extra: Option::None,
}; };
if let Some(extra) = v.find("extra") { if let Some(extra) = v.find("extra") {
if let Some(data) = extra.as_array() { if let Some(data) = extra.as_array() {
let mut ex = Vec::new(); let mut ex = Vec::new();
for e in data { for e in data {
ex.push(Component::from_value(e)); ex.push(Component::from_value(e));
} }
m.extra = Some(ex); m.extra = Some(ex);
} }
} }
m m
} }
pub fn to_value(&self) -> serde_json::Value { pub fn to_value(&self) -> serde_json::Value {
unimplemented!() unimplemented!()
} }
} }
#[derive(Debug)] #[derive(Debug)]
pub struct TextComponent { pub struct TextComponent {
pub text: String, pub text: String,
pub modifier: Modifier, pub modifier: Modifier,
} }
impl TextComponent { impl TextComponent {
pub fn from_value(v: &serde_json::Value, modifier: Modifier) -> Self { pub fn from_value(v: &serde_json::Value, modifier: Modifier) -> Self {
TextComponent { TextComponent {
text: v.find("text").unwrap().as_string().unwrap_or("").to_owned(), text: v.find("text").unwrap().as_string().unwrap_or("").to_owned(),
modifier: modifier, modifier: modifier,
} }
} }
pub fn to_value(&self) -> serde_json::Value { pub fn to_value(&self) -> serde_json::Value {
unimplemented!() unimplemented!()
} }
} }
impl fmt::Display for TextComponent { impl fmt::Display for TextComponent {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{}", self.text)); try!(write!(f, "{}", self.text));
if let Some(ref extra) = self.modifier.extra { if let Some(ref extra) = self.modifier.extra {
for c in extra { for c in extra {
try!(write!(f, "{}", c)); try!(write!(f, "{}", c));
} }
} }
Result::Ok(()) Result::Ok(())
} }
} }
#[derive(Debug)] #[derive(Debug)]
pub enum Color { pub enum Color {
Black, Black,
DarkBlue, DarkBlue,
DarkGreen, DarkGreen,
DarkAqua, DarkAqua,
DarkRed, DarkRed,
DarkPurple, DarkPurple,
Gold, Gold,
Gray, Gray,
DarkGray, DarkGray,
Blue, Blue,
Green, Green,
Aqua, Aqua,
Red, Red,
LightPurple, LightPurple,
Yellow, Yellow,
White, White,
RGB(u8, u8, u8) RGB(u8, u8, u8)
} }
impl fmt::Display for Color { impl fmt::Display for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_string()) write!(f, "{}", self.to_string())
} }
} }
impl Color { impl Color {
fn from_string(val: &String) -> Self { fn from_string(val: &String) -> Self {
match val.as_ref() { match val.as_ref() {
"black" => Color::Black, "black" => Color::Black,
"dark_blue" => Color::DarkBlue, "dark_blue" => Color::DarkBlue,
"dark_green" => Color::DarkGreen, "dark_green" => Color::DarkGreen,
"dark_aqua" => Color::DarkAqua, "dark_aqua" => Color::DarkAqua,
"dark_red" => Color::DarkRed, "dark_red" => Color::DarkRed,
"dark_purple" => Color::DarkPurple, "dark_purple" => Color::DarkPurple,
"gold" => Color::Gold, "gold" => Color::Gold,
"gray" => Color::Gray, "gray" => Color::Gray,
"dark_gray" => Color::DarkGray, "dark_gray" => Color::DarkGray,
"blue" => Color::Blue, "blue" => Color::Blue,
"green" => Color::Green, "green" => Color::Green,
"aqua" => Color::Aqua, "aqua" => Color::Aqua,
"red" => Color::Red, "red" => Color::Red,
"light_purple" => Color::LightPurple, "light_purple" => Color::LightPurple,
"yellow" => Color::Yellow, "yellow" => Color::Yellow,
"white" => Color::White, "white" => Color::White,
val if val.len() == 7 && val.as_bytes()[0] == b'#' => { val if val.len() == 7 && val.as_bytes()[0] == b'#' => {
let r = match u8::from_str_radix(&val[1..3], 16) { let r = match u8::from_str_radix(&val[1..3], 16) {
Ok(r) => r, Ok(r) => r,
Err(_) => return Color::White, Err(_) => return Color::White,
}; };
let g = match u8::from_str_radix(&val[3..5], 16) { let g = match u8::from_str_radix(&val[3..5], 16) {
Ok(g) => g, Ok(g) => g,
Err(_) => return Color::White, Err(_) => return Color::White,
}; };
let b = match u8::from_str_radix(&val[5..7], 16) { let b = match u8::from_str_radix(&val[5..7], 16) {
Ok(b) => b, Ok(b) => b,
Err(_) => return Color::White, Err(_) => return Color::White,
}; };
Color::RGB( Color::RGB(
r, r,
g, g,
b b
) )
} }
_ => Color::White, _ => Color::White,
} }
} }
fn to_string(&self) -> String { fn to_string(&self) -> String {
match *self { match *self {
Color::Black => "black".to_owned(), Color::Black => "black".to_owned(),
Color::DarkBlue => "dark_blue".to_owned(), Color::DarkBlue => "dark_blue".to_owned(),
Color::DarkGreen => "dark_green".to_owned(), Color::DarkGreen => "dark_green".to_owned(),
Color::DarkAqua => "dark_aqua".to_owned(), Color::DarkAqua => "dark_aqua".to_owned(),
Color::DarkRed => "dark_red".to_owned(), Color::DarkRed => "dark_red".to_owned(),
Color::DarkPurple => "dark_purple".to_owned(), Color::DarkPurple => "dark_purple".to_owned(),
Color::Gold => "gold".to_owned(), Color::Gold => "gold".to_owned(),
Color::Gray => "gray".to_owned(), Color::Gray => "gray".to_owned(),
Color::DarkGray => "dark_gray".to_owned(), Color::DarkGray => "dark_gray".to_owned(),
Color::Blue => "blue".to_owned(), Color::Blue => "blue".to_owned(),
Color::Green => "green".to_owned(), Color::Green => "green".to_owned(),
Color::Aqua => "aqua".to_owned(), Color::Aqua => "aqua".to_owned(),
Color::Red => "red".to_owned(), Color::Red => "red".to_owned(),
Color::LightPurple => "light_purple".to_owned(), Color::LightPurple => "light_purple".to_owned(),
Color::Yellow => "yellow".to_owned(), Color::Yellow => "yellow".to_owned(),
Color::White => "white".to_owned(), Color::White => "white".to_owned(),
Color::RGB(r, g, b) => format!("#{:02X}{:02X}{:02X}", r, g, b), Color::RGB(r, g, b) => format!("#{:02X}{:02X}{:02X}", r, g, b),
} }
} }
#[allow(dead_code)] #[allow(dead_code)]
fn to_rgb(&self) -> (u8, u8, u8) { fn to_rgb(&self) -> (u8, u8, u8) {
match *self { match *self {
Color::Black =>(0, 0, 0), Color::Black =>(0, 0, 0),
Color::DarkBlue =>(0, 0, 170), Color::DarkBlue =>(0, 0, 170),
Color::DarkGreen =>(0, 170, 0), Color::DarkGreen =>(0, 170, 0),
Color::DarkAqua =>(0, 170, 170), Color::DarkAqua =>(0, 170, 170),
Color::DarkRed =>(170, 0, 0), Color::DarkRed =>(170, 0, 0),
Color::DarkPurple =>(170, 0, 170), Color::DarkPurple =>(170, 0, 170),
Color::Gold =>(255, 170, 0), Color::Gold =>(255, 170, 0),
Color::Gray =>(170, 170, 170), Color::Gray =>(170, 170, 170),
Color::DarkGray =>(85, 85, 85), Color::DarkGray =>(85, 85, 85),
Color::Blue =>(85, 85, 255), Color::Blue =>(85, 85, 255),
Color::Green =>(85, 255, 85), Color::Green =>(85, 255, 85),
Color::Aqua =>(85, 255, 255), Color::Aqua =>(85, 255, 255),
Color::Red =>(255, 85, 85), Color::Red =>(255, 85, 85),
Color::LightPurple =>(255, 85, 255), Color::LightPurple =>(255, 85, 255),
Color::Yellow =>(255, 255, 85), Color::Yellow =>(255, 255, 85),
Color::White =>(255, 255, 255), Color::White =>(255, 255, 255),
Color::RGB(r, g, b) => (r, g, b), Color::RGB(r, g, b) => (r, g, b),
} }
} }
} }
#[test] #[test]
fn test_color_from() { fn test_color_from() {
let test = Color::from_string(&"#FF0000".to_owned()); let test = Color::from_string(&"#FF0000".to_owned());
match test { match test {
Color::RGB(r, g, b) => assert!(r == 255 && g == 0 && b == 0), Color::RGB(r, g, b) => assert!(r == 255 && g == 0 && b == 0),
_ => panic!("Wrong type"), _ => panic!("Wrong type"),
} }
let test = Color::from_string(&"#123456".to_owned()); let test = Color::from_string(&"#123456".to_owned());
match test { match test {
Color::RGB(r, g, b) => assert!(r == 0x12 && g == 0x34 && b == 0x56), Color::RGB(r, g, b) => assert!(r == 0x12 && g == 0x34 && b == 0x56),
_ => panic!("Wrong type"), _ => panic!("Wrong type"),
} }
let test = Color::from_string(&"red".to_owned()); let test = Color::from_string(&"red".to_owned());
match test { match test {
Color::Red => {}, Color::Red => {},
_ => panic!("Wrong type"), _ => panic!("Wrong type"),
} }
let test = Color::from_string(&"dark_blue".to_owned()); let test = Color::from_string(&"dark_blue".to_owned());
match test { match test {
Color::DarkBlue => {}, Color::DarkBlue => {},
_ => panic!("Wrong type"), _ => panic!("Wrong type"),
} }
} }

View File

@ -3,9 +3,9 @@ extern crate serde_json;
extern crate hyper; extern crate hyper;
pub struct Profile { pub struct Profile {
pub username: String, pub username: String,
pub id: String, pub id: String,
pub access_token: String pub access_token: String
} }
const JOIN_URL: &'static str = "https://sessionserver.mojang.com/session/minecraft/join"; const JOIN_URL: &'static str = "https://sessionserver.mojang.com/session/minecraft/join";
@ -54,12 +54,12 @@ impl Profile {
} }
fn twos_compliment(data: &mut Vec<u8>) { fn twos_compliment(data: &mut Vec<u8>) {
let mut carry = true; let mut carry = true;
for i in (0 .. data.len()).rev() { for i in (0 .. data.len()).rev() {
data[i] = !data[i]; data[i] = !data[i];
if carry { if carry {
carry = data[i] == 0xFF; carry = data[i] == 0xFF;
data[i] += 1; data[i] += 1;
} }
} }
} }

View File

@ -1,186 +1,186 @@
state_packets!( state_packets!(
handshake Handshaking { handshake Handshaking {
serverbound Serverbound { serverbound Serverbound {
// Handshake is the first packet sent in the protocol. // Handshake is the first packet sent in the protocol.
// Its used for deciding if the request is a client // Its used for deciding if the request is a client
// is requesting status information about the server // is requesting status information about the server
// (MOTD, players etc) or trying to login to the server. // (MOTD, players etc) or trying to login to the server.
// //
// The host and port fields are not used by the vanilla // The host and port fields are not used by the vanilla
// server but are there for virtual server hosting to // server but are there for virtual server hosting to
// be able to redirect a client to a target server with // be able to redirect a client to a target server with
// a single address + port. // a single address + port.
// //
// Some modified servers/proxies use the handshake field // Some modified servers/proxies use the handshake field
// differently, packing information into the field other // differently, packing information into the field other
// than the hostname due to the protocol not providing // than the hostname due to the protocol not providing
// any system for custom information to be transfered // any system for custom information to be transfered
// by the client to the server until after login. // by the client to the server until after login.
Handshake => 0x00 { Handshake => 0x00 {
// The protocol version of the connecting client // The protocol version of the connecting client
protocol_version: VarInt =, protocol_version: VarInt =,
// The hostname the client connected to // The hostname the client connected to
host: String =, host: String =,
// The port the client connected to // The port the client connected to
port: u16 =, port: u16 =,
// The next protocol state the client wants // The next protocol state the client wants
next: VarInt =, next: VarInt =,
} }
} }
clientbound Clientbound { clientbound Clientbound {
} }
} }
play Play { play Play {
serverbound Serverbound { serverbound Serverbound {
// TabComplete is sent by the client when the client presses tab in // TabComplete is sent by the client when the client presses tab in
// the chat box. // the chat box.
TabComplete => 0x00 { TabComplete => 0x00 {
text: String =, text: String =,
has_target: bool =, has_target: bool =,
target: Option<Position> = when(|p: &TabComplete| p.has_target == true), target: Option<Position> = when(|p: &TabComplete| p.has_target == true),
} }
// ChatMessage is sent by the client when it sends a chat message or // ChatMessage is sent by the client when it sends a chat message or
// executes a command (prefixed by '/'). // executes a command (prefixed by '/').
ChatMessage => 0x01 { ChatMessage => 0x01 {
message: String =, message: String =,
} }
// ClientStatus is sent to update the client's status // ClientStatus is sent to update the client's status
ClientStatus => 0x02 { ClientStatus => 0x02 {
action_id: VarInt =, action_id: VarInt =,
} }
// ClientSettings is sent by the client to update its current settings. // ClientSettings is sent by the client to update its current settings.
ClientSettings => 0x03 { ClientSettings => 0x03 {
locale: String =, locale: String =,
view_distance: u8 =, view_distance: u8 =,
chat_mode: u8 =, chat_mode: u8 =,
chat_colors: bool =, chat_colors: bool =,
displayed_skin_parts: u8 =, displayed_skin_parts: u8 =,
main_hand: VarInt =, main_hand: VarInt =,
} }
// ConfirmTransactionServerbound is a reply to ConfirmTransaction. // ConfirmTransactionServerbound is a reply to ConfirmTransaction.
ConfirmTransactionServerbound => 0x04 { ConfirmTransactionServerbound => 0x04 {
id: u8 =, id: u8 =,
action_number: i16 =, action_number: i16 =,
accepted: bool =, accepted: bool =,
} }
// EnchantItem is sent when the client enchants an item. // EnchantItem is sent when the client enchants an item.
EnchantItem => 0x05 { EnchantItem => 0x05 {
id: u8 =, id: u8 =,
enchantment: u8 =, enchantment: u8 =,
} }
// ClickWindow is sent when the client clicks in a window. // ClickWindow is sent when the client clicks in a window.
ClickWindow => 0x06 { ClickWindow => 0x06 {
id: u8 =, id: u8 =,
slot: i16 =, slot: i16 =,
button: u8 =, button: u8 =,
action_number: u16 =, action_number: u16 =,
mode: u8 =, mode: u8 =,
clicked_item: ()=, // TODO clicked_item: ()=, // TODO
} }
} }
clientbound Clientbound { clientbound Clientbound {
ServerMessage => 15 { ServerMessage => 15 {
message: format::Component =, message: format::Component =,
position: u8 =, position: u8 =,
} }
} }
} }
login Login { login Login {
serverbound Serverbound { serverbound Serverbound {
// LoginStart is sent immeditately after switching into the login // LoginStart is sent immeditately after switching into the login
// state. The passed username is used by the server to authenticate // state. The passed username is used by the server to authenticate
// the player in online mode. // the player in online mode.
LoginStart => 0 { LoginStart => 0 {
username: String =, username: String =,
} }
// EncryptionResponse is sent as a reply to EncryptionRequest. All // EncryptionResponse is sent as a reply to EncryptionRequest. All
// packets following this one must be encrypted with AES/CFB8 // packets following this one must be encrypted with AES/CFB8
// encryption. // encryption.
EncryptionResponse => 1 { EncryptionResponse => 1 {
// The key for the AES/CFB8 cipher encrypted with the // The key for the AES/CFB8 cipher encrypted with the
// public key // public key
shared_secret: LenPrefixed<VarInt, u8> =, shared_secret: LenPrefixed<VarInt, u8> =,
// The verify token from the request encrypted with the // The verify token from the request encrypted with the
// public key // public key
verify_token: LenPrefixed<VarInt, u8> =, verify_token: LenPrefixed<VarInt, u8> =,
} }
} }
clientbound Clientbound { clientbound Clientbound {
// LoginDisconnect is sent by the server if there was any issues // LoginDisconnect is sent by the server if there was any issues
// authenticating the player during login or the general server // authenticating the player during login or the general server
// issues (e.g. too many players). // issues (e.g. too many players).
LoginDisconnect => 0 { LoginDisconnect => 0 {
reason: format::Component =, reason: format::Component =,
} }
// EncryptionRequest is sent by the server if the server is in // EncryptionRequest is sent by the server if the server is in
// online mode. If it is not sent then its assumed the server is // online mode. If it is not sent then its assumed the server is
// in offline mode. // in offline mode.
EncryptionRequest => 1 { EncryptionRequest => 1 {
// Generally empty, left in from legacy auth // Generally empty, left in from legacy auth
// but is still used by the client if provided // but is still used by the client if provided
server_id: String =, server_id: String =,
// A RSA Public key serialized in x.509 PRIX format // A RSA Public key serialized in x.509 PRIX format
public_key: LenPrefixed<VarInt, u8> =, public_key: LenPrefixed<VarInt, u8> =,
// Token used by the server to verify encryption is working // Token used by the server to verify encryption is working
// correctly // correctly
verify_token: LenPrefixed<VarInt, u8> =, verify_token: LenPrefixed<VarInt, u8> =,
} }
// LoginSuccess is sent by the server if the player successfully // LoginSuccess is sent by the server if the player successfully
// authenicates with the session servers (online mode) or straight // authenicates with the session servers (online mode) or straight
// after LoginStart (offline mode). // after LoginStart (offline mode).
LoginSuccess => 2 { LoginSuccess => 2 {
// String encoding of a uuid (with hyphens) // String encoding of a uuid (with hyphens)
uuid: String =, uuid: String =,
username: String =, username: String =,
} }
// SetInitialCompression sets the compression threshold during the // SetInitialCompression sets the compression threshold during the
// login state. // login state.
SetInitialCompression => 3 { SetInitialCompression => 3 {
// Threshold where a packet should be sent compressed // Threshold where a packet should be sent compressed
threshold: VarInt =, threshold: VarInt =,
} }
} }
} }
status Status { status Status {
serverbound Serverbound { serverbound Serverbound {
// StatusRequest is sent by the client instantly after // StatusRequest is sent by the client instantly after
// switching to the Status protocol state and is used // switching to the Status protocol state and is used
// to signal the server to send a StatusResponse to the // to signal the server to send a StatusResponse to the
// client // client
StatusRequest => 0 { StatusRequest => 0 {
empty: () =, empty: () =,
} }
// StatusPing is sent by the client after recieving a // StatusPing is sent by the client after recieving a
// StatusResponse. The client uses the time from sending // StatusResponse. The client uses the time from sending
// the ping until the time of recieving a pong to measure // the ping until the time of recieving a pong to measure
// the latency between the client and the server. // the latency between the client and the server.
StatusPing => 1 { StatusPing => 1 {
ping: i64 =, ping: i64 =,
} }
} }
clientbound Clientbound { clientbound Clientbound {
// StatusResponse is sent as a reply to a StatusRequest. // StatusResponse is sent as a reply to a StatusRequest.
// The Status should contain a json encoded structure with // The Status should contain a json encoded structure with
// version information, a player sample, a description/MOTD // version information, a player sample, a description/MOTD
// and optionally a favicon. // and optionally a favicon.
// //
// The structure is as follows // The structure is as follows
// { // {
// "version": { // "version": {
// "name": "1.8.3", // "name": "1.8.3",
// "protocol": 47, // "protocol": 47,
// }, // },
// "players": { // "players": {
// "max": 20, // "max": 20,
// "online": 1, // "online": 1,
// "sample": [ // "sample": [
// {"name": "Thinkofdeath", "id": "4566e69f-c907-48ee-8d71-d7ba5aa00d20"} // {"name": "Thinkofdeath", "id": "4566e69f-c907-48ee-8d71-d7ba5aa00d20"}
// ] // ]
// }, // },
// "description": "Hello world", // "description": "Hello world",
// "favicon": "data:image/png;base64,<data>" // "favicon": "data:image/png;base64,<data>"
// } // }
StatusResponse => 0 { StatusResponse => 0 {
status: String =, status: String =,
} }
@ -190,6 +190,6 @@ state_packets!(
StatusPong => 1 { StatusPong => 1 {
ping: i64 =, ping: i64 =,
} }
} }
} }
); );