1//! # settings_ui
2use std::{rc::Rc, sync::Arc};
3
4use editor::Editor;
5use feature_flags::{FeatureFlag, FeatureFlagAppExt as _};
6use gpui::{
7 App, AppContext as _, Context, Div, Entity, IntoElement, ReadGlobal as _, Render, Window,
8 WindowHandle, WindowOptions, actions, div, px, size,
9};
10use project::WorktreeId;
11use settings::{SettingsContent, SettingsStore};
12use std::path::Path;
13use ui::{
14 ActiveTheme as _, AnyElement, BorrowAppContext as _, Button, Clickable as _, Color,
15 FluentBuilder as _, Icon, IconName, InteractiveElement as _, Label, LabelCommon as _,
16 LabelSize, ParentElement, SharedString, StatefulInteractiveElement as _, Styled, Switch,
17 v_flex,
18};
19
20fn user_settings_data() -> Vec<SettingsPage> {
21 vec![
22 SettingsPage {
23 title: "General Page",
24 items: vec![
25 SettingsPageItem::SectionHeader("General Section"),
26 SettingsPageItem::SettingItem(SettingItem {
27 title: "Confirm Quit",
28 description: "Whether to confirm before quitting Zed",
29 render: Rc::new(|_, cx| {
30 render_toggle_button(
31 "confirm_quit",
32 SettingsFile::User,
33 cx,
34 |settings_content| &mut settings_content.workspace.confirm_quit,
35 )
36 }),
37 }),
38 SettingsPageItem::SettingItem(SettingItem {
39 title: "Auto Update",
40 description: "Automatically update Zed (may be ignored on Linux if installed through a package manager)",
41 render: Rc::new(|_, cx| {
42 render_toggle_button(
43 "Auto Update",
44 SettingsFile::User,
45 cx,
46 |settings_content| &mut settings_content.auto_update,
47 )
48 }),
49 }),
50 ],
51 },
52 SettingsPage {
53 title: "Project",
54 items: vec![
55 SettingsPageItem::SectionHeader("Worktree Settings Content"),
56 SettingsPageItem::SettingItem(SettingItem {
57 title: "Project Name",
58 description: "The displayed name of this project. If not set, the root directory name",
59 render: Rc::new(|window, cx| {
60 render_text_field(
61 "project_name",
62 SettingsFile::User,
63 window,
64 cx,
65 |settings_content| &mut settings_content.project.worktree.project_name,
66 )
67 }),
68 }),
69 ],
70 },
71 ]
72}
73
74fn project_settings_data() -> Vec<SettingsPage> {
75 vec![SettingsPage {
76 title: "Project",
77 items: vec![
78 SettingsPageItem::SectionHeader("Worktree Settings Content"),
79 SettingsPageItem::SettingItem(SettingItem {
80 title: "Project Name",
81 description: " The displayed name of this project. If not set, the root directory name",
82 render: Rc::new(|window, cx| {
83 render_text_field(
84 "project_name",
85 SettingsFile::Local((
86 WorktreeId::from_usize(0),
87 Arc::from(Path::new("TODO: actually pass through file")),
88 )),
89 window,
90 cx,
91 |settings_content| &mut settings_content.project.worktree.project_name,
92 )
93 }),
94 }),
95 ],
96 }]
97}
98
99pub struct SettingsUiFeatureFlag;
100
101impl FeatureFlag for SettingsUiFeatureFlag {
102 const NAME: &'static str = "settings-ui";
103}
104
105actions!(
106 zed,
107 [
108 /// Opens Settings Editor.
109 OpenSettingsEditor
110 ]
111);
112
113pub fn init(cx: &mut App) {
114 cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
115 workspace.register_action_renderer(|div, _, _, cx| {
116 let settings_ui_actions = [std::any::TypeId::of::<OpenSettingsEditor>()];
117 let has_flag = cx.has_flag::<SettingsUiFeatureFlag>();
118 command_palette_hooks::CommandPaletteFilter::update_global(cx, |filter, _| {
119 if has_flag {
120 filter.show_action_types(&settings_ui_actions);
121 } else {
122 filter.hide_action_types(&settings_ui_actions);
123 }
124 });
125 if has_flag {
126 div.on_action(cx.listener(|_, _: &OpenSettingsEditor, _, cx| {
127 open_settings_editor(cx).ok();
128 }))
129 } else {
130 div
131 }
132 });
133 })
134 .detach();
135}
136
137pub fn open_settings_editor(cx: &mut App) -> anyhow::Result<WindowHandle<SettingsWindow>> {
138 cx.open_window(
139 WindowOptions {
140 titlebar: None,
141 focus: true,
142 show: true,
143 kind: gpui::WindowKind::Normal,
144 window_min_size: Some(size(px(300.), px(500.))), // todo(settings_ui): Does this min_size make sense?
145 ..Default::default()
146 },
147 |window, cx| cx.new(|cx| SettingsWindow::new(window, cx)),
148 )
149}
150
151pub struct SettingsWindow {
152 files: Vec<SettingsFile>,
153 current_file: SettingsFile,
154 pages: Vec<SettingsPage>,
155 search: Entity<Editor>,
156 current_page: usize, // Index into pages - should probably be (usize, Option<usize>) for section + page
157}
158
159#[derive(Clone)]
160struct SettingsPage {
161 title: &'static str,
162 items: Vec<SettingsPageItem>,
163}
164
165#[derive(Clone)]
166enum SettingsPageItem {
167 SectionHeader(&'static str),
168 SettingItem(SettingItem),
169}
170
171impl SettingsPageItem {
172 fn render(&self, window: &mut Window, cx: &mut App) -> AnyElement {
173 match self {
174 SettingsPageItem::SectionHeader(header) => Label::new(SharedString::new_static(header))
175 .size(LabelSize::Large)
176 .into_any_element(),
177 SettingsPageItem::SettingItem(setting_item) => div()
178 .child(setting_item.title)
179 .child(setting_item.description)
180 .child((setting_item.render)(window, cx))
181 .into_any_element(),
182 }
183 }
184}
185
186impl SettingsPageItem {
187 fn _header(&self) -> Option<&'static str> {
188 match self {
189 SettingsPageItem::SectionHeader(header) => Some(header),
190 _ => None,
191 }
192 }
193}
194
195#[derive(Clone)]
196struct SettingItem {
197 title: &'static str,
198 description: &'static str,
199 render: std::rc::Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>,
200}
201
202#[allow(unused)]
203#[derive(Clone, PartialEq)]
204enum SettingsFile {
205 User, // Uses all settings.
206 Local((WorktreeId, Arc<Path>)), // Has a special name, and special set of settings
207 Server(&'static str), // Uses a special name, and the user settings
208}
209
210impl SettingsFile {
211 fn pages(&self) -> Vec<SettingsPage> {
212 match self {
213 SettingsFile::User => user_settings_data(),
214 SettingsFile::Local(_) => project_settings_data(),
215 SettingsFile::Server(_) => user_settings_data(),
216 }
217 }
218
219 fn name(&self) -> SharedString {
220 match self {
221 SettingsFile::User => SharedString::new_static("User"),
222 SettingsFile::Local((_, path)) => format!("Local ({})", path.display()).into(),
223 SettingsFile::Server(file) => format!("Server ({})", file).into(),
224 }
225 }
226}
227
228impl SettingsWindow {
229 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
230 let current_file = SettingsFile::User;
231 let search = cx.new(|cx| {
232 let mut editor = Editor::single_line(window, cx);
233 editor.set_placeholder_text("Search Settings", window, cx);
234 editor
235 });
236 let mut this = Self {
237 files: vec![],
238 current_file: current_file,
239 pages: vec![],
240 current_page: 0,
241 search,
242 };
243 cx.observe_global_in::<SettingsStore>(window, move |this, _, cx| {
244 this.fetch_files(cx);
245 cx.notify();
246 })
247 .detach();
248 this.fetch_files(cx);
249
250 this.build_ui();
251 this
252 }
253
254 fn build_ui(&mut self) {
255 self.pages = self.current_file.pages();
256 }
257
258 fn fetch_files(&mut self, cx: &mut App) {
259 let settings_store = cx.global::<SettingsStore>();
260 let mut ui_files = vec![];
261 let all_files = settings_store.get_all_files();
262 for file in all_files {
263 let settings_ui_file = match file {
264 settings::SettingsFile::User => SettingsFile::User,
265 settings::SettingsFile::Global => continue,
266 settings::SettingsFile::Extension => continue,
267 settings::SettingsFile::Server => SettingsFile::Server("todo: server name"),
268 settings::SettingsFile::Default => continue,
269 settings::SettingsFile::Local(location) => SettingsFile::Local(location),
270 };
271 ui_files.push(settings_ui_file);
272 }
273 ui_files.reverse();
274 if !ui_files.contains(&self.current_file) {
275 self.change_file(0);
276 }
277 self.files = ui_files;
278 }
279
280 fn change_file(&mut self, ix: usize) {
281 if ix >= self.files.len() {
282 self.current_file = SettingsFile::User;
283 return;
284 }
285 if self.files[ix] == self.current_file {
286 return;
287 }
288 self.current_file = self.files[ix].clone();
289 self.build_ui();
290 }
291
292 fn render_files(&self, _window: &mut Window, cx: &mut Context<SettingsWindow>) -> Div {
293 div()
294 .flex()
295 .flex_row()
296 .gap_1()
297 .children(self.files.iter().enumerate().map(|(ix, file)| {
298 Button::new(ix, file.name())
299 .on_click(cx.listener(move |this, _, _window, _cx| this.change_file(ix)))
300 }))
301 }
302
303 fn render_search(&self, _window: &mut Window, _cx: &mut App) -> Div {
304 div()
305 .child(Icon::new(IconName::MagnifyingGlass))
306 .child(self.search.clone())
307 }
308
309 fn render_nav(&self, window: &mut Window, cx: &mut Context<SettingsWindow>) -> Div {
310 let mut nav = v_flex()
311 .p_4()
312 .gap_2()
313 .child(div().h_10()) // Files spacer;
314 .child(self.render_search(window, cx));
315
316 for (ix, page) in self.pages.iter().enumerate() {
317 nav = nav.child(
318 div()
319 .id(page.title)
320 .child(
321 Label::new(page.title)
322 .size(LabelSize::Large)
323 .when(self.is_page_selected(ix), |this| {
324 this.color(Color::Selected)
325 }),
326 )
327 .on_click(cx.listener(move |this, _, _, cx| {
328 this.current_page = ix;
329 cx.notify();
330 })),
331 );
332 }
333 nav
334 }
335
336 fn render_page(
337 &self,
338 page: &SettingsPage,
339 window: &mut Window,
340 cx: &mut Context<SettingsWindow>,
341 ) -> Div {
342 div()
343 .child(self.render_files(window, cx))
344 .child(Label::new(page.title))
345 .children(page.items.iter().map(|item| item.render(window, cx)))
346 }
347
348 fn current_page(&self) -> &SettingsPage {
349 &self.pages[self.current_page]
350 }
351
352 fn is_page_selected(&self, ix: usize) -> bool {
353 ix == self.current_page
354 }
355}
356
357impl Render for SettingsWindow {
358 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
359 div()
360 .size_full()
361 .bg(cx.theme().colors().background)
362 .flex()
363 .flex_row()
364 .text_color(cx.theme().colors().text)
365 .child(self.render_nav(window, cx).w(px(300.0)))
366 .child(self.render_page(self.current_page(), window, cx).w_full())
367 }
368}
369
370fn write_setting_value<T: Send + 'static>(
371 get_value: fn(&mut SettingsContent) -> &mut Option<T>,
372 value: Option<T>,
373 cx: &mut App,
374) {
375 cx.update_global(|store: &mut SettingsStore, cx| {
376 store.update_settings_file(<dyn fs::Fs>::global(cx), move |settings, _cx| {
377 *get_value(settings) = value;
378 });
379 });
380}
381
382fn render_text_field(
383 id: &'static str,
384 _file: SettingsFile,
385 window: &mut Window,
386 cx: &mut App,
387 get_value: fn(&mut SettingsContent) -> &mut Option<String>,
388) -> AnyElement {
389 // TODO: Updating file does not cause the editor text to reload, suspicious it may be a missing global update/notify in SettingsStore
390
391 // TODO: in settings window state
392 let store = SettingsStore::global(cx);
393
394 // TODO: This clone needs to go!!
395 let mut defaults = store.raw_default_settings().clone();
396 let mut user_settings = store
397 .raw_user_settings()
398 .cloned()
399 .unwrap_or_default()
400 .content;
401
402 // TODO: unwrap_or_default here because project name is null
403 let initial_text = get_value(user_settings.as_mut())
404 .clone()
405 .unwrap_or_else(|| get_value(&mut defaults).clone().unwrap_or_default());
406
407 let editor = window.use_keyed_state((id.into(), initial_text.clone()), cx, {
408 move |window, cx| {
409 let mut editor = Editor::single_line(window, cx);
410 editor.set_text(initial_text, window, cx);
411 editor
412 }
413 });
414
415 let weak_editor = editor.downgrade();
416 let theme_colors = cx.theme().colors();
417
418 div()
419 .child(editor)
420 .bg(theme_colors.editor_background)
421 .border_1()
422 .rounded_lg()
423 .border_color(theme_colors.border)
424 .on_action::<menu::Confirm>({
425 move |_, _, cx| {
426 let Some(editor) = weak_editor.upgrade() else {
427 return;
428 };
429 let new_value = editor.read_with(cx, |editor, cx| editor.text(cx));
430 let new_value = (!new_value.is_empty()).then_some(new_value);
431 write_setting_value(get_value, new_value, cx);
432 editor.update(cx, |_, cx| {
433 cx.notify();
434 });
435 }
436 })
437 .into_any_element()
438}
439
440fn render_toggle_button(
441 id: &'static str,
442 _: SettingsFile,
443 cx: &mut App,
444 get_value: fn(&mut SettingsContent) -> &mut Option<bool>,
445) -> AnyElement {
446 // TODO: in settings window state
447 let store = SettingsStore::global(cx);
448
449 // TODO: This clone needs to go!!
450 let mut defaults = store.raw_default_settings().clone();
451 let mut user_settings = store
452 .raw_user_settings()
453 .cloned()
454 .unwrap_or_default()
455 .content;
456
457 let toggle_state =
458 if get_value(&mut user_settings).unwrap_or_else(|| get_value(&mut defaults).unwrap()) {
459 ui::ToggleState::Selected
460 } else {
461 ui::ToggleState::Unselected
462 };
463
464 Switch::new(id, toggle_state)
465 .on_click({
466 move |state, _window, cx| {
467 write_setting_value(get_value, Some(*state == ui::ToggleState::Selected), cx);
468 }
469 })
470 .into_any_element()
471}