Skip to main content

crisol_core/state/
session.rs

1//! Versioned workspace persistence: documents, active tab, explorer, panels, theme,
2//! and plot views in one atomically written file.
3//!
4//! ```
5//! use crisol_core::state::session;
6//! ```
7
8use std::collections::BTreeMap;
9#[cfg(feature = "threads")]
10use std::path::Path;
11use std::path::PathBuf;
12
13use serde::{Deserialize, Serialize};
14
15use crate::theme::ThemeId;
16
17use super::layout::Layout;
18
19/// One open document in the workspace.
20#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
21#[non_exhaustive]
22/// # Example
23///
24/// ```
25/// use crisol_core::state::WorkspaceDocument;
26/// ```
27pub struct WorkspaceDocument {
28    /// Stable application id.
29    pub id: String,
30    /// Tab title.
31    pub title: String,
32    /// Unsaved changes.
33    pub dirty: bool,
34    /// Path on disk, when the document has one.
35    pub path: Option<PathBuf>,
36    /// Application-specific payload (cursor, scroll offset, model data).
37    #[serde(default)]
38    pub payload: serde_json::Value,
39}
40
41impl WorkspaceDocument {
42    /// A document with no path and no payload.
43    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
44        Self {
45            id: id.into(),
46            title: title.into(),
47            dirty: false,
48            path: None,
49            payload: serde_json::Value::Null,
50        }
51    }
52}
53
54/// Which panels are visible.
55#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
56#[non_exhaustive]
57/// # Example
58///
59/// ```
60/// use crisol_core::state::WorkspacePanels;
61/// ```
62pub struct WorkspacePanels {
63    /// Explorer.
64    pub sidebar: bool,
65    /// Right inspector.
66    pub inspector: bool,
67    /// Bottom output.
68    pub output: bool,
69    /// Status bar.
70    pub status_bar: bool,
71}
72
73impl Default for WorkspacePanels {
74    fn default() -> Self {
75        Self {
76            sidebar: true,
77            inspector: false,
78            output: false,
79            status_bar: true,
80        }
81    }
82}
83
84/// A serializable plot view: the visible x and y ranges plus hidden series.
85#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
86#[non_exhaustive]
87/// # Example
88///
89/// ```
90/// use crisol_core::state::WorkspacePlotView;
91/// ```
92pub struct WorkspacePlotView {
93    /// Visible x range.
94    pub x: [f64; 2],
95    /// Visible y range.
96    pub y: [f64; 2],
97    /// Hidden series names.
98    #[serde(default)]
99    pub hidden: Vec<String>,
100}
101
102impl WorkspacePlotView {
103    /// A view from two ranges.
104    pub fn new(x: [f64; 2], y: [f64; 2]) -> Self {
105        Self {
106            x,
107            y,
108            hidden: Vec::new(),
109        }
110    }
111}
112
113/// The persisted workspace.
114#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
115#[serde(default)]
116#[non_exhaustive]
117/// # Example
118///
119/// ```
120/// use crisol_core::state::Workspace;
121/// ```
122pub struct Workspace {
123    /// File format version.
124    pub version: u32,
125    /// Requested theme.
126    pub theme: ThemeId,
127    /// Follow the desktop light/dark preference.
128    pub follow_system: bool,
129    /// Reduced motion.
130    pub reduced_motion: bool,
131    /// Open documents, in tab order.
132    pub documents: Vec<WorkspaceDocument>,
133    /// Active document index (clamped on load).
134    pub active: usize,
135    /// Expanded explorer keys.
136    pub explorer: Vec<String>,
137    /// Visible panels.
138    pub panels: WorkspacePanels,
139    /// Left panel width.
140    pub sidebar_width: f32,
141    /// Right panel width.
142    pub right_width: f32,
143    /// Bottom panel height.
144    pub bottom_height: f32,
145    /// Plot views by plot id.
146    pub plot_views: BTreeMap<String, WorkspacePlotView>,
147    /// The current editor layout.
148    pub layout: Layout,
149    /// Named layouts ("Analysis", "Review") that can be switched from the palette.
150    pub named_layouts: BTreeMap<String, Layout>,
151    /// The name of the active named layout.
152    pub active_layout: String,
153}
154
155impl Default for Workspace {
156    fn default() -> Self {
157        Self {
158            version: Self::VERSION,
159            theme: ThemeId::GithubLight,
160            follow_system: false,
161            reduced_motion: false,
162            documents: Vec::new(),
163            active: 0,
164            explorer: Vec::new(),
165            panels: WorkspacePanels::default(),
166            sidebar_width: 240.0,
167            right_width: 280.0,
168            bottom_height: 180.0,
169            plot_views: BTreeMap::new(),
170            layout: Layout::default(),
171            named_layouts: BTreeMap::new(),
172            active_layout: "Default".to_owned(),
173        }
174    }
175}
176
177impl Workspace {
178    /// The current file version.
179    pub const VERSION: u32 = 1;
180
181    /// A workspace with the current version and default panel sizes.
182    pub fn new() -> Self {
183        Self::default()
184    }
185
186    /// A workspace with documents.
187    pub fn with_documents(documents: Vec<WorkspaceDocument>) -> Self {
188        Self {
189            documents,
190            ..Self::default()
191        }
192    }
193
194    /// Add a document and return its index.
195    pub fn add_document(&mut self, document: WorkspaceDocument) -> usize {
196        self.documents.push(document);
197        self.documents.len() - 1
198    }
199
200    /// The active document.
201    pub fn active_document(&self) -> Option<&WorkspaceDocument> {
202        self.documents.get(self.active)
203    }
204
205    /// Select an existing document.
206    pub fn set_active(&mut self, index: usize) -> bool {
207        if index < self.documents.len() {
208            self.active = index;
209            true
210        } else {
211            false
212        }
213    }
214
215    /// Clamp the active index and the panel sizes after a load.
216    pub fn normalize(&mut self) {
217        if self.documents.is_empty() {
218            self.active = 0;
219        } else {
220            self.active = self.active.min(self.documents.len() - 1);
221        }
222        self.sidebar_width = self.sidebar_width.clamp(120.0, 800.0);
223        self.right_width = self.right_width.clamp(120.0, 800.0);
224        self.bottom_height = self.bottom_height.clamp(80.0, 600.0);
225        self.layout.normalize();
226        if self.active_layout.is_empty() {
227            self.active_layout = "Default".to_owned();
228        }
229    }
230
231    /// Save the current layout under a name and return the name.
232    pub fn save_layout(&mut self, name: impl Into<String>) -> String {
233        let name = name.into();
234        self.named_layouts.insert(name.clone(), self.layout.clone());
235        self.active_layout = name.clone();
236        name
237    }
238
239    /// Switch to a named layout. Returns whether it existed.
240    pub fn switch_layout(&mut self, name: &str) -> bool {
241        let Some(layout) = self.named_layouts.get(name).cloned() else {
242            return false;
243        };
244        self.layout = layout;
245        self.active_layout = name.to_owned();
246        true
247    }
248
249    /// Serialize as pretty JSON.
250    ///
251    /// # Errors
252    /// When serialization fails (it does not for this type).
253    pub fn to_json(&self) -> Result<String, SessionError> {
254        serde_json::to_string_pretty(self).map_err(|error| SessionError::Json(error.to_string()))
255    }
256
257    /// Parse a workspace, migrating an older version and rejecting a newer one.
258    ///
259    /// # Errors
260    /// When the JSON is malformed or the version is newer than [`Self::VERSION`].
261    pub fn from_json(json: &str) -> Result<Self, SessionError> {
262        let mut value: serde_json::Value =
263            serde_json::from_str(json).map_err(|error| SessionError::Json(error.to_string()))?;
264        // `as u32` wrapped 2^32 + 1 to 1 and let a far newer file through.
265        let raw = value.get("version").and_then(serde_json::Value::as_u64).unwrap_or(0);
266        let version = u32::try_from(raw).unwrap_or(u32::MAX);
267        if version > Self::VERSION {
268            return Err(SessionError::UnsupportedVersion(version));
269        }
270        if version < 1 {
271            // Version 0 had no `version` field and no plot views. `serde(default)` fills
272            // every field added since; write the current version before deserializing.
273            if let Some(object) = value.as_object_mut() {
274                object.insert("version".to_owned(), serde_json::Value::from(Self::VERSION));
275            }
276        }
277        let mut workspace: Self =
278            serde_json::from_value(value).map_err(|error| SessionError::Json(error.to_string()))?;
279        workspace.normalize();
280        Ok(workspace)
281    }
282
283    /// Write the workspace atomically.
284    ///
285    /// # Errors
286    /// When serialization or the write fails.
287    #[cfg(feature = "threads")]
288    pub fn save(&self, path: impl AsRef<Path>) -> Result<(), SessionError> {
289        let json = self.to_json()?;
290        crate::storage::atomic_write(path.as_ref(), json.as_bytes())
291            .map_err(|error| SessionError::Io(error.to_string()))
292    }
293
294    /// Read a workspace from disk.
295    ///
296    /// # Errors
297    /// When the file cannot be read or parsed.
298    #[cfg(feature = "threads")]
299    pub fn load(path: impl AsRef<Path>) -> Result<Self, SessionError> {
300        let text = std::fs::read_to_string(path).map_err(|error| SessionError::Io(error.to_string()))?;
301        Self::from_json(&text)
302    }
303}
304
305/// Why a workspace could not be read or written.
306#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
307#[non_exhaustive]
308/// # Example
309///
310/// ```
311/// use crisol_core::state::SessionError;
312/// ```
313pub enum SessionError {
314    /// The JSON is malformed.
315    #[error("invalid workspace JSON: {0}")]
316    Json(String),
317    /// The file version is newer than this crate understands.
318    #[error("unsupported workspace version {0}")]
319    UnsupportedVersion(u32),
320    /// The file could not be read or written.
321    #[error("{0}")]
322    Io(String),
323}
324
325#[cfg(all(test, feature = "threads"))]
326mod tests {
327    use super::*;
328
329    fn test_directory(prefix: &str) -> std::path::PathBuf {
330        let thread: String = std::thread::current()
331            .name()
332            .unwrap_or("test")
333            .chars()
334            .map(|character| {
335                if character.is_ascii_alphanumeric() {
336                    character
337                } else {
338                    '_'
339                }
340            })
341            .collect();
342        std::path::PathBuf::from("/tmp").join(format!("{prefix}-{thread}"))
343    }
344
345    #[test]
346    fn documents_and_panels_round_trip() {
347        let mut workspace = Workspace::new();
348        workspace.add_document(WorkspaceDocument::new("one", "One"));
349        workspace.add_document(WorkspaceDocument::new("two", "Two"));
350        workspace.set_active(1);
351        workspace.theme = ThemeId::Dracula;
352        workspace.explorer = vec!["src".to_owned()];
353        workspace.panels.inspector = true;
354        workspace
355            .plot_views
356            .insert("main".to_owned(), WorkspacePlotView::new([0.0, 1.0], [2.0, 3.0]));
357        workspace.layout.split(
358            crate::state::layout::EditorGroupId(0),
359            crate::state::layout::SplitDirection::Horizontal,
360        );
361        workspace.save_layout("Review");
362        let json = workspace.to_json().expect("serialize");
363        let back = Workspace::from_json(&json).expect("parse");
364        assert_eq!(back, workspace);
365        assert_eq!(back.active_document().map(|doc| doc.title.as_str()), Some("Two"));
366        assert_eq!(back.active_layout, "Review");
367        assert!(back.named_layouts.contains_key("Review"));
368    }
369
370    #[test]
371    fn missing_fields_and_version_zero_migrate() {
372        let json = r#"{"documents":[{"id":"a","title":"A","dirty":true,"path":null}]}"#;
373        let workspace = Workspace::from_json(json).expect("migrate");
374        assert_eq!(workspace.version, Workspace::VERSION);
375        assert_eq!(workspace.documents.len(), 1);
376        assert!(workspace.panels.sidebar);
377        assert_eq!(workspace.active, 0);
378    }
379
380    #[test]
381    fn a_newer_version_is_rejected() {
382        let error = Workspace::from_json(r#"{"version": 9}"#).expect_err("newer");
383        assert!(matches!(error, SessionError::UnsupportedVersion(9)));
384    }
385
386    #[test]
387    fn normalize_clamps_active_and_sizes() {
388        let mut workspace = Workspace::new();
389        workspace.add_document(WorkspaceDocument::new("a", "A"));
390        workspace.active = 99;
391        workspace.sidebar_width = 1.0;
392        workspace.right_width = 9999.0;
393        workspace.bottom_height = 1.0;
394        workspace.normalize();
395        assert_eq!(workspace.active, 0);
396        assert_eq!(workspace.sidebar_width, 120.0);
397        assert_eq!(workspace.right_width, 800.0);
398        assert_eq!(workspace.bottom_height, 80.0);
399    }
400
401    #[test]
402    fn save_and_load_are_atomic() {
403        let directory = test_directory("crisol-workspace");
404        let _ = std::fs::remove_dir_all(&directory);
405        std::fs::create_dir_all(&directory).expect("create");
406        let path = directory.join("workspace.json");
407        let mut workspace = Workspace::new();
408        workspace.add_document(WorkspaceDocument::new("a", "A"));
409        workspace.save(&path).expect("save");
410        let back = Workspace::load(&path).expect("load");
411        assert_eq!(back, workspace);
412        let leftovers = std::fs::read_dir(&directory).expect("dir").count();
413        assert_eq!(leftovers, 1, "no temporary file stays behind");
414        let _ = std::fs::remove_dir_all(directory);
415    }
416}