rightkit_document_workspace/
settings.rs1use std::path::PathBuf;
5use std::sync::OnceLock;
6
7use rightkit_app_settings::{Document, Error as SettingsError, Schema, StoreOptions};
8use serde_json::{json, Map, Value};
9
10use crate::error::WorkspaceError;
11
12pub const SETTINGS_KEY: &str = "vr.settings.v1";
14const DOCUMENT_VERSION: u32 = 1;
18
19fn parse_object(raw: &str) -> Option<Map<String, Value>> {
20 match serde_json::from_str::<Value>(raw) {
21 Ok(Value::Object(map)) => Some(map),
22 _ => None,
23 }
24}
25
26#[derive(Debug)]
28pub struct SettingsWrite {
29 pub answer: Value,
31 pub committed: Option<Value>,
34}
35
36impl SettingsWrite {
37 pub fn diagnostics_enabled(&self) -> Option<bool> {
40 self.committed.as_ref().map(|settings| {
41 settings
42 .get("diagnostics")
43 .and_then(Value::as_bool)
44 .unwrap_or(true)
45 })
46 }
47}
48
49pub struct SettingsStore {
54 folder: Option<PathBuf>,
56 namespace: String,
57 document: OnceLock<Document>,
58 explorer: OnceLock<Document>,
59}
60
61impl SettingsStore {
62 pub fn new(data_dir: Option<PathBuf>, namespace: impl Into<String>) -> Self {
65 let namespace = namespace.into();
66 Self {
67 folder: data_dir.map(|dir| dir.join(&namespace)),
68 namespace,
69 document: OnceLock::new(),
70 explorer: OnceLock::new(),
71 }
72 }
73
74 pub fn in_app_folder(app_folder: PathBuf, namespace: impl Into<String>) -> Self {
78 Self {
79 folder: Some(app_folder),
80 namespace: namespace.into(),
81 document: OnceLock::new(),
82 explorer: OnceLock::new(),
83 }
84 }
85
86 fn document_path(&self, name: &str) -> Result<PathBuf, WorkspaceError> {
87 let folder = self
88 .folder
89 .as_ref()
90 .ok_or_else(|| WorkspaceError::Other("settings directory is unavailable".into()))?;
91 Ok(folder.join(name))
92 }
93
94 fn options(&self) -> StoreOptions {
95 StoreOptions::new(Schema::new(self.namespace.clone(), DOCUMENT_VERSION))
96 }
97
98 fn explorer_document(&self) -> Result<&Document, WorkspaceError> {
99 if let Some(document) = self.explorer.get() {
100 return Ok(document);
101 }
102 let opened =
103 Document::open_path_with(self.document_path("explorer.json")?, &self.options())
104 .map_err(settings_error)?;
105 Ok(self.explorer.get_or_init(|| opened))
106 }
107
108 fn document(&self) -> Result<&Document, WorkspaceError> {
111 if let Some(document) = self.document.get() {
112 return Ok(document);
113 }
114 let opened =
115 Document::open_path_with(self.document_path("settings.json")?, &self.options())
116 .map_err(settings_error)?;
117 Ok(self.document.get_or_init(|| opened))
118 }
119
120 pub fn persisted_diagnostics_enabled(&self) -> bool {
123 let Ok(path) = self.document_path("settings.json") else {
124 return true;
125 };
126 match Document::open_path_with(path, &self.options()) {
127 Ok(document) => diagnostics_of(&document),
128 Err(_) => true,
129 }
130 }
131
132 pub fn startup_diagnostics_enabled(&self) -> bool {
135 match self.document() {
136 Ok(document) => diagnostics_of(document),
137 Err(_) => false,
138 }
139 }
140
141 pub fn get(&self, key: &str, with_revision: Option<bool>) -> Result<Value, WorkspaceError> {
146 if key == SETTINGS_KEY {
147 let state = self.document()?.get().map_err(settings_error)?;
148 let revision = state.as_ref().map_or(0, |state| state.revision);
149 let value = state
150 .filter(|state| state.value.as_object().is_some_and(|map| !map.is_empty()))
151 .map(|state| state.value.to_string());
152 if with_revision == Some(true) {
153 return Ok(json!({ "value": value, "revision": revision }));
154 }
155 return Ok(value.map_or(Value::Null, Value::String));
156 }
157 let state = self.explorer_document()?.get().map_err(settings_error)?;
158 Ok(state
159 .and_then(|state| {
160 state
161 .value
162 .get(key)
163 .and_then(Value::as_str)
164 .map(str::to_owned)
165 })
166 .map_or(Value::Null, Value::String))
167 }
168
169 pub fn set(
177 &self,
178 key: &str,
179 value: &str,
180 expected_revision: Option<u64>,
181 merge: Option<bool>,
182 ) -> Result<SettingsWrite, WorkspaceError> {
183 if key == SETTINGS_KEY {
184 let map = parse_object(value)
185 .ok_or_else(|| WorkspaceError::Other("settings must be a JSON object".into()))?;
186 let document = self.document()?;
187 let state = if merge == Some(true) {
188 document.patch(DOCUMENT_VERSION, &Value::Object(map), expected_revision)
189 } else {
190 document.put(DOCUMENT_VERSION, Value::Object(map), expected_revision)
191 }
192 .map_err(settings_error)?;
193 let committed = state.value.to_string();
194 return Ok(SettingsWrite {
195 answer: json!({ "value": committed, "revision": state.revision }),
196 committed: Some(state.value),
197 });
198 }
199 self.explorer_document()?
200 .patch(DOCUMENT_VERSION, &json!({ key: value }), None)
201 .map_err(settings_error)?;
202 Ok(SettingsWrite {
203 answer: Value::Null,
204 committed: None,
205 })
206 }
207}
208
209fn diagnostics_of(document: &Document) -> bool {
210 document
211 .get()
212 .ok()
213 .flatten()
214 .and_then(|state| state.value.get("diagnostics").and_then(Value::as_bool))
215 .unwrap_or(true)
216}
217
218fn settings_error(error: SettingsError) -> WorkspaceError {
219 match error {
220 SettingsError::Conflict { expected, actual } => WorkspaceError::WriteConflict(format!(
223 "settings revision conflict: expected {expected}, found {actual}"
224 )),
225 other => WorkspaceError::Other(format!("settings store: {other}")),
226 }
227}