use std::collections::BTreeMap;
#[cfg(feature = "threads")]
use std::path::Path;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::theme::ThemeId;
use super::layout::Layout;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct WorkspaceDocument {
pub id: String,
pub title: String,
pub dirty: bool,
pub path: Option<PathBuf>,
#[serde(default)]
pub payload: serde_json::Value,
}
impl WorkspaceDocument {
pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
Self {
id: id.into(),
title: title.into(),
dirty: false,
path: None,
payload: serde_json::Value::Null,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct WorkspacePanels {
pub sidebar: bool,
pub inspector: bool,
pub output: bool,
pub status_bar: bool,
}
impl Default for WorkspacePanels {
fn default() -> Self {
Self {
sidebar: true,
inspector: false,
output: false,
status_bar: true,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct WorkspacePlotView {
pub x: [f64; 2],
pub y: [f64; 2],
#[serde(default)]
pub hidden: Vec<String>,
}
impl WorkspacePlotView {
pub fn new(x: [f64; 2], y: [f64; 2]) -> Self {
Self {
x,
y,
hidden: Vec::new(),
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct Workspace {
pub version: u32,
pub theme: ThemeId,
pub follow_system: bool,
pub reduced_motion: bool,
pub documents: Vec<WorkspaceDocument>,
pub active: usize,
pub explorer: Vec<String>,
pub panels: WorkspacePanels,
pub sidebar_width: f32,
pub right_width: f32,
pub bottom_height: f32,
pub plot_views: BTreeMap<String, WorkspacePlotView>,
pub layout: Layout,
pub named_layouts: BTreeMap<String, Layout>,
pub active_layout: String,
}
impl Default for Workspace {
fn default() -> Self {
Self {
version: Self::VERSION,
theme: ThemeId::GithubLight,
follow_system: false,
reduced_motion: false,
documents: Vec::new(),
active: 0,
explorer: Vec::new(),
panels: WorkspacePanels::default(),
sidebar_width: 240.0,
right_width: 280.0,
bottom_height: 180.0,
plot_views: BTreeMap::new(),
layout: Layout::default(),
named_layouts: BTreeMap::new(),
active_layout: "Default".to_owned(),
}
}
}
impl Workspace {
pub const VERSION: u32 = 1;
pub fn new() -> Self {
Self::default()
}
pub fn with_documents(documents: Vec<WorkspaceDocument>) -> Self {
Self {
documents,
..Self::default()
}
}
pub fn add_document(&mut self, document: WorkspaceDocument) -> usize {
self.documents.push(document);
self.documents.len() - 1
}
pub fn active_document(&self) -> Option<&WorkspaceDocument> {
self.documents.get(self.active)
}
pub fn set_active(&mut self, index: usize) -> bool {
if index < self.documents.len() {
self.active = index;
true
} else {
false
}
}
pub fn normalize(&mut self) {
if self.documents.is_empty() {
self.active = 0;
} else {
self.active = self.active.min(self.documents.len() - 1);
}
self.sidebar_width = self.sidebar_width.clamp(120.0, 800.0);
self.right_width = self.right_width.clamp(120.0, 800.0);
self.bottom_height = self.bottom_height.clamp(80.0, 600.0);
self.layout.normalize();
if self.active_layout.is_empty() {
self.active_layout = "Default".to_owned();
}
}
pub fn save_layout(&mut self, name: impl Into<String>) -> String {
let name = name.into();
self.named_layouts.insert(name.clone(), self.layout.clone());
self.active_layout = name.clone();
name
}
pub fn switch_layout(&mut self, name: &str) -> bool {
let Some(layout) = self.named_layouts.get(name).cloned() else {
return false;
};
self.layout = layout;
self.active_layout = name.to_owned();
true
}
pub fn to_json(&self) -> Result<String, SessionError> {
serde_json::to_string_pretty(self).map_err(|error| SessionError::Json(error.to_string()))
}
pub fn from_json(json: &str) -> Result<Self, SessionError> {
let mut value: serde_json::Value =
serde_json::from_str(json).map_err(|error| SessionError::Json(error.to_string()))?;
let raw = value.get("version").and_then(serde_json::Value::as_u64).unwrap_or(0);
let version = u32::try_from(raw).unwrap_or(u32::MAX);
if version > Self::VERSION {
return Err(SessionError::UnsupportedVersion(version));
}
if version < 1 {
if let Some(object) = value.as_object_mut() {
object.insert("version".to_owned(), serde_json::Value::from(Self::VERSION));
}
}
let mut workspace: Self =
serde_json::from_value(value).map_err(|error| SessionError::Json(error.to_string()))?;
workspace.normalize();
Ok(workspace)
}
#[cfg(feature = "threads")]
pub fn save(&self, path: impl AsRef<Path>) -> Result<(), SessionError> {
let json = self.to_json()?;
crate::storage::atomic_write(path.as_ref(), json.as_bytes())
.map_err(|error| SessionError::Io(error.to_string()))
}
#[cfg(feature = "threads")]
pub fn load(path: impl AsRef<Path>) -> Result<Self, SessionError> {
let text = std::fs::read_to_string(path).map_err(|error| SessionError::Io(error.to_string()))?;
Self::from_json(&text)
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum SessionError {
#[error("invalid workspace JSON: {0}")]
Json(String),
#[error("unsupported workspace version {0}")]
UnsupportedVersion(u32),
#[error("{0}")]
Io(String),
}
#[cfg(all(test, feature = "threads"))]
mod tests {
use super::*;
fn test_directory(prefix: &str) -> std::path::PathBuf {
let thread: String = std::thread::current()
.name()
.unwrap_or("test")
.chars()
.map(|character| {
if character.is_ascii_alphanumeric() {
character
} else {
'_'
}
})
.collect();
std::path::PathBuf::from("/tmp").join(format!("{prefix}-{thread}"))
}
#[test]
fn documents_and_panels_round_trip() {
let mut workspace = Workspace::new();
workspace.add_document(WorkspaceDocument::new("one", "One"));
workspace.add_document(WorkspaceDocument::new("two", "Two"));
workspace.set_active(1);
workspace.theme = ThemeId::Dracula;
workspace.explorer = vec!["src".to_owned()];
workspace.panels.inspector = true;
workspace
.plot_views
.insert("main".to_owned(), WorkspacePlotView::new([0.0, 1.0], [2.0, 3.0]));
workspace.layout.split(
crate::state::layout::EditorGroupId(0),
crate::state::layout::SplitDirection::Horizontal,
);
workspace.save_layout("Review");
let json = workspace.to_json().expect("serialize");
let back = Workspace::from_json(&json).expect("parse");
assert_eq!(back, workspace);
assert_eq!(back.active_document().map(|doc| doc.title.as_str()), Some("Two"));
assert_eq!(back.active_layout, "Review");
assert!(back.named_layouts.contains_key("Review"));
}
#[test]
fn missing_fields_and_version_zero_migrate() {
let json = r#"{"documents":[{"id":"a","title":"A","dirty":true,"path":null}]}"#;
let workspace = Workspace::from_json(json).expect("migrate");
assert_eq!(workspace.version, Workspace::VERSION);
assert_eq!(workspace.documents.len(), 1);
assert!(workspace.panels.sidebar);
assert_eq!(workspace.active, 0);
}
#[test]
fn a_newer_version_is_rejected() {
let error = Workspace::from_json(r#"{"version": 9}"#).expect_err("newer");
assert!(matches!(error, SessionError::UnsupportedVersion(9)));
}
#[test]
fn normalize_clamps_active_and_sizes() {
let mut workspace = Workspace::new();
workspace.add_document(WorkspaceDocument::new("a", "A"));
workspace.active = 99;
workspace.sidebar_width = 1.0;
workspace.right_width = 9999.0;
workspace.bottom_height = 1.0;
workspace.normalize();
assert_eq!(workspace.active, 0);
assert_eq!(workspace.sidebar_width, 120.0);
assert_eq!(workspace.right_width, 800.0);
assert_eq!(workspace.bottom_height, 80.0);
}
#[test]
fn save_and_load_are_atomic() {
let directory = test_directory("crisol-workspace");
let _ = std::fs::remove_dir_all(&directory);
std::fs::create_dir_all(&directory).expect("create");
let path = directory.join("workspace.json");
let mut workspace = Workspace::new();
workspace.add_document(WorkspaceDocument::new("a", "A"));
workspace.save(&path).expect("save");
let back = Workspace::load(&path).expect("load");
assert_eq!(back, workspace);
let leftovers = std::fs::read_dir(&directory).expect("dir").count();
assert_eq!(leftovers, 1, "no temporary file stays behind");
let _ = std::fs::remove_dir_all(directory);
}
}