crisol-core 1.1.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Versioned workspace persistence: documents, active tab, explorer, panels, theme,
//! and plot views in one atomically written file.
//!
//! ```
//! use crisol_core::state::session;
//! ```

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;

/// One open document in the workspace.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::WorkspaceDocument;
/// ```
pub struct WorkspaceDocument {
    /// Stable application id.
    pub id: String,
    /// Tab title.
    pub title: String,
    /// Unsaved changes.
    pub dirty: bool,
    /// Path on disk, when the document has one.
    pub path: Option<PathBuf>,
    /// Application-specific payload (cursor, scroll offset, model data).
    #[serde(default)]
    pub payload: serde_json::Value,
}

impl WorkspaceDocument {
    /// A document with no path and no payload.
    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,
        }
    }
}

/// Which panels are visible.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::WorkspacePanels;
/// ```
pub struct WorkspacePanels {
    /// Explorer.
    pub sidebar: bool,
    /// Right inspector.
    pub inspector: bool,
    /// Bottom output.
    pub output: bool,
    /// Status bar.
    pub status_bar: bool,
}

impl Default for WorkspacePanels {
    fn default() -> Self {
        Self {
            sidebar: true,
            inspector: false,
            output: false,
            status_bar: true,
        }
    }
}

/// A serializable plot view: the visible x and y ranges plus hidden series.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::WorkspacePlotView;
/// ```
pub struct WorkspacePlotView {
    /// Visible x range.
    pub x: [f64; 2],
    /// Visible y range.
    pub y: [f64; 2],
    /// Hidden series names.
    #[serde(default)]
    pub hidden: Vec<String>,
}

impl WorkspacePlotView {
    /// A view from two ranges.
    pub fn new(x: [f64; 2], y: [f64; 2]) -> Self {
        Self {
            x,
            y,
            hidden: Vec::new(),
        }
    }
}

/// The persisted workspace.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::Workspace;
/// ```
pub struct Workspace {
    /// File format version.
    pub version: u32,
    /// Requested theme.
    pub theme: ThemeId,
    /// Follow the desktop light/dark preference.
    pub follow_system: bool,
    /// Reduced motion.
    pub reduced_motion: bool,
    /// Open documents, in tab order.
    pub documents: Vec<WorkspaceDocument>,
    /// Active document index (clamped on load).
    pub active: usize,
    /// Expanded explorer keys.
    pub explorer: Vec<String>,
    /// Visible panels.
    pub panels: WorkspacePanels,
    /// Left panel width.
    pub sidebar_width: f32,
    /// Right panel width.
    pub right_width: f32,
    /// Bottom panel height.
    pub bottom_height: f32,
    /// Plot views by plot id.
    pub plot_views: BTreeMap<String, WorkspacePlotView>,
    /// The current editor layout.
    pub layout: Layout,
    /// Named layouts ("Analysis", "Review") that can be switched from the palette.
    pub named_layouts: BTreeMap<String, Layout>,
    /// The name of the active named 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 {
    /// The current file version.
    pub const VERSION: u32 = 1;

    /// A workspace with the current version and default panel sizes.
    pub fn new() -> Self {
        Self::default()
    }

    /// A workspace with documents.
    pub fn with_documents(documents: Vec<WorkspaceDocument>) -> Self {
        Self {
            documents,
            ..Self::default()
        }
    }

    /// Add a document and return its index.
    pub fn add_document(&mut self, document: WorkspaceDocument) -> usize {
        self.documents.push(document);
        self.documents.len() - 1
    }

    /// The active document.
    pub fn active_document(&self) -> Option<&WorkspaceDocument> {
        self.documents.get(self.active)
    }

    /// Select an existing document.
    pub fn set_active(&mut self, index: usize) -> bool {
        if index < self.documents.len() {
            self.active = index;
            true
        } else {
            false
        }
    }

    /// Clamp the active index and the panel sizes after a load.
    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();
        }
    }

    /// Save the current layout under a name and return the name.
    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
    }

    /// Switch to a named layout. Returns whether it existed.
    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
    }

    /// Serialize as pretty JSON.
    ///
    /// # Errors
    /// When serialization fails (it does not for this type).
    pub fn to_json(&self) -> Result<String, SessionError> {
        serde_json::to_string_pretty(self).map_err(|error| SessionError::Json(error.to_string()))
    }

    /// Parse a workspace, migrating an older version and rejecting a newer one.
    ///
    /// # Errors
    /// When the JSON is malformed or the version is newer than [`Self::VERSION`].
    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()))?;
        // `as u32` wrapped 2^32 + 1 to 1 and let a far newer file through.
        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 {
            // Version 0 had no `version` field and no plot views. `serde(default)` fills
            // every field added since; write the current version before deserializing.
            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)
    }

    /// Write the workspace atomically.
    ///
    /// # Errors
    /// When serialization or the write fails.
    #[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()))
    }

    /// Read a workspace from disk.
    ///
    /// # Errors
    /// When the file cannot be read or parsed.
    #[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)
    }
}

/// Why a workspace could not be read or written.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::SessionError;
/// ```
pub enum SessionError {
    /// The JSON is malformed.
    #[error("invalid workspace JSON: {0}")]
    Json(String),
    /// The file version is newer than this crate understands.
    #[error("unsupported workspace version {0}")]
    UnsupportedVersion(u32),
    /// The file could not be read or written.
    #[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);
    }
}