1use std::collections::{BTreeMap, BTreeSet};
19use std::sync::{Mutex, OnceLock};
20
21use serde::{Deserialize, Deserializer, Serialize, Serializer};
22use serde_json::Value as Json;
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
27pub struct ValueScope(&'static str);
28
29#[allow(
30 non_upper_case_globals,
31 reason = "the scopes read as names (`ValueScope::App`), like enum variants"
32)]
33impl ValueScope {
34 pub const App: ValueScope = ValueScope("app");
36 pub const Run: ValueScope = ValueScope("run");
38 #[deprecated(
40 since = "0.8.0",
41 note = "declare the host's scopes with `ValueScope::new` and `Layers::declare`"
42 )]
43 pub const Library: ValueScope = ValueScope("library");
44 #[deprecated(
46 since = "0.8.0",
47 note = "declare the host's scopes with `ValueScope::new` and `Layers::declare`"
48 )]
49 pub const Workspace: ValueScope = ValueScope("workspace");
50
51 pub const fn new(name: &'static str) -> ValueScope {
53 ValueScope(name)
54 }
55
56 pub fn named(name: &str) -> ValueScope {
59 static NAMES: OnceLock<Mutex<BTreeSet<&'static str>>> = OnceLock::new();
60 for known in ["app", "run"] {
61 if name == known {
62 return ValueScope(known);
63 }
64 }
65 let mut names = NAMES
66 .get_or_init(Mutex::default)
67 .lock()
68 .unwrap_or_else(std::sync::PoisonError::into_inner);
69 if let Some(n) = names.get(name) {
70 return ValueScope(n);
71 }
72 let n: &'static str = Box::leak(name.to_owned().into_boxed_str());
73 names.insert(n);
74 ValueScope(n)
75 }
76
77 pub fn name(self) -> &'static str {
78 self.0
79 }
80
81 pub fn editable(self) -> bool {
82 self != ValueScope::Run
83 }
84}
85
86impl Serialize for ValueScope {
87 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
88 s.serialize_str(self.0)
89 }
90}
91
92impl<'de> Deserialize<'de> for ValueScope {
93 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<ValueScope, D::Error> {
94 let name = String::deserialize(d)?;
95 Ok(ValueScope::named(&name))
96 }
97}
98
99#[derive(Clone, Debug, Default, PartialEq, Serialize)]
101pub struct Layers {
102 declared: Vec<ValueScope>,
104 offered: Vec<ValueScope>,
106 layers: BTreeMap<ValueScope, BTreeMap<String, Json>>,
108 app: BTreeMap<String, Json>,
110}
111
112impl Layers {
113 pub fn new() -> Layers {
114 Layers {
115 offered: vec![ValueScope::App],
116 ..Layers::default()
117 }
118 }
119
120 pub fn declare(&mut self, scope: ValueScope) {
124 if scope != ValueScope::App && scope != ValueScope::Run && !self.declared.contains(&scope) {
125 self.declared.push(scope);
126 }
127 }
128
129 pub fn declared(&self) -> &[ValueScope] {
131 &self.declared
132 }
133
134 pub fn stack(&self) -> Vec<ValueScope> {
136 let mut out = vec![ValueScope::App];
137 out.extend(self.declared.iter().copied());
138 out.push(ValueScope::Run);
139 out
140 }
141
142 pub fn offer(&mut self, scope: ValueScope, on: bool) {
146 if !scope.editable() || scope == ValueScope::App {
147 return;
148 }
149 self.declare(scope);
150 self.offered.retain(|s| *s != scope);
151 if on {
152 self.offered.push(scope);
153 }
154 let order = self.stack();
155 self.offered
156 .sort_by_key(|s| order.iter().position(|o| o == s));
157 }
158
159 pub fn offered(&self) -> &[ValueScope] {
161 &self.offered
162 }
163
164 fn map(&self, scope: ValueScope) -> Option<&BTreeMap<String, Json>> {
165 if scope == ValueScope::App {
166 return None;
167 }
168 self.layers.get(&scope)
169 }
170
171 fn map_mut(&mut self, scope: ValueScope) -> Option<&mut BTreeMap<String, Json>> {
172 if scope == ValueScope::App {
173 return None;
174 }
175 self.declare(scope);
176 Some(self.layers.entry(scope).or_default())
177 }
178
179 pub fn origin(&self, path: &str) -> ValueScope {
182 self.stack()
183 .into_iter()
184 .rev()
185 .find(|s| self.map(*s).is_some_and(|m| m.contains_key(path)))
186 .unwrap_or(ValueScope::App)
187 }
188
189 pub fn holders(&self, path: &str, store: &Json, default: &Json) -> Vec<ValueScope> {
192 let mut out = Vec::new();
193 if self.app_value(path, store) != *default {
194 out.push(ValueScope::App);
195 }
196 for s in self.stack().into_iter().skip(1) {
197 if self.map(s).is_some_and(|m| m.contains_key(path)) {
198 out.push(s);
199 }
200 }
201 out
202 }
203
204 pub fn value_in(&self, scope: ValueScope, path: &str, store: &Json) -> Option<Json> {
207 match scope {
208 ValueScope::App => Some(self.app_value(path, store)),
209 s => self.map(s).and_then(|m| m.get(path)).cloned(),
210 }
211 }
212
213 pub fn app_value(&self, path: &str, store: &Json) -> Json {
215 self.app.get(path).cloned().unwrap_or_else(|| store.clone())
216 }
217
218 pub fn set(
222 &mut self,
223 scope: ValueScope,
224 path: &str,
225 value: Json,
226 store: &Json,
227 ) -> Option<Json> {
228 match scope {
229 ValueScope::Run => None,
230 ValueScope::App => {
231 if self.origin(path) == ValueScope::App {
232 (value != *store).then_some(value)
233 } else {
234 self.app.insert(path.into(), value);
235 None
236 }
237 }
238 s => {
239 if self.origin(path) == ValueScope::App {
240 self.app.insert(path.into(), store.clone());
241 }
242 self.map_mut(s)?.insert(path.into(), value);
243 let effective = self.effective(path)?;
244 (effective != *store).then_some(effective)
245 }
246 }
247 }
248
249 pub fn set_run(&mut self, path: &str, value: Json, store: &Json) -> Option<Json> {
251 if self.origin(path) == ValueScope::App {
252 self.app.insert(path.into(), store.clone());
253 }
254 self.layers
255 .entry(ValueScope::Run)
256 .or_default()
257 .insert(path.into(), value.clone());
258 (value != *store).then_some(value)
259 }
260
261 fn effective(&self, path: &str) -> Option<Json> {
263 let o = self.origin(path);
264 self.map(o).and_then(|m| m.get(path)).cloned()
265 }
266
267 pub fn clear(
270 &mut self,
271 scope: ValueScope,
272 path: &str,
273 store: &Json,
274 default: &Json,
275 ) -> Option<Json> {
276 match scope {
277 ValueScope::Run => None,
278 ValueScope::App => {
279 if self.origin(path) == ValueScope::App {
280 (default != store).then(|| default.clone())
281 } else {
282 self.app.insert(path.into(), default.clone());
283 None
284 }
285 }
286 s => {
287 self.map_mut(s)?.remove(path)?;
288 let effective = match self.effective(path) {
289 Some(v) => v,
290 None => self.app.remove(path).unwrap_or_else(|| store.clone()),
291 };
292 (effective != *store).then_some(effective)
293 }
294 }
295 }
296
297 pub fn export(&self, scope: ValueScope) -> BTreeMap<String, Json> {
300 self.map(scope).cloned().unwrap_or_default()
301 }
302
303 pub fn load(
307 &mut self,
308 scope: ValueScope,
309 values: BTreeMap<String, Json>,
310 store: &dyn Fn(&str) -> Option<Json>,
311 ) -> Vec<(String, Json)> {
312 if scope == ValueScope::App {
313 return Vec::new();
314 }
315 let mut paths: Vec<String> = self.export(scope).into_keys().collect();
316 paths.extend(values.keys().cloned());
317 paths.sort();
318 paths.dedup();
319 let mut writes = Vec::new();
320 for path in &paths {
321 let Some(now) = store(path) else { continue };
322 let before = self.origin(path);
323 if before == ValueScope::App {
324 self.app.insert(path.clone(), now.clone());
325 }
326 if let Some(m) = self.map_mut(scope) {
327 match values.get(path) {
328 Some(v) => m.insert(path.clone(), v.clone()),
329 None => m.remove(path),
330 };
331 }
332 let effective = match self.effective(path) {
333 Some(v) => v,
334 None => self.app.remove(path).unwrap_or_else(|| now.clone()),
335 };
336 if effective != now {
337 writes.push((path.clone(), effective));
338 }
339 }
340 writes
341 }
342
343 pub fn app_doc(
347 &self,
348 values: &mut BTreeMap<String, Json>,
349 default: &dyn Fn(&str) -> Option<Json>,
350 ) {
351 for (path, v) in &self.app {
352 if default(path).as_ref() == Some(v) {
353 values.remove(path);
354 } else {
355 values.insert(path.clone(), v.clone());
356 }
357 }
358 }
359}
360
361#[cfg(test)]
362mod tests {
363 use super::*;
364 use serde_json::json;
365
366 const P: &str = "settings/appearance.theme";
367 const LIB: ValueScope = ValueScope::new("library");
368 const WS: ValueScope = ValueScope::new("workspace");
369
370 #[test]
371 fn the_host_declares_its_scopes_and_the_later_one_wins() {
372 let mut l = Layers::new();
373 l.declare(WS);
375 l.declare(LIB);
376 l.declare(WS);
377 assert_eq!(l.declared(), &[WS, LIB]);
378 l.offer(LIB, true);
379 l.offer(WS, true);
380 assert_eq!(l.offered(), &[ValueScope::App, WS, LIB]);
381 let mut store = json!(1);
382 store = l.set(LIB, P, json!(2), &store).unwrap();
383 assert_eq!(l.set(WS, P, json!(3), &store), None, "under the library");
384 assert_eq!(l.origin(P), LIB);
385 assert_eq!(l.holders(P, &store, &json!(1)), vec![WS, LIB]);
386 assert_eq!(l.clear(LIB, P, &store, &json!(1)), Some(json!(3)));
388 }
389
390 #[test]
391 fn a_scope_name_round_trips() {
392 let s: ValueScope = serde_json::from_value(json!("library")).unwrap();
393 assert_eq!(s, LIB);
394 assert_eq!(serde_json::to_value(ValueScope::App).unwrap(), json!("app"));
395 assert_eq!(ValueScope::named("run"), ValueScope::Run);
396 }
397
398 #[test]
399 fn a_layer_above_app_wins_and_its_reset_gives_app_back() {
400 let mut l = Layers::new();
401 l.offer(LIB, true);
402 l.offer(ValueScope::Run, true);
403 assert_eq!(l.offered(), &[ValueScope::App, LIB]);
404 let store = json!("dark");
405 assert_eq!(l.set(LIB, P, json!("light"), &store), Some(json!("light")));
407 let store = json!("light");
408 assert_eq!(l.origin(P), LIB);
409 assert_eq!(l.value_in(ValueScope::App, P, &store), Some(json!("dark")));
410 assert_eq!(l.set(ValueScope::App, P, json!("system"), &store), None);
412 let mut doc = BTreeMap::from([(P.to_string(), json!("light"))]);
414 l.app_doc(&mut doc, &|_| Some(json!("dark")));
415 assert_eq!(doc[P], json!("system"));
416 assert_eq!(
418 l.clear(LIB, P, &store, &json!("dark")),
419 Some(json!("system"))
420 );
421 assert_eq!(l.origin(P), ValueScope::App);
422 let mut doc = BTreeMap::new();
423 l.app_doc(&mut doc, &|_| Some(json!("dark")));
424 assert!(doc.is_empty(), "nothing kept aside any more");
425 }
426
427 #[test]
428 fn workspace_wins_over_library_and_run_over_both() {
429 let mut l = Layers::new();
430 let mut store = json!(1);
431 store = l.set(LIB, P, json!(2), &store).unwrap();
432 store = l.set(WS, P, json!(3), &store).unwrap();
433 assert_eq!(l.origin(P), WS);
434 assert_eq!(l.holders(P, &store, &json!(1)), vec![LIB, WS]);
435 store = l.set_run(P, json!(4), &store).unwrap();
436 assert_eq!(l.origin(P), ValueScope::Run);
437 assert_eq!(l.set(ValueScope::Run, P, json!(5), &store), None);
438 assert_eq!(l.clear(WS, P, &store, &json!(1)), None);
440 assert_eq!(l.value_in(LIB, P, &store), Some(json!(2)));
441 }
442
443 #[test]
444 fn loading_a_layer_writes_what_changes() {
445 let mut l = Layers::new();
446 let store = |_: &str| Some(json!(1));
447 let w = l.load(WS, BTreeMap::from([(P.to_string(), json!(9))]), &store);
448 assert_eq!(w, vec![(P.to_string(), json!(9))]);
449 let store = |_: &str| Some(json!(9));
450 let w = l.load(WS, BTreeMap::new(), &store);
451 assert_eq!(w, vec![(P.to_string(), json!(1))]);
452 assert_eq!(l.origin(P), ValueScope::App);
453 }
454}