use super::*;
use std::path::Path;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ActionBinding {
pub action: u16,
pub buttons: Vec<Button>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AxisConfig {
pub axis: u16,
pub sources: Vec<AxisBinding>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BindingConfig {
pub schema_version: u32,
pub actions: Vec<ActionBinding>,
pub axes: Vec<AxisConfig>,
}
impl Default for BindingConfig {
fn default() -> Self {
Self {
schema_version: 1,
actions: Vec::new(),
axes: Vec::new(),
}
}
}
impl BindingConfig {
pub fn validate(&self) -> Result<(), Error> {
if self.schema_version != 1 {
return Err(invalid("unsupported binding schema_version; expected 1"));
}
let mut actions = std::collections::HashSet::new();
for entry in &self.actions {
if !actions.insert(entry.action) {
return Err(invalid(format!("duplicate action ID {}", entry.action)));
}
for (i, button) in entry.buttons.iter().enumerate() {
button
.validate()
.map_err(|e| invalid(format!("action {} button {i}: {e}", entry.action)))?;
}
}
let mut axes = std::collections::HashSet::new();
for entry in &self.axes {
if !axes.insert(entry.axis) {
return Err(invalid(format!("duplicate axis ID {}", entry.axis)));
}
for (i, source) in entry.sources.iter().enumerate() {
source
.validate()
.map_err(|e| invalid(format!("axis {} source {i}: {e}", entry.axis)))?;
}
}
Ok(())
}
}
impl Bindings {
pub fn config(&self) -> BindingConfig {
BindingConfig {
schema_version: 1,
actions: self
.actions
.iter()
.map(|(a, buttons)| ActionBinding {
action: a.0,
buttons: buttons.clone(),
})
.collect(),
axes: self
.axes
.iter()
.map(|(a, sources)| AxisConfig {
axis: a.0,
sources: sources.clone(),
})
.collect(),
}
}
pub fn from_config(config: BindingConfig) -> Result<Self, Error> {
config.validate()?;
Ok(Self {
actions: config
.actions
.into_iter()
.filter(|a| !a.buttons.is_empty())
.map(|a| (Action(a.action), a.buttons))
.collect(),
axes: config
.axes
.into_iter()
.filter(|a| !a.sources.is_empty())
.map(|a| (Axis(a.axis), a.sources))
.collect(),
})
}
pub fn replace(&mut self, config: BindingConfig) -> Result<(), Error> {
*self = Self::from_config(config)?;
Ok(())
}
pub fn from_json(json: &str) -> Result<Self, Error> {
let config = serde_json::from_str(json)
.map_err(|e| invalid(format!("invalid binding JSON: {e}")))?;
Self::from_config(config)
}
pub fn to_json(&self) -> Result<String, Error> {
self.validate()?;
serde_json::to_string_pretty(&self.config())
.map_err(|e| invalid(format!("binding serialization failed: {e}")))
}
pub fn load(path: impl AsRef<Path>) -> Result<Self, Error> {
Self::from_json(&std::fs::read_to_string(path)?)
}
pub fn save(&self, path: impl AsRef<Path>) -> Result<(), Error> {
let json = self.to_json()?;
std::fs::write(path, json)?;
Ok(())
}
}