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 "buffer_font_size": 14,
46 "theme": theme::EMPTY_THEME_NAME,
47 }),
48 &mut value,
49 );
50 value.as_object_mut().unwrap().remove("languages");
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 new_text = cx.read(|cx| {
176 cx.global::<SettingsStore>()
177 .new_text_for_update::<T>(old_text, update)
178 });
179
180 cx.background()
181 .spawn(async move { fs.atomic_write(paths::SETTINGS.clone(), new_text).await })
182 .await?;
183 anyhow::Ok(())
184 })
185 .detach_and_log_err(cx);
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191 use fs::FakeFs;
192 use gpui::{actions, elements::*, Action, Entity, TestAppContext, View, ViewContext};
193 use theme::ThemeRegistry;
194
195 struct TestView;
196
197 impl Entity for TestView {
198 type Event = ();
199 }
200
201 impl View for TestView {
202 fn ui_name() -> &'static str {
203 "TestView"
204 }
205
206 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
207 Empty::new().into_any()
208 }
209 }
210
211 #[gpui::test]
212 async fn test_base_keymap(cx: &mut gpui::TestAppContext) {
213 let executor = cx.background();
214 let fs = FakeFs::new(executor.clone());
215
216 actions!(test, [A, B]);
217 // From the Atom keymap
218 actions!(workspace, [ActivatePreviousPane]);
219 // From the JetBrains keymap
220 actions!(pane, [ActivatePrevItem]);
221
222 fs.save(
223 "/settings.json".as_ref(),
224 &r#"
225 {
226 "base_keymap": "Atom"
227 }
228 "#
229 .into(),
230 Default::default(),
231 )
232 .await
233 .unwrap();
234
235 fs.save(
236 "/keymap.json".as_ref(),
237 &r#"
238 [
239 {
240 "bindings": {
241 "backspace": "test::A"
242 }
243 }
244 ]
245 "#
246 .into(),
247 Default::default(),
248 )
249 .await
250 .unwrap();
251
252 cx.update(|cx| {
253 let mut store = SettingsStore::default();
254 store.set_default_settings(&test_settings(), cx).unwrap();
255 cx.set_global(store);
256 cx.set_global(ThemeRegistry::new(Assets, cx.font_cache().clone()));
257 cx.add_global_action(|_: &A, _cx| {});
258 cx.add_global_action(|_: &B, _cx| {});
259 cx.add_global_action(|_: &ActivatePreviousPane, _cx| {});
260 cx.add_global_action(|_: &ActivatePrevItem, _cx| {});
261
262 let settings_rx = watch_config_file(
263 executor.clone(),
264 fs.clone(),
265 PathBuf::from("/settings.json"),
266 );
267 let keymap_rx =
268 watch_config_file(executor.clone(), fs.clone(), PathBuf::from("/keymap.json"));
269
270 handle_keymap_file_changes(keymap_rx, cx);
271 handle_settings_file_changes(settings_rx, cx);
272 });
273
274 cx.foreground().run_until_parked();
275
276 let (window_id, _view) = cx.add_window(|_| TestView);
277
278 // Test loading the keymap base at all
279 assert_key_bindings_for(
280 window_id,
281 cx,
282 vec![("backspace", &A), ("k", &ActivatePreviousPane)],
283 line!(),
284 );
285
286 // Test modifying the users keymap, while retaining the base keymap
287 fs.save(
288 "/keymap.json".as_ref(),
289 &r#"
290 [
291 {
292 "bindings": {
293 "backspace": "test::B"
294 }
295 }
296 ]
297 "#
298 .into(),
299 Default::default(),
300 )
301 .await
302 .unwrap();
303
304 cx.foreground().run_until_parked();
305
306 assert_key_bindings_for(
307 window_id,
308 cx,
309 vec![("backspace", &B), ("k", &ActivatePreviousPane)],
310 line!(),
311 );
312
313 // Test modifying the base, while retaining the users keymap
314 fs.save(
315 "/settings.json".as_ref(),
316 &r#"
317 {
318 "base_keymap": "JetBrains"
319 }
320 "#
321 .into(),
322 Default::default(),
323 )
324 .await
325 .unwrap();
326
327 cx.foreground().run_until_parked();
328
329 assert_key_bindings_for(
330 window_id,
331 cx,
332 vec![("backspace", &B), ("[", &ActivatePrevItem)],
333 line!(),
334 );
335 }
336
337 fn assert_key_bindings_for<'a>(
338 window_id: usize,
339 cx: &TestAppContext,
340 actions: Vec<(&'static str, &'a dyn Action)>,
341 line: u32,
342 ) {
343 for (key, action) in actions {
344 // assert that...
345 assert!(
346 cx.available_actions(window_id, 0)
347 .into_iter()
348 .any(|(_, bound_action, b)| {
349 // action names match...
350 bound_action.name() == action.name()
351 && bound_action.namespace() == action.namespace()
352 // and key strokes contain the given key
353 && b.iter()
354 .any(|binding| binding.keystrokes().iter().any(|k| k.key == key))
355 }),
356 "On {} Failed to find {} with key binding {}",
357 line,
358 action.name(),
359 key
360 );
361 }
362 }
363}