use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
const MIN_WIDTH: i32 = 360;
const MIN_HEIGHT: i32 = 150;
const MAX_WIDTH: i32 = 8192;
const MAX_HEIGHT: i32 = 8192;
const PREVIEW_SPLIT_DEFAULT_FRACTION: i32 = 3;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct WindowState {
pub width: i32,
pub height: i32,
pub maximized: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub preview_split: Option<i32>,
}
impl Default for WindowState {
fn default() -> Self {
Self {
width: 720,
height: 540,
maximized: false,
preview_split: None,
}
}
}
impl WindowState {
pub fn resolved_preview_split(&self) -> i32 {
match self.preview_split {
Some(p) if p > 0 => p.clamp(MIN_HEIGHT / PREVIEW_SPLIT_DEFAULT_FRACTION, self.height),
_ => (self.height / PREVIEW_SPLIT_DEFAULT_FRACTION)
.max(MIN_HEIGHT / PREVIEW_SPLIT_DEFAULT_FRACTION),
}
}
}
fn sanitize(mut state: WindowState) -> WindowState {
state.width = state.width.clamp(MIN_WIDTH, MAX_WIDTH);
state.height = state.height.clamp(MIN_HEIGHT, MAX_HEIGHT);
if state.preview_split.is_some_and(|p| p <= 0) {
state.preview_split = None;
}
state
}
fn config_path() -> Option<PathBuf> {
let base = fluxframe_core::paths::config_home()?;
Some(config_path_in(&base))
}
fn config_path_in(base: &Path) -> PathBuf {
base.join("fluxframe").join("gui.json")
}
pub(crate) fn load() -> WindowState {
let Some(path) = config_path() else {
tracing::debug!("no XDG_CONFIG_HOME or HOME — skipping load");
return WindowState::default();
};
load_from(&path)
}
fn load_from(path: &Path) -> WindowState {
match std::fs::read_to_string(path) {
Ok(s) => match serde_json::from_str::<WindowState>(&s) {
Ok(state) => {
tracing::debug!(?path, ?state, "loaded window state");
sanitize(state)
}
Err(e) => {
tracing::debug!(error = %e, ?path, "window state parse failed, using default");
WindowState::default()
}
},
Err(e) if e.kind() == std::io::ErrorKind::NotFound => WindowState::default(),
Err(e) => {
tracing::debug!(error = %e, ?path, "window state read failed, using default");
WindowState::default()
}
}
}
pub(crate) fn save(state: &WindowState) {
let Some(path) = config_path() else {
return;
};
save_to(&path, state);
}
fn save_to(path: &Path, state: &WindowState) {
if let Some(parent) = path.parent()
&& let Err(e) = std::fs::create_dir_all(parent)
{
tracing::warn!(error = %e, ?parent, "failed to create config dir");
return;
}
let payload = match serde_json::to_string_pretty(state) {
Ok(s) => s,
Err(e) => {
tracing::warn!(error = %e, "window state serialise failed");
return;
}
};
let tmp_path = path.with_extension("json.tmp");
if let Err(e) = std::fs::write(&tmp_path, payload) {
tracing::warn!(error = %e, ?tmp_path, "window state write failed");
return;
}
if let Err(e) = std::fs::rename(&tmp_path, path) {
tracing::warn!(error = %e, ?path, "window state rename failed");
let _ = std::fs::remove_file(&tmp_path);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn load_missing_returns_default() {
let tmp = tempfile::tempdir().expect("create tempdir");
let path = config_path_in(tmp.path());
let state = load_from(&path);
let def = WindowState::default();
assert_eq!(state.width, def.width);
assert_eq!(state.height, def.height);
assert_eq!(state.maximized, def.maximized);
}
#[test]
fn save_then_load_roundtrip() {
let tmp = tempfile::tempdir().expect("create tempdir");
let path = config_path_in(tmp.path());
let original = WindowState {
width: 1024,
height: 768,
maximized: true,
preview_split: Some(256),
};
save_to(&path, &original);
let loaded = load_from(&path);
assert_eq!(loaded.width, original.width);
assert_eq!(loaded.height, original.height);
assert_eq!(loaded.maximized, original.maximized);
assert_eq!(loaded.preview_split, original.preview_split);
}
#[test]
fn missing_preview_split_loads_as_unset() {
let tmp = tempfile::tempdir().expect("create tempdir");
let path = config_path_in(tmp.path());
let dir = path.parent().expect("path has parent");
std::fs::create_dir_all(dir).expect("create fluxframe dir");
std::fs::write(
&path,
r#"{"width": 800, "height": 600, "maximized": false}"#,
)
.expect("write json");
let state = load_from(&path);
assert_eq!(state.preview_split, None);
assert_eq!(state.resolved_preview_split(), 200);
}
#[test]
fn negative_preview_split_is_sanitized_to_unset() {
let tmp = tempfile::tempdir().expect("create tempdir");
let path = config_path_in(tmp.path());
let dir = path.parent().expect("path has parent");
std::fs::create_dir_all(dir).expect("create fluxframe dir");
std::fs::write(
&path,
r#"{"width": 800, "height": 600, "maximized": false, "preview_split": -42}"#,
)
.expect("write json");
let state = load_from(&path);
assert_eq!(state.preview_split, None);
}
#[test]
fn resolved_preview_split_clamps_above_height() {
let state = WindowState {
width: 800,
height: 600,
maximized: false,
preview_split: Some(9999),
};
assert_eq!(state.resolved_preview_split(), 600);
}
#[test]
fn resolved_preview_split_clamps_below_min() {
let state = WindowState {
width: 800,
height: 600,
maximized: false,
preview_split: Some(10),
};
assert_eq!(
state.resolved_preview_split(),
MIN_HEIGHT / PREVIEW_SPLIT_DEFAULT_FRACTION,
);
}
#[test]
fn resolved_preview_split_passes_through_valid_range() {
let state = WindowState {
width: 800,
height: 600,
maximized: false,
preview_split: Some(250),
};
assert_eq!(state.resolved_preview_split(), 250);
}
#[test]
fn load_corrupt_json_returns_default() {
let tmp = tempfile::tempdir().expect("create tempdir");
let path = config_path_in(tmp.path());
let dir = path.parent().expect("path has parent");
std::fs::create_dir_all(dir).expect("create fluxframe dir");
std::fs::write(&path, "not valid json").expect("write corrupt json");
let state = load_from(&path);
let def = WindowState::default();
assert_eq!(state.width, def.width);
assert_eq!(state.height, def.height);
assert_eq!(state.maximized, def.maximized);
}
#[test]
fn load_clamps_negative_dimensions() {
let tmp = tempfile::tempdir().expect("create tempdir");
let path = config_path_in(tmp.path());
let dir = path.parent().expect("path has parent");
std::fs::create_dir_all(dir).expect("create fluxframe dir");
std::fs::write(&path, r#"{"width": -5, "height": 0, "maximized": false}"#)
.expect("write json");
let state = load_from(&path);
assert_eq!(state.width, MIN_WIDTH);
assert_eq!(state.height, MIN_HEIGHT);
assert!(!state.maximized);
}
#[test]
fn load_clamps_huge_dimensions() {
let tmp = tempfile::tempdir().expect("create tempdir");
let path = config_path_in(tmp.path());
let dir = path.parent().expect("path has parent");
std::fs::create_dir_all(dir).expect("create fluxframe dir");
std::fs::write(
&path,
r#"{"width": 999999, "height": 888888, "maximized": true}"#,
)
.expect("write json");
let state = load_from(&path);
assert_eq!(state.width, MAX_WIDTH);
assert_eq!(state.height, MAX_HEIGHT);
assert!(state.maximized);
}
#[test]
fn save_atomic_write_does_not_leave_tmp_on_success() {
let tmp = tempfile::tempdir().expect("create tempdir");
let path = config_path_in(tmp.path());
let state = WindowState {
width: 800,
height: 600,
maximized: false,
preview_split: None,
};
save_to(&path, &state);
let dir = path.parent().expect("path has parent");
let entries: Vec<_> = std::fs::read_dir(dir)
.expect("read fluxframe dir")
.filter_map(Result::ok)
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
assert!(
entries.iter().any(|n| n == "gui.json"),
"gui.json should exist after save, got: {entries:?}",
);
assert!(
!entries.iter().any(|n| std::path::Path::new(n)
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("tmp"))),
"no .tmp file should remain after successful save, got: {entries:?}",
);
}
}