1use std::collections::HashMap;
15use std::path::{Path, PathBuf};
16use std::sync::{Arc, OnceLock};
17use std::time::Duration;
18
19use tokio::sync::broadcast;
20
21use super::config_watcher_fs::{broadcast_full_config, resolve_settings_dir};
22use super::eventbus::EventBus;
23use super::fs_watch::{FsWatchEvent, FsWatchEventKind, FsWatchPool};
24use super::mps::Broker;
25use super::wconfig::{self, ConfigError, ConfigState, WidgetConfigType};
26
27pub const USER_WIDGETS_FILE: &str = "widgets.json";
28
29pub fn user_widgets_path() -> PathBuf {
30 resolve_settings_dir().join(USER_WIDGETS_FILE)
31}
32
33pub fn read_user_widgets(path: &Path) -> Result<HashMap<String, WidgetConfigType>, ConfigError> {
37 if !path.exists() {
38 return Ok(HashMap::new());
39 }
40 let file = path.to_string_lossy().to_string();
41 let content = std::fs::read_to_string(path)
42 .map_err(|e| ConfigError { file: file.clone(), err: format!("cannot read widgets.json: {e}"), ..Default::default() })?;
43 parse_user_widgets(&content, &file)
44}
45
46pub fn parse_user_widgets(content: &str, file: &str) -> Result<HashMap<String, WidgetConfigType>, ConfigError> {
48 if wconfig::config_text_is_blank(content) {
49 return Ok(HashMap::new());
50 }
51 wconfig::parse_config_text(content).map_err(|e| ConfigError {
52 file: file.to_string(),
53 err: format!("widgets.json doesn't parse, so your own widgets are not loaded: {e}"),
54 line: Some(e.line() as u32),
55 column: Some(e.column() as u32),
56 })
57}
58
59fn builtin_widgets() -> &'static HashMap<String, WidgetConfigType> {
61 static BUILTIN: OnceLock<HashMap<String, WidgetConfigType>> = OnceLock::new();
62 BUILTIN.get_or_init(|| wconfig::build_default_config().widgets)
63}
64
65pub fn merge_widgets(
67 builtin: &HashMap<String, WidgetConfigType>,
68 user: HashMap<String, WidgetConfigType>,
69) -> HashMap<String, WidgetConfigType> {
70 let mut merged = builtin.clone();
71 merged.extend(user);
72 merged
73}
74
75static LAST_USER: std::sync::Mutex<Option<HashMap<String, WidgetConfigType>>> = std::sync::Mutex::new(None);
79
80pub fn last_v1_entries() -> HashMap<String, WidgetConfigType> {
82 let guard = LAST_USER.lock().unwrap_or_else(|p| p.into_inner());
83 guard
84 .as_ref()
85 .map(|u| u.iter().filter(|(_, e)| !e.module.is_empty()).map(|(k, e)| (k.clone(), e.clone())).collect())
86 .unwrap_or_default()
87}
88
89fn apply(config_watcher: &ConfigState, user: HashMap<String, WidgetConfigType>) {
90 config_watcher.set_widgets_config_errors(Vec::new());
92 wconfig::validate_widget_configs(&user);
93 *LAST_USER.lock().unwrap_or_else(|p| p.into_inner()) = Some(user);
94 if let Some(svc) = super::widget::packages::service() {
95 svc.rescan(&last_v1_entries());
96 }
97 recompute(config_watcher);
98}
99
100pub fn recompute(config_watcher: &ConfigState) {
104 let user = LAST_USER.lock().unwrap_or_else(|p| p.into_inner()).clone().unwrap_or_default();
105 let mut base = builtin_widgets().clone();
106 if let Some(svc) = super::widget::packages::service() {
107 base.extend(super::widget::packages::widget_entries(&svc.list()));
108 }
109 config_watcher.update_widgets(merge_widgets(&base, user));
110}
111
112fn same_section(a: &serde_json::Value, b: &serde_json::Value) -> bool {
114 let view = |e: &serde_json::Value| e.pointer("/blockdef/meta/view").cloned();
115 a.get("section").is_some() && a.get("section") == b.get("section") && view(a) == view(b)
116}
117
118pub fn section_entry_in(content: &str, base: &str, entry: serde_json::Value) -> Result<(String, Option<String>), String> {
124 let widgets: serde_json::Map<String, serde_json::Value> = if wconfig::config_text_is_blank(content) {
125 serde_json::Map::new()
126 } else {
127 wconfig::parse_config_text(content).map_err(|e| format!("widgets.json doesn't parse, so it was left alone: {e}"))?
128 };
129 for n in 1..=50 {
130 let key = if n == 1 { base.to_string() } else { format!("{base}-{n}") };
131 match widgets.get(&key) {
132 Some(existing) if same_section(existing, &entry) => return Ok((key, None)),
133 Some(_) => continue,
134 None => {
135 let text = insert_member(content, &key, &entry)?;
136 return Ok((key, Some(text)));
137 }
138 }
139 }
140 Err(format!("widgets.json has no free key for {base}"))
141}
142
143struct ObjectEnd {
145 close: usize,
147 last: Option<(char, usize)>,
149}
150
151fn top_level_object_end(text: &str) -> Option<ObjectEnd> {
153 let mut depth = 0usize;
154 let mut last: Option<(char, usize)> = None;
155 let mut in_string = false;
156 let mut escaped = false;
157 let mut chars = text.char_indices().peekable();
158 while let Some((i, c)) = chars.next() {
159 if in_string {
160 if escaped {
161 escaped = false;
162 } else if c == '\\' {
163 escaped = true;
164 } else if c == '"' {
165 in_string = false;
166 last = Some(('"', i + 1));
167 }
168 continue;
169 }
170 match c {
171 '/' if chars.peek().is_some_and(|&(_, n)| n == '/') => {
172 while chars.next_if(|&(_, n)| n != '\n').is_some() {}
173 }
174 '/' if chars.peek().is_some_and(|&(_, n)| n == '*') => {
175 chars.next();
176 let mut prev = ' ';
177 for (_, n) in chars.by_ref() {
178 if prev == '*' && n == '/' {
179 break;
180 }
181 prev = n;
182 }
183 }
184 '"' => in_string = true,
185 '{' | '[' => {
186 depth += 1;
187 last = Some((c, i + 1));
188 }
189 '}' | ']' => {
190 depth = depth.saturating_sub(1);
191 if depth == 0 && c == '}' {
192 return Some(ObjectEnd { close: i, last });
193 }
194 last = Some((c, i + 1));
195 }
196 c if c.is_whitespace() || c == '\u{feff}' => {}
197 _ => last = Some((c, i + c.len_utf8())),
198 }
199 }
200 None
201}
202
203fn insert_member(content: &str, key: &str, entry: &serde_json::Value) -> Result<String, String> {
206 use serde::Serialize;
207 let mut body = Vec::new();
208 let mut ser = serde_json::Serializer::with_formatter(&mut body, serde_json::ser::PrettyFormatter::with_indent(b" "));
209 entry.serialize(&mut ser).map_err(|e| e.to_string())?;
210 let body = String::from_utf8(body).map_err(|e| e.to_string())?.replace('\n', "\n ");
211 let member = format!(" {}: {}", serde_json::to_string(key).map_err(|e| e.to_string())?, body);
212 let Some(end) = top_level_object_end(content) else {
213 let head = content.trim_end();
215 let gap = if head.is_empty() { "" } else { "\n" };
216 return Ok(format!("{head}{gap}{{\n{member}\n}}\n"));
217 };
218 let (before, after) = content.split_at(end.close);
219 let mut before = before.to_string();
220 if let Some((c, at)) = end.last {
222 if c != '{' && c != ',' {
223 before.insert(at, ',');
224 }
225 }
226 let before = before.trim_end_matches([' ', '\t']);
227 let gap = if before.ends_with('\n') { "" } else { "\n" };
228 Ok(format!("{before}{gap}{member}\n{after}"))
229}
230
231pub fn add_section_entry(
236 config_watcher: &Arc<ConfigState>,
237 event_bus: &Arc<EventBus>,
238 base: &str,
239 entry: serde_json::Value,
240) -> Result<String, String> {
241 static WRITE: std::sync::Mutex<()> = std::sync::Mutex::new(());
242 let _one_at_a_time = WRITE.lock().unwrap_or_else(|p| p.into_inner());
243 let path = user_widgets_path();
244 let content = match std::fs::read_to_string(&path) {
245 Ok(c) => c,
246 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
247 Err(e) => return Err(format!("read widgets.json: {e}")),
248 };
249 let (key, text) = section_entry_in(&content, base, entry)?;
250 if let Some(text) = text {
251 if let Some(dir) = path.parent() {
252 std::fs::create_dir_all(dir).map_err(|e| format!("create the settings folder: {e}"))?;
253 }
254 crate::registry::atomic::write_atomic(&path, text.as_bytes()).map_err(|e| format!("write widgets.json: {e}"))?;
256 }
257 apply(config_watcher, read_user_widgets(&path).map_err(|e| e.err)?);
258 broadcast_full_config(config_watcher, event_bus);
259 Ok(key)
260}
261
262pub fn load_user_widgets_from_disk(config_watcher: &ConfigState) {
263 let path = user_widgets_path();
264 match read_user_widgets(&path) {
265 Ok(user) => {
266 tracing::info!(path = %path.display(), count = user.len(), "user widgets.json loaded");
267 apply(config_watcher, user);
268 }
269 Err(e) => {
270 tracing::warn!(path = %path.display(), error = %e.err, line = ?e.line, "user widgets.json failed to load (built-ins only)");
271 config_watcher.set_widgets_config_errors(vec![e]);
273 }
274 }
275}
276
277fn is_user_widgets_event(event: &FsWatchEvent) -> bool {
278 let is_file = event.path.file_name().map(|n| n == USER_WIDGETS_FILE).unwrap_or(false);
279 is_file && matches!(event.kind, FsWatchEventKind::Created | FsWatchEventKind::Modified)
282}
283
284fn on_changed(config_watcher: &Arc<ConfigState>, event_bus: &Arc<EventBus>, broker: &Broker, user: HashMap<String, WidgetConfigType>) {
287 apply(config_watcher, user);
288 broadcast_full_config(config_watcher, event_bus);
289 let packages = super::widget::packages::service().map(|s| s.list()).unwrap_or_default();
290 super::widget::packages::publish(broker, &packages);
291}
292
293pub fn spawn_user_widgets_watcher(
294 pool: Arc<FsWatchPool>,
295 config_watcher: Arc<ConfigState>,
296 event_bus: Arc<EventBus>,
297 broker: Arc<Broker>,
298) {
299 let path = user_widgets_path();
300 let Some(dir) = path.parent() else {
301 return;
302 };
303 if !dir.exists() {
304 tracing::warn!(dir = %dir.display(), "settings directory does not exist, widgets.json watcher not started");
305 return;
306 }
307
308 let mut events = pool.events();
311 let _ = pool.subscribe_file(&path);
312 tracing::info!(path = %path.display(), "fs_watch subscription active for user widgets.json");
313
314 let watched_path = path.clone();
315 tokio::spawn(async move {
316 loop {
317 match events.recv().await {
318 Ok(ev) if is_user_widgets_event(&ev) => {}
319 Ok(_) => continue,
320 Err(broadcast::error::RecvError::Closed) => {
321 tracing::info!("user widgets watcher event stream closed, stopping");
322 break;
323 }
324 Err(broadcast::error::RecvError::Lagged(skipped)) => {
325 tracing::warn!(skipped, "user widgets watcher lagged; reloading defensively");
326 }
327 }
328 tokio::time::sleep(Duration::from_millis(300)).await;
329 while events.try_recv().is_ok() {}
330
331 match read_user_widgets(&watched_path) {
332 Ok(user) => {
333 tracing::info!(path = %watched_path.display(), "user widgets.json changed, reloading");
334 let (c, e, b) = (config_watcher.clone(), event_bus.clone(), broker.clone());
336 let _ = tokio::task::spawn_blocking(move || on_changed(&c, &e, &b, user)).await;
337 }
338 Err(e) => {
339 tracing::warn!(path = %watched_path.display(), error = %e.err, line = ?e.line, "user widgets.json reload parse error (keeping previous widgets)");
340 if config_watcher.set_widgets_config_errors(vec![e]) {
342 broadcast_full_config(&config_watcher, &event_bus);
343 }
344 }
345 }
346 }
347 });
348}
349
350#[cfg(test)]
351mod tests {
352 use super::*;
353
354 fn widget(label: &str) -> WidgetConfigType {
355 WidgetConfigType { label: label.to_string(), ..Default::default() }
356 }
357
358 #[test]
359 fn a_change_to_widgets_json_tells_the_ui_the_package_list_too() {
360 let seen = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
361 let broker = Broker::new();
362 let log = seen.clone();
363 broker.add_observer(Arc::new(move |ev| log.lock().unwrap().push(ev.event.clone())));
364 let config = Arc::new(ConfigState::new());
365 on_changed(&config, &Arc::new(EventBus::new()), &broker, HashMap::from([("mine".to_string(), widget("Mine"))]));
366 assert!(seen.lock().unwrap().iter().any(|e| e == super::super::mps::EVENT_WIDGET_PACKAGES));
367 }
368
369 #[test]
370 fn a_section_entry_is_added_once_and_never_to_a_file_that_doesnt_parse() {
371 let base = "section@warden-jobs";
372 let entry = serde_json::json!({ "label": "Jobs", "section": "jobs", "blockdef": { "meta": { "view": "warden" } } });
373 let (key, text) = section_entry_in("", base, entry.clone()).unwrap();
374 let parsed: HashMap<String, WidgetConfigType> = serde_json::from_str(&text.unwrap()).unwrap();
375 assert_eq!((key.as_str(), parsed[base].section.as_str()), (base, "jobs"));
376 let (_, both) = section_entry_in(r#"{"mine@x":{"label":"Mine"}}"#, base, entry.clone()).unwrap();
378 let both = both.unwrap();
379 assert!(both.contains("mine@x") && both.contains(base));
380 assert_eq!(section_entry_in(&both, base, entry.clone()).unwrap(), (base.to_string(), None));
381 assert!(section_entry_in("{ half typed", base, entry).is_err());
382 }
383
384 #[test]
385 fn a_section_entry_key_the_user_reused_for_something_else_is_never_handed_back() {
386 let base = "section@warden-jobs";
387 let entry = serde_json::json!({ "label": "Jobs", "section": "jobs", "blockdef": { "meta": { "view": "warden" } } });
388 let taken = r#"{"section@warden-jobs":{"label":"Mine","blockdef":{"meta":{"view":"term"}}}}"#;
389 let (key, text) = section_entry_in(taken, base, entry.clone()).unwrap();
390 assert_eq!(key, "section@warden-jobs-2");
391 let text = text.unwrap();
392 assert!(text.contains("\"Mine\""));
393 assert_eq!(section_entry_in(&text, base, entry).unwrap(), ("section@warden-jobs-2".to_string(), None));
395 }
396
397 #[test]
398 fn a_missing_or_empty_file_is_no_widgets() {
399 let dir = tempfile::tempdir().unwrap();
400 let path = dir.path().join(USER_WIDGETS_FILE);
401 assert!(read_user_widgets(&path).unwrap().is_empty());
402 std::fs::write(&path, " \n").unwrap();
403 assert!(read_user_widgets(&path).unwrap().is_empty());
404 }
405
406 #[test]
407 fn reads_an_ext_widget_with_its_module() {
408 let dir = tempfile::tempdir().unwrap();
409 let path = dir.path().join(USER_WIDGETS_FILE);
410 std::fs::write(
411 &path,
412 r#"{"ext@hello":{"label":"Hello","module":"hello/index.js","blockdef":{"meta":{"view":"ext:hello"}}}}"#,
413 )
414 .unwrap();
415 let user = read_user_widgets(&path).unwrap();
416 assert_eq!(user["ext@hello"].module, "hello/index.js");
417 }
418
419 #[test]
420 fn a_malformed_file_is_an_error_not_an_empty_set() {
421 let dir = tempfile::tempdir().unwrap();
422 let path = dir.path().join(USER_WIDGETS_FILE);
423 std::fs::write(&path, "{ not json").unwrap();
424 assert!(read_user_widgets(&path).is_err());
425 }
426
427 #[test]
428 fn user_entries_add_widgets_and_replace_builtins_by_key() {
429 let builtin = HashMap::from([("defwidget@a".to_string(), widget("A")), ("defwidget@b".to_string(), widget("B"))]);
430 let user = HashMap::from([("defwidget@b".to_string(), widget("B2")), ("ext@c".to_string(), widget("C"))]);
431 let merged = merge_widgets(&builtin, user);
432 assert_eq!(merged.len(), 3);
433 assert_eq!(merged["defwidget@a"].label, "A");
434 assert_eq!(merged["defwidget@b"].label, "B2");
435 assert_eq!(merged["ext@c"].label, "C");
436 }
437
438 #[test]
439 fn the_merge_always_starts_from_the_builtins() {
440 let builtin = HashMap::from([("defwidget@a".to_string(), widget("A"))]);
442 let first = merge_widgets(&builtin, HashMap::from([("ext@c".to_string(), widget("C"))]));
443 assert!(first.contains_key("ext@c"));
444 let second = merge_widgets(&builtin, HashMap::new());
445 assert!(!second.contains_key("ext@c"));
446 }
447
448 const ENTRY: &str = r#"{ "label": "Jobs", "section": "jobs", "blockdef": { "meta": { "view": "warden" } } }"#;
449
450 fn entry() -> serde_json::Value {
451 serde_json::from_str(ENTRY).unwrap()
452 }
453
454 #[test]
455 fn a_file_with_comments_and_a_trailing_comma_loads_its_entry() {
456 let text = "// my buttons\n{\n /* the docs */\n \"my-docs\": { \"label\": \"Docs\", \"module\": \"a//b\", },\n}\n";
457 let user = parse_user_widgets(text, "widgets.json").unwrap();
458 assert_eq!(user.len(), 1);
459 assert_eq!(user["my-docs"].label, "Docs");
460 assert_eq!(user["my-docs"].module, "a//b");
462 }
463
464 #[test]
465 fn a_file_with_nothing_but_comments_is_no_widgets() {
466 assert!(parse_user_widgets("// nothing here yet\n/* or here */\n", "widgets.json").unwrap().is_empty());
467 assert!(parse_user_widgets("\u{feff}", "widgets.json").unwrap().is_empty());
468 }
469
470 #[test]
471 fn the_text_a_new_file_starts_with_parses_to_no_widgets_and_says_what_each_field_is() {
472 let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../frontend/app/util/widgets-json-template.jsonc");
473 let text = std::fs::read_to_string(path).unwrap();
474 assert!(parse_user_widgets(&text, "widgets.json").unwrap().is_empty());
475 for field in [
476 "label",
477 "icon",
478 "color",
479 "description",
480 "display:order",
481 "display:pinned",
482 "blockdef",
483 "singleton",
484 "scope",
485 "children",
486 "section",
487 "module",
488 ] {
489 assert!(text.contains(&format!("\"{field}\"")), "the text says nothing about {field}");
490 }
491 let live: Vec<String> = text
493 .lines()
494 .map(|l| l.strip_prefix(" // ").unwrap_or(l).to_string())
496 .collect();
497 let user = parse_user_widgets(&live.join("\n"), "widgets.json").unwrap();
498 assert_eq!(user["defwidget@my-docs"].label, "Docs");
499 }
500
501 #[test]
502 fn a_file_that_does_not_parse_names_its_line_and_column() {
503 let err = parse_user_widgets("{\n \"a\": { \"label\": \"A\" },\n \"b\": oops,\n}\n", "C:/x/widgets.json").unwrap_err();
504 assert_eq!((err.line, err.file.as_str()), (Some(3), "C:/x/widgets.json"));
505 assert!(err.column.is_some());
506 assert!(err.err.contains("line 3"), "{}", err.err);
507 let err = parse_user_widgets("// one\n// two\n{ \"a\": oops }", "widgets.json").unwrap_err();
509 assert_eq!(err.line, Some(3));
510 }
511
512 #[test]
513 fn adding_an_entry_keeps_every_comment_and_the_order_of_the_file() {
514 let text = "// my buttons\n{\n /* first */\n \"mine\": { \"label\": \"M // }\" } // the only one\n}\n";
515 let (key, out) = section_entry_in(text, "section@warden-jobs", entry()).unwrap();
516 let out = out.unwrap();
517 for kept in ["// my buttons", "/* first */", "\"M // }\"", "// the only one"] {
518 assert!(out.contains(kept), "lost {kept:?} in:\n{out}");
519 }
520 assert!(out.find("\"mine\"").unwrap() < out.find(&key).unwrap());
521 let user = parse_user_widgets(&out, "widgets.json").unwrap();
522 assert_eq!((user["mine"].label.as_str(), user[&key].section.as_str()), ("M // }", "jobs"));
523 }
524
525 #[test]
526 fn adding_an_entry_works_in_every_shape_of_file() {
527 for text in [
528 "",
529 "// only a note\n",
530 "{}",
531 "{\n}\n",
532 "{\n // nothing yet\n}\n",
533 "{ \"a\": { \"label\": \"A\" }, }",
534 "{ \"a\": { \"label\": \"A\" } }",
535 "{ \"a\": { \"label\": \"A\" } /* last */ }",
536 ] {
537 let (key, out) = section_entry_in(text, "section@x", entry()).unwrap();
538 let out = out.unwrap();
539 let user = parse_user_widgets(&out, "widgets.json")
540 .unwrap_or_else(|e| panic!("{text:?} gave a file that does not parse ({}):\n{out}", e.err));
541 assert!(user.contains_key(&key), "{text:?}");
542 assert_eq!(user.len(), if text.contains("\"a\"") { 2 } else { 1 }, "{text:?}");
543 }
544 }
545
546 #[test]
547 fn a_file_that_does_not_parse_is_left_alone_by_the_writer() {
548 assert!(section_entry_in("{ \"a\": oops // note\n}", "section@x", entry()).is_err());
549 }
550
551 #[test]
552 fn a_widgets_json_error_stays_until_the_file_reads_and_does_not_clear_settings_errors() {
553 let config = ConfigState::new();
554 let settings = ConfigError { file: "C:/x/settings.json".into(), err: "bad".into(), ..Default::default() };
555 config.set_config_errors(vec![settings.clone()]);
556 let bad = parse_user_widgets("{ oops", "C:/x/widgets.json").unwrap_err();
557 assert!(config.set_widgets_config_errors(vec![bad.clone()]));
558 assert_eq!(config.get_full_config().config_errors, vec![settings.clone(), bad.clone()]);
559 config.set_config_errors(Vec::new());
561 assert_eq!(config.get_full_config().config_errors, vec![bad]);
562 config.set_config_errors(vec![settings.clone()]);
563 apply(&config, HashMap::new());
565 assert_eq!(config.get_full_config().config_errors, vec![settings]);
566 }
567}