valence/tools/packet_inspector/src/config.rs
Ryan Johnson eaf1e18610
Reorganize Project (#321)
## Description

- `valence` and `valence_protocol` have been divided into smaller crates
in order to parallelize the build and improve IDE responsiveness. In the
process, code architecture has been made clearer by removing circular
dependencies between modules. `valence` is now just a shell around the
other crates.
- `workspace.packages` and `workspace.dependencies` are now used. This
makes dependency managements and crate configuration much easier.
- `valence_protocol` is no more. Most things from `valence_protocol`
ended up in `valence_core`. We won't advertise `valence_core` as a
general-purpose protocol library since it contains too much
valence-specific stuff. Closes #308.
- Networking code (login, initial TCP connection handling, etc.) has
been extracted into the `valence_network` crate. The API has been
expanded and improved with better defaults. Player counts and initial
connections to the server are now tracked separately. Player counts
function by default without any user configuration.
- Some crates like `valence_anvil`, `valence_network`,
`valence_player_list`, `valence_inventory`, etc. are now optional. They
can be enabled/disabled with feature flags and `DefaultPlugins` just
like bevy.
- Whole-server unit tests have been moved to `valence/src/tests` in
order to avoid [cyclic
dev-dependencies](https://github.com/rust-lang/cargo/issues/4242).
- Tools like `valence_stresser` and `packet_inspector` have been moved
to a new `tools` directory. Renamed `valence_stresser` to `stresser`.
Closes #241.
- Moved all benches to `valence/benches/` to make them easier to run and
organize.

Ignoring transitive dependencies and `valence_core`, here's what the
dependency graph looks like now:

```mermaid
graph TD
	network --> client
	client --> instance
	biome --> registry
	dimension --> registry
	instance --> biome
	instance --> dimension
	instance --> entity
	player_list --> client
	inventory --> client
	anvil --> instance
	entity --> block
```

### Issues
- Inventory tests inspect many private implementation details of the
inventory module, forcing us to mark things as `pub` and
`#[doc(hidden)]`. It would be ideal if the tests only looked at
observable behavior.
- Consider moving packets in `valence_core` elsewhere. `Particle` wants
to use `BlockState`, but that's defined in `valence_block`, so we can't
use it without causing cycles.
- Unsure what exactly should go in `valence::prelude`.
- This could use some more tests of course, but I'm holding off on that
until I'm confident this is the direction we want to take things.

## TODOs
- [x] Update examples.
- [x] Update benches.
- [x] Update main README.
- [x] Add short READMEs to crates.
- [x] Test new schedule to ensure behavior is the same. 
- [x] Update tools.
- [x] Copy lints to all crates.
- [x] Fix docs, clippy, etc.
2023-04-21 14:43:59 -07:00

132 lines
3.5 KiB
Rust

use std::collections::BTreeMap;
use std::net::SocketAddr;
use std::path::PathBuf;
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use crate::MetaPacket;
#[derive(Serialize, Deserialize)]
pub struct ApplicationConfig {
server_addr: SocketAddr,
client_addr: SocketAddr,
max_connections: Option<usize>,
filter: Option<String>,
selected_packets: Option<BTreeMap<MetaPacket, bool>>,
#[serde(skip_serializing, skip_deserializing)]
must_save: bool,
}
impl Default for ApplicationConfig {
fn default() -> Self {
Self {
server_addr: "127.0.0.1:25565".parse().unwrap(),
client_addr: "127.0.0.1:25566".parse().unwrap(),
max_connections: None,
filter: None,
selected_packets: None,
must_save: false,
}
}
}
impl ApplicationConfig {
pub fn load() -> Result<ApplicationConfig, Box<dyn std::error::Error>> {
let config_dir = get_or_create_project_dirs()?;
let config_file = config_dir.join("config.toml");
if config_file.exists() {
let config = std::fs::read_to_string(config_file)?;
toml::from_str(&config).map_err(|e| e.into())
} else {
let config = toml::to_string(&ApplicationConfig::default()).unwrap();
std::fs::write(config_file, config)?;
Ok(ApplicationConfig::default())
}
}
pub fn server_addr(&self) -> SocketAddr {
self.server_addr
}
pub fn client_addr(&self) -> SocketAddr {
self.client_addr
}
pub fn max_connections(&self) -> Option<usize> {
self.max_connections
}
pub fn filter(&self) -> &Option<String> {
&self.filter
}
pub fn selected_packets(&self) -> &Option<BTreeMap<MetaPacket, bool>> {
&self.selected_packets
}
pub fn set_server_addr(&mut self, addr: SocketAddr) {
self.must_save = true;
self.server_addr = addr;
}
pub fn set_client_addr(&mut self, addr: SocketAddr) {
self.must_save = true;
self.client_addr = addr;
}
pub fn set_max_connections(&mut self, max: Option<usize>) {
self.must_save = true;
self.max_connections = max;
}
pub fn set_filter(&mut self, filter: Option<String>) {
self.must_save = true;
self.filter = filter;
}
pub fn set_selected_packets(&mut self, packets: BTreeMap<MetaPacket, bool>) {
self.must_save = true;
self.selected_packets = Some(packets);
}
pub fn save(&mut self) -> Result<(), Box<dyn std::error::Error>> {
if !self.must_save {
return Ok(());
}
self.must_save = false;
let config_dir = match get_or_create_project_dirs() {
Ok(dir) => dir,
Err(e) => {
eprintln!("Could not find config directory: {}", e);
return Ok(());
}
};
let config_file = config_dir.join("config.toml");
let config = toml::to_string(&self).unwrap();
std::fs::write(config_file, config).unwrap();
Ok(())
}
}
fn get_or_create_project_dirs() -> Result<PathBuf, Box<dyn std::error::Error>> {
if let Some(proj_dirs) = ProjectDirs::from("com", "valence", "inspector") {
// check if the directory exists, if not create it
if !proj_dirs.config_dir().exists() {
std::fs::create_dir_all(proj_dirs.config_dir())?;
}
Ok(proj_dirs.config_dir().to_owned())
} else {
Err("Could not find project directories".into())
}
}