use crate::managed_file::{self, Snapshot};
use anyhow::{Result, ensure};
use serde::Deserialize;
use std::{collections::BTreeMap, path::Path};
type Sizes = BTreeMap<String, [i32; 2]>;
const FILE: &str = "desktop-tray-sizes.json";
#[derive(Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub(super) enum Request {
SaveTraySize {
display: String,
width: i32,
height: i32,
},
}
fn read(home: &Path) -> Result<(Snapshot, Sizes)> {
let snapshot = Snapshot::read(&home.join(FILE))?;
snapshot.private()?;
let sizes = snapshot
.text
.as_deref()
.and_then(|text| serde_json::from_str::<Sizes>(text).ok())
.unwrap_or_default();
Ok((snapshot, sizes))
}
pub(super) fn initial(home: &Path) -> Result<Option<Vec<u8>>> {
let (_, sizes) = read(home)?;
if sizes.is_empty() {
return Ok(None);
}
let mut bytes = serde_json::to_vec(&serde_json::json!({ "tray_sizes": sizes }))?;
bytes.push(b'\n');
Ok(Some(bytes))
}
impl Request {
pub(super) fn save(self, home: &Path) -> Result<()> {
let Self::SaveTraySize {
display,
width,
height,
} = self;
ensure!(
!display.is_empty()
&& display.len() <= 512
&& !display.chars().any(char::is_control)
&& width > 0
&& height > 0,
"invalid dashboard window size"
);
let _lock = managed_file::lock(&home.join("desktop-tray-sizes.lock"))?;
let (snapshot, mut sizes) = read(home)?;
sizes.insert(display, [width, height]);
snapshot.write(&serde_json::to_string(&sizes)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn restore_profile_sizes_and_preserve_other_displays() -> Result<()> {
let profile = tempfile::tempdir()?;
let home = profile.path();
let save = |display: &str, width, height| {
Request::SaveTraySize {
display: display.to_owned(),
width,
height,
}
.save(home)
};
assert!(initial(home)?.is_none());
save("display-a", 700, 430)?;
save("display-b", 520, 640)?;
save("display-a", 830, 500)?;
assert!(save("display-b", -1, 100).is_err());
let startup = initial(home)?.unwrap();
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&startup)?,
serde_json::json!({"tray_sizes":{"display-a":[830,500], "display-b":[520,640]}})
);
assert!(initial(tempfile::tempdir()?.path())?.is_none());
Ok(())
}
}