1use crate::{settings_store::SettingsStore, Settings};
2use anyhow::Result;
3use fs::Fs;
4use futures::{channel::mpsc, StreamExt};
5use gpui::{AppContext, BackgroundExecutor, ReadGlobal, UpdateGlobal};
6use std::{path::PathBuf, sync::Arc, time::Duration};
7use util::ResultExt;
8
9pub const EMPTY_THEME_NAME: &str = "empty-theme";
10
11#[cfg(any(test, feature = "test-support"))]
12pub fn test_settings() -> String {
13 let mut value = crate::settings_store::parse_json_with_comments::<serde_json::Value>(
14 crate::default_settings().as_ref(),
15 )
16 .unwrap();
17 util::merge_non_null_json_value_into(
18 serde_json::json!({
19 "ui_font_family": "Courier",
20 "ui_font_features": {},
21 "ui_font_size": 14,
22 "ui_font_fallback": [],
23 "buffer_font_family": "Courier",
24 "buffer_font_features": {},
25 "buffer_font_size": 14,
26 "buffer_font_fallback": [],
27 "theme": EMPTY_THEME_NAME,
28 }),
29 &mut value,
30 );
31 value.as_object_mut().unwrap().remove("languages");
32 serde_json::to_string(&value).unwrap()
33}
34
35pub fn watch_config_file(
36 executor: &BackgroundExecutor,
37 fs: Arc<dyn Fs>,
38 path: PathBuf,
39) -> mpsc::UnboundedReceiver<String> {
40 let (tx, rx) = mpsc::unbounded();
41 executor
42 .spawn(async move {
43 let (events, _) = fs.watch(&path, Duration::from_millis(100)).await;
44 futures::pin_mut!(events);
45
46 let contents = fs.load(&path).await.unwrap_or_default();
47 if tx.unbounded_send(contents).is_err() {
48 return;
49 }
50
51 loop {
52 if events.next().await.is_none() {
53 break;
54 }
55
56 if let Ok(contents) = fs.load(&path).await {
57 if tx.unbounded_send(contents).is_err() {
58 break;
59 }
60 }
61 }
62 })
63 .detach();
64 rx
65}
66
67pub fn handle_settings_file_changes(
68 mut user_settings_file_rx: mpsc::UnboundedReceiver<String>,
69 cx: &mut AppContext,
70 settings_changed: impl Fn(Result<()>, &mut AppContext) + 'static,
71) {
72 let user_settings_content = cx
73 .background_executor()
74 .block(user_settings_file_rx.next())
75 .unwrap();
76 SettingsStore::update_global(cx, |store, cx| {
77 store
78 .set_user_settings(&user_settings_content, cx)
79 .log_err();
80 });
81 cx.spawn(move |mut cx| async move {
82 while let Some(user_settings_content) = user_settings_file_rx.next().await {
83 let result = cx.update_global(|store: &mut SettingsStore, cx| {
84 let result = store.set_user_settings(&user_settings_content, cx);
85 if let Err(err) = &result {
86 log::error!("Failed to load user settings: {err}");
87 }
88 settings_changed(result, cx);
89 cx.refresh();
90 });
91 if result.is_err() {
92 break; // App dropped
93 }
94 }
95 })
96 .detach();
97}
98
99pub fn update_settings_file<T: Settings>(
100 fs: Arc<dyn Fs>,
101 cx: &AppContext,
102 update: impl 'static + Send + FnOnce(&mut T::FileContent, &AppContext),
103) {
104 SettingsStore::global(cx).update_settings_file::<T>(fs, update);
105}