use std::path::PathBuf;
use gpui_kit::{App, AppContext as _, Global};
use subspace_core::state::{self, State};
pub const MAX_STORED: usize = 400;
#[derive(Clone, Default)]
pub struct Prefs {
state: State,
file: Option<PathBuf>,
dirty: bool,
}
impl Global for Prefs {}
pub fn init(cx: &mut App) {
init_file(state::path(), cx);
}
pub fn init_file(file: Option<PathBuf>, cx: &mut App) {
let state = file.as_deref().map(State::load).unwrap_or_default();
cx.set_global(Prefs {
state,
file,
dirty: false,
});
crate::icon_button::initialize(cx);
crate::avatar::initialize_icons(cx);
}
pub fn get(cx: &App, key: &str) -> Option<String> {
cx.try_global::<Prefs>()?.state.get(key).map(str::to_string)
}
pub fn has_invalid_value(cx: &App, key: &str) -> bool {
cx.try_global::<Prefs>()
.is_some_and(|prefs| prefs.state.has_invalid_value(key))
}
pub fn set(cx: &mut App, key: &str, value: impl Into<String>) {
let value = value.into();
if !cx.has_global::<Prefs>() || get(cx, key).as_deref() == Some(value.as_str()) {
return;
}
let prefs = cx.global_mut::<Prefs>();
prefs.state.set(key, value);
prefs.dirty = true;
}
pub fn remove(cx: &mut App, key: &str) {
if get(cx, key).is_none() && !has_invalid_value(cx, key) {
return;
}
let prefs = cx.global_mut::<Prefs>();
prefs.state.remove(key);
prefs.dirty = true;
}
pub fn state_dir(cx: &App) -> Option<PathBuf> {
let file = cx.try_global::<Prefs>()?.file.as_deref()?;
file.parent().map(std::path::Path::to_path_buf)
}
pub fn read_cache(name: &str) -> Option<String> {
std::fs::read_to_string(state::sibling(name)?).ok()
}
pub fn write_cache(name: &str, text: String, cx: &App) {
let Some(file) = state::sibling(name) else {
return;
};
cx.background_spawn(async move {
if let Err(error) = state::write_atomic(&file, &text) {
eprintln!("subspace: could not save {}: {error}", file.display());
}
})
.detach();
}
pub fn get_list(cx: &App, key: &str) -> Vec<String> {
get(cx, key)
.and_then(|text| serde_json::from_str(&text).ok())
.unwrap_or_default()
}
pub fn set_list(cx: &mut App, key: &str, values: &[String]) {
let start = values.len().saturating_sub(MAX_STORED);
let text = serde_json::to_string(&values[start..]).unwrap_or_default();
set(cx, key, text);
}
pub fn save(cx: &mut App) -> std::io::Result<()> {
let Some(prefs) = cx.try_global::<Prefs>() else {
return Ok(());
};
let (Some(file), true) = (prefs.file.clone(), prefs.dirty) else {
return Ok(());
};
prefs.state.save(&file)?;
cx.global_mut::<Prefs>().dirty = false;
Ok(())
}
#[cfg(test)]
mod tests {
use std::fs;
use gpui_kit::TestAppContext;
use super::{get, has_invalid_value, init_file, remove, save, set};
#[gpui_kit::test]
fn invalid_entry_survives_other_saves_until_explicitly_removed(cx: &mut TestAppContext) {
let directory = tempfile::tempdir().unwrap();
let file = directory.path().join("state.json");
fs::write(&file, r#"{"layout":{"bad":true},"other":"old"}"#).unwrap();
cx.update(|cx| {
init_file(Some(file.clone()), cx);
assert!(has_invalid_value(cx, "layout"));
assert_eq!(get(cx, "other").as_deref(), Some("old"));
set(cx, "other", "new");
save(cx).unwrap();
});
let saved: serde_json::Value = serde_json::from_slice(&fs::read(&file).unwrap()).unwrap();
assert_eq!(saved["layout"]["bad"], true);
assert_eq!(saved["other"], "new");
cx.update(|cx| {
remove(cx, "layout");
assert!(!has_invalid_value(cx, "layout"));
save(cx).unwrap();
});
let saved: serde_json::Value = serde_json::from_slice(&fs::read(&file).unwrap()).unwrap();
assert!(saved.get("layout").is_none());
assert_eq!(saved["other"], "new");
}
}