1use crate::{
2 settings_store::parse_json_with_comments, settings_store::SettingsStore, KeymapFileContent,
3 Setting, Settings, DEFAULT_SETTINGS_ASSET_PATH,
4};
5use anyhow::Result;
6use assets::Assets;
7use fs::Fs;
8use futures::{channel::mpsc, StreamExt};
9use gpui::{executor::Background, AppContext, AssetSource};
10use std::{
11 borrow::Cow,
12 io::ErrorKind,
13 path::{Path, PathBuf},
14 str,
15 sync::Arc,
16 time::Duration,
17};
18use util::{paths, ResultExt};
19
20pub fn register_setting<T: Setting>(cx: &mut AppContext) {
21 cx.update_global::<SettingsStore, _, _>(|store, cx| {
22 store.register_setting::<T>(cx);
23 });
24}
25
26pub fn get_setting<'a, T: Setting>(path: Option<&Path>, cx: &'a AppContext) -> &'a T {
27 cx.global::<SettingsStore>().get(path)
28}
29
30pub fn default_settings() -> Cow<'static, str> {
31 match Assets.load(DEFAULT_SETTINGS_ASSET_PATH).unwrap() {
32 Cow::Borrowed(s) => Cow::Borrowed(str::from_utf8(s).unwrap()),
33 Cow::Owned(s) => Cow::Owned(String::from_utf8(s).unwrap()),
34 }
35}
36
37#[cfg(any(test, feature = "test-support"))]
38pub fn test_settings() -> String {
39 let mut value =
40 parse_json_with_comments::<serde_json::Value>(default_settings().as_ref()).unwrap();
41 util::merge_non_null_json_value_into(
42 serde_json::json!({
43 "buffer_font_family": "Courier",
44 "buffer_font_features": {},
45 "default_buffer_font_size": 14,
46 "preferred_line_length": 80,
47 "theme": theme::EMPTY_THEME_NAME,
48 }),
49 &mut value,
50 );
51 serde_json::to_string(&value).unwrap()
52}
53
54pub fn watch_config_file(
55 executor: Arc<Background>,
56 fs: Arc<dyn Fs>,
57 path: PathBuf,
58) -> mpsc::UnboundedReceiver<String> {
59 let (tx, rx) = mpsc::unbounded();
60 executor
61 .spawn(async move {
62 let events = fs.watch(&path, Duration::from_millis(100)).await;
63 futures::pin_mut!(events);
64 loop {
65 if let Ok(contents) = fs.load(&path).await {
66 if !tx.unbounded_send(contents).is_ok() {
67 break;
68 }
69 }
70 if events.next().await.is_none() {
71 break;
72 }
73 }
74 })
75 .detach();
76 rx
77}
78
79pub fn handle_keymap_file_changes(
80 mut user_keymap_file_rx: mpsc::UnboundedReceiver<String>,
81 cx: &mut AppContext,
82) {
83 cx.spawn(move |mut cx| async move {
84 let mut settings_subscription = None;
85 while let Some(user_keymap_content) = user_keymap_file_rx.next().await {
86 if let Ok(keymap_content) =
87 parse_json_with_comments::<KeymapFileContent>(&user_keymap_content)
88 {
89 cx.update(|cx| {
90 cx.clear_bindings();
91 KeymapFileContent::load_defaults(cx);
92 keymap_content.clone().add_to_cx(cx).log_err();
93 });
94
95 let mut old_base_keymap = cx.read(|cx| cx.global::<Settings>().base_keymap.clone());
96 drop(settings_subscription);
97 settings_subscription = Some(cx.update(|cx| {
98 cx.observe_global::<Settings, _>(move |cx| {
99 let settings = cx.global::<Settings>();
100 if settings.base_keymap != old_base_keymap {
101 old_base_keymap = settings.base_keymap.clone();
102
103 cx.clear_bindings();
104 KeymapFileContent::load_defaults(cx);
105 keymap_content.clone().add_to_cx(cx).log_err();
106 }
107 })
108 .detach();
109 }));
110 }
111 }
112 })
113 .detach();
114}
115
116pub fn handle_settings_file_changes(
117 mut user_settings_file_rx: mpsc::UnboundedReceiver<String>,
118 cx: &mut AppContext,
119) {
120 let user_settings_content = cx.background().block(user_settings_file_rx.next()).unwrap();
121 cx.update_global::<SettingsStore, _, _>(|store, cx| {
122 store
123 .set_user_settings(&user_settings_content, cx)
124 .log_err();
125
126 // TODO - remove the Settings global, use the SettingsStore instead.
127 store.register_setting::<Settings>(cx);
128 cx.set_global(store.get::<Settings>(None).clone());
129 });
130 cx.spawn(move |mut cx| async move {
131 while let Some(user_settings_content) = user_settings_file_rx.next().await {
132 cx.update(|cx| {
133 cx.update_global::<SettingsStore, _, _>(|store, cx| {
134 store
135 .set_user_settings(&user_settings_content, cx)
136 .log_err();
137
138 // TODO - remove the Settings global, use the SettingsStore instead.
139 cx.set_global(store.get::<Settings>(None).clone());
140 });
141 });
142 }
143 })
144 .detach();
145}
146
147async fn load_settings(fs: &Arc<dyn Fs>) -> Result<String> {
148 match fs.load(&paths::SETTINGS).await {
149 result @ Ok(_) => result,
150 Err(err) => {
151 if let Some(e) = err.downcast_ref::<std::io::Error>() {
152 if e.kind() == ErrorKind::NotFound {
153 return Ok(Settings::initial_user_settings_content(&Assets).to_string());
154 }
155 }
156 return Err(err);
157 }
158 }
159}
160
161pub fn update_settings_file<T: Setting>(
162 fs: Arc<dyn Fs>,
163 cx: &mut AppContext,
164 update: impl 'static + Send + FnOnce(&mut T::FileContent),
165) {
166 cx.spawn(|cx| async move {
167 let old_text = cx
168 .background()
169 .spawn({
170 let fs = fs.clone();
171 async move { load_settings(&fs).await }
172 })
173 .await?;
174
175 let edits = cx.read(|cx| cx.global::<SettingsStore>().update::<T>(&old_text, update));
176
177 let mut new_text = old_text;
178 for (range, replacement) in edits.into_iter().rev() {
179 new_text.replace_range(range, &replacement);
180 }
181
182 cx.background()
183 .spawn(async move { fs.atomic_write(paths::SETTINGS.clone(), new_text).await })
184 .await?;
185 anyhow::Ok(())
186 })
187 .detach_and_log_err(cx);
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193 use fs::FakeFs;
194 use gpui::{actions, elements::*, Action, Entity, TestAppContext, View, ViewContext};
195 use theme::ThemeRegistry;
196
197 struct TestView;
198
199 impl Entity for TestView {
200 type Event = ();
201 }
202
203 impl View for TestView {
204 fn ui_name() -> &'static str {
205 "TestView"
206 }
207
208 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
209 Empty::new().into_any()
210 }
211 }
212
213 #[gpui::test]
214 async fn test_base_keymap(cx: &mut gpui::TestAppContext) {
215 let executor = cx.background();
216 let fs = FakeFs::new(executor.clone());
217
218 actions!(test, [A, B]);
219 // From the Atom keymap
220 actions!(workspace, [ActivatePreviousPane]);
221 // From the JetBrains keymap
222 actions!(pane, [ActivatePrevItem]);
223
224 fs.save(
225 "/settings.json".as_ref(),
226 &r#"
227 {
228 "base_keymap": "Atom"
229 }
230 "#
231 .into(),
232 Default::default(),
233 )
234 .await
235 .unwrap();
236
237 fs.save(
238 "/keymap.json".as_ref(),
239 &r#"
240 [
241 {
242 "bindings": {
243 "backspace": "test::A"
244 }
245 }
246 ]
247 "#
248 .into(),
249 Default::default(),
250 )
251 .await
252 .unwrap();
253
254 cx.update(|cx| {
255 let mut store = SettingsStore::default();
256 store.set_default_settings(&test_settings(), cx).unwrap();
257 cx.set_global(store);
258 cx.set_global(ThemeRegistry::new(Assets, cx.font_cache().clone()));
259 cx.add_global_action(|_: &A, _cx| {});
260 cx.add_global_action(|_: &B, _cx| {});
261 cx.add_global_action(|_: &ActivatePreviousPane, _cx| {});
262 cx.add_global_action(|_: &ActivatePrevItem, _cx| {});
263
264 let settings_rx = watch_config_file(
265 executor.clone(),
266 fs.clone(),
267 PathBuf::from("/settings.json"),
268 );
269 let keymap_rx =
270 watch_config_file(executor.clone(), fs.clone(), PathBuf::from("/keymap.json"));
271
272 handle_keymap_file_changes(keymap_rx, cx);
273 handle_settings_file_changes(settings_rx, cx);
274 });
275
276 cx.foreground().run_until_parked();
277
278 let (window_id, _view) = cx.add_window(|_| TestView);
279
280 // Test loading the keymap base at all
281 assert_key_bindings_for(
282 window_id,
283 cx,
284 vec![("backspace", &A), ("k", &ActivatePreviousPane)],
285 line!(),
286 );
287
288 // Test modifying the users keymap, while retaining the base keymap
289 fs.save(
290 "/keymap.json".as_ref(),
291 &r#"
292 [
293 {
294 "bindings": {
295 "backspace": "test::B"
296 }
297 }
298 ]
299 "#
300 .into(),
301 Default::default(),
302 )
303 .await
304 .unwrap();
305
306 cx.foreground().run_until_parked();
307
308 assert_key_bindings_for(
309 window_id,
310 cx,
311 vec![("backspace", &B), ("k", &ActivatePreviousPane)],
312 line!(),
313 );
314
315 // Test modifying the base, while retaining the users keymap
316 fs.save(
317 "/settings.json".as_ref(),
318 &r#"
319 {
320 "base_keymap": "JetBrains"
321 }
322 "#
323 .into(),
324 Default::default(),
325 )
326 .await
327 .unwrap();
328
329 cx.foreground().run_until_parked();
330
331 assert_key_bindings_for(
332 window_id,
333 cx,
334 vec![("backspace", &B), ("[", &ActivatePrevItem)],
335 line!(),
336 );
337 }
338
339 fn assert_key_bindings_for<'a>(
340 window_id: usize,
341 cx: &TestAppContext,
342 actions: Vec<(&'static str, &'a dyn Action)>,
343 line: u32,
344 ) {
345 for (key, action) in actions {
346 // assert that...
347 assert!(
348 cx.available_actions(window_id, 0)
349 .into_iter()
350 .any(|(_, bound_action, b)| {
351 // action names match...
352 bound_action.name() == action.name()
353 && bound_action.namespace() == action.namespace()
354 // and key strokes contain the given key
355 && b.iter()
356 .any(|binding| binding.keystrokes().iter().any(|k| k.key == key))
357 }),
358 "On {} Failed to find {} with key binding {}",
359 line,
360 action.name(),
361 key
362 );
363 }
364 }
365}