settings_file.rs

  1use crate::{settings_store::SettingsStore, Setting, DEFAULT_SETTINGS_ASSET_PATH};
  2use anyhow::Result;
  3use assets::Assets;
  4use fs::Fs;
  5use futures::{channel::mpsc, StreamExt};
  6use gpui::{executor::Background, AppContext, AssetSource};
  7use std::{
  8    borrow::Cow,
  9    io::ErrorKind,
 10    path::{Path, PathBuf},
 11    str,
 12    sync::Arc,
 13    time::Duration,
 14};
 15use util::{paths, ResultExt};
 16
 17pub fn register<T: Setting>(cx: &mut AppContext) {
 18    cx.update_global::<SettingsStore, _, _>(|store, cx| {
 19        store.register_setting::<T>(cx);
 20    });
 21}
 22
 23pub fn get<'a, T: Setting>(cx: &'a AppContext) -> &'a T {
 24    cx.global::<SettingsStore>().get(None)
 25}
 26
 27pub fn get_local<'a, T: Setting>(location: Option<(usize, &Path)>, cx: &'a AppContext) -> &'a T {
 28    cx.global::<SettingsStore>().get(location)
 29}
 30
 31pub fn default_settings() -> Cow<'static, str> {
 32    match Assets.load(DEFAULT_SETTINGS_ASSET_PATH).unwrap() {
 33        Cow::Borrowed(s) => Cow::Borrowed(str::from_utf8(s).unwrap()),
 34        Cow::Owned(s) => Cow::Owned(String::from_utf8(s).unwrap()),
 35    }
 36}
 37
 38pub const EMPTY_THEME_NAME: &'static str = "empty-theme";
 39
 40#[cfg(any(test, feature = "test-support"))]
 41pub fn test_settings() -> String {
 42    let mut value = crate::settings_store::parse_json_with_comments::<serde_json::Value>(
 43        default_settings().as_ref(),
 44    )
 45    .unwrap();
 46    util::merge_non_null_json_value_into(
 47        serde_json::json!({
 48            "buffer_font_family": "Courier",
 49            "buffer_font_features": {},
 50            "buffer_font_size": 14,
 51            "theme": EMPTY_THEME_NAME,
 52        }),
 53        &mut value,
 54    );
 55    value.as_object_mut().unwrap().remove("languages");
 56    serde_json::to_string(&value).unwrap()
 57}
 58
 59pub fn watch_config_file(
 60    executor: Arc<Background>,
 61    fs: Arc<dyn Fs>,
 62    path: PathBuf,
 63) -> mpsc::UnboundedReceiver<String> {
 64    let (tx, rx) = mpsc::unbounded();
 65    executor
 66        .spawn(async move {
 67            let events = fs.watch(&path, Duration::from_millis(100)).await;
 68            futures::pin_mut!(events);
 69            loop {
 70                if let Ok(contents) = fs.load(&path).await {
 71                    if !tx.unbounded_send(contents).is_ok() {
 72                        break;
 73                    }
 74                }
 75                if events.next().await.is_none() {
 76                    break;
 77                }
 78            }
 79        })
 80        .detach();
 81    rx
 82}
 83
 84pub fn handle_settings_file_changes(
 85    mut user_settings_file_rx: mpsc::UnboundedReceiver<String>,
 86    cx: &mut AppContext,
 87) {
 88    let user_settings_content = cx.background().block(user_settings_file_rx.next()).unwrap();
 89    cx.update_global::<SettingsStore, _, _>(|store, cx| {
 90        store
 91            .set_user_settings(&user_settings_content, cx)
 92            .log_err();
 93    });
 94    cx.spawn(move |mut cx| async move {
 95        while let Some(user_settings_content) = user_settings_file_rx.next().await {
 96            cx.update(|cx| {
 97                cx.update_global::<SettingsStore, _, _>(|store, cx| {
 98                    store
 99                        .set_user_settings(&user_settings_content, cx)
100                        .log_err();
101                });
102                cx.refresh_windows();
103            });
104        }
105    })
106    .detach();
107}
108
109async fn load_settings(fs: &Arc<dyn Fs>) -> Result<String> {
110    match fs.load(&paths::SETTINGS).await {
111        result @ Ok(_) => result,
112        Err(err) => {
113            if let Some(e) = err.downcast_ref::<std::io::Error>() {
114                if e.kind() == ErrorKind::NotFound {
115                    return Ok(crate::initial_user_settings_content(&Assets).to_string());
116                }
117            }
118            return Err(err);
119        }
120    }
121}
122
123pub fn update_settings_file<T: Setting>(
124    fs: Arc<dyn Fs>,
125    cx: &mut AppContext,
126    update: impl 'static + Send + FnOnce(&mut T::FileContent),
127) {
128    cx.spawn(|cx| async move {
129        let old_text = cx
130            .background()
131            .spawn({
132                let fs = fs.clone();
133                async move { load_settings(&fs).await }
134            })
135            .await?;
136
137        let new_text = cx.read(|cx| {
138            cx.global::<SettingsStore>()
139                .new_text_for_update::<T>(old_text, update)
140        });
141
142        cx.background()
143            .spawn(async move { fs.atomic_write(paths::SETTINGS.clone(), new_text).await })
144            .await?;
145        anyhow::Ok(())
146    })
147    .detach_and_log_err(cx);
148}