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	std::path::PathBuf::from(Home)
15		.join(".land")
16		.join("workspaces")
17		.join("RecentlyOpened.json")
18}
19
20pub fn ReadRecentlyOpened() -> Result<Value, String> {
21	let Path = RecentlyOpenedPath();
22	match std::fs::read_to_string(&Path) {
23		Ok(Contents) => {
24			match serde_json::from_str::<Value>(&Contents) {
25				Ok(Parsed) => Ok(Parsed),
26				Err(_) => Ok(json!({ "workspaces": [], "files": [] })),
27			}
28		},
29		Err(_) => Ok(json!({ "workspaces": [], "files": [] })),
30	}
31}
32
33pub fn MutateRecentlyOpened<F:FnOnce(&mut serde_json::Map<String, Value>)>(Apply:F) {
34	let Path = RecentlyOpenedPath();
35	let mut Parsed:serde_json::Map<String, Value> = std::fs::read_to_string(&Path)
36		.ok()
37		.and_then(|Contents| serde_json::from_str::<Value>(&Contents).ok())
38		.and_then(|V| V.as_object().cloned())
39		.unwrap_or_default();
40	if !Parsed.contains_key("workspaces") {
41		Parsed.insert("workspaces".into(), json!([]));
42	}
43	if !Parsed.contains_key("files") {
44		Parsed.insert("files".into(), json!([]));
45	}
46	Apply(&mut Parsed);
47	if let Some(Parent) = Path.parent() {
48		let _ = std::fs::create_dir_all(Parent);
49	}
50	if let Ok(Serialised) = serde_json::to_vec_pretty(&Value::Object(Parsed)) {
51		let _ = std::fs::write(&Path, Serialised);
52	}
53}