Skip to main content

Mountain/IPC/WindServiceHandlers/Utilities/
RecentlyOpened.rs

1#![allow(non_snake_case, unused_variables, dead_code, unused_imports)]
2
3//! Recently-opened workspaces/files persistence.
4//! File lives at `~/.land/workspaces/RecentlyOpened.json`. Parse failures
5//! degrade to an empty `{workspaces, files}` envelope so the UI never
6//! sees a missing field.
7
8use serde_json::{Value, json};
9
10pub fn RecentlyOpenedPath() -> std::path::PathBuf {
11	let Home = std::env::var("HOME")
12		.or_else(|_| std::env::var("USERPROFILE"))
13		.unwrap_or_default();
14
15	std::path::PathBuf::from(Home)
16		.join(".land")
17		.join("workspaces")
18		.join("RecentlyOpened.json")
19}
20
21pub fn ReadRecentlyOpened() -> Result<Value, String> {
22	let Path = RecentlyOpenedPath();
23
24	match std::fs::read_to_string(&Path) {
25		Ok(Contents) => {
26			match serde_json::from_str::<Value>(&Contents) {
27				Ok(Parsed) => Ok(Parsed),
28
29				Err(_) => Ok(json!({ "workspaces": [], "files": [] })),
30			}
31		},
32
33		Err(_) => Ok(json!({ "workspaces": [], "files": [] })),
34	}
35}
36
37pub fn MutateRecentlyOpened<F:FnOnce(&mut serde_json::Map<String, Value>)>(Apply:F) {
38	let Path = RecentlyOpenedPath();
39
40	let mut Parsed:serde_json::Map<String, Value> = std::fs::read_to_string(&Path)
41		.ok()
42		.and_then(|Contents| serde_json::from_str::<Value>(&Contents).ok())
43		.and_then(|V| V.as_object().cloned())
44		.unwrap_or_default();
45
46	if !Parsed.contains_key("workspaces") {
47		Parsed.insert("workspaces".into(), json!([]));
48	}
49
50	if !Parsed.contains_key("files") {
51		Parsed.insert("files".into(), json!([]));
52	}
53
54	Apply(&mut Parsed);
55
56	if let Some(Parent) = Path.parent() {
57		let _ = std::fs::create_dir_all(Parent);
58	}
59
60	if let Ok(Serialised) = serde_json::to_vec_pretty(&Value::Object(Parsed)) {
61		let _ = std::fs::write(&Path, Serialised);
62	}
63}