1use 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
21#[non_exhaustive]
22pub struct WorkspaceDocument {
28 pub id: String,
30 pub title: String,
32 pub dirty: bool,
34 pub path: Option<PathBuf>,
36 #[serde(default)]
38 pub payload: serde_json::Value,
39}
40
41impl WorkspaceDocument {
42 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
56#[non_exhaustive]
57pub struct WorkspacePanels {
63 pub sidebar: bool,
65 pub inspector: bool,
67 pub output: bool,
69 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
86#[non_exhaustive]
87pub struct WorkspacePlotView {
93 pub x: [f64; 2],
95 pub y: [f64; 2],
97 #[serde(default)]
99 pub hidden: Vec<String>,
100}
101
102impl WorkspacePlotView {
103 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
115#[serde(default)]
116#[non_exhaustive]
117pub struct Workspace {
123 pub version: u32,
125 pub theme: ThemeId,
127 pub follow_system: bool,
129 pub reduced_motion: bool,
131 pub documents: Vec<WorkspaceDocument>,
133 pub active: usize,
135 pub explorer: Vec<String>,
137 pub panels: WorkspacePanels,
139 pub sidebar_width: f32,
141 pub right_width: f32,
143 pub bottom_height: f32,
145 pub plot_views: BTreeMap<String, WorkspacePlotView>,
147 pub layout: Layout,
149 pub named_layouts: BTreeMap<String, Layout>,
151 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 pub const VERSION: u32 = 1;
180
181 pub fn new() -> Self {
183 Self::default()
184 }
185
186 pub fn with_documents(documents: Vec<WorkspaceDocument>) -> Self {
188 Self {
189 documents,
190 ..Self::default()
191 }
192 }
193
194 pub fn add_document(&mut self, document: WorkspaceDocument) -> usize {
196 self.documents.push(document);
197 self.documents.len() - 1
198 }
199
200 pub fn active_document(&self) -> Option<&WorkspaceDocument> {
202 self.documents.get(self.active)
203 }
204
205 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 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 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 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 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 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 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 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 #[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 #[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#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
307#[non_exhaustive]
308pub enum SessionError {
314 #[error("invalid workspace JSON: {0}")]
316 Json(String),
317 #[error("unsupported workspace version {0}")]
319 UnsupportedVersion(u32),
320 #[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}