1//! # settings_ui
2mod components;
3mod page_data;
4
5use anyhow::Result;
6use editor::{Editor, EditorEvent};
7use feature_flags::{FeatureFlag, FeatureFlagAppExt as _};
8use fuzzy::StringMatchCandidate;
9use gpui::{
10 App, Div, Entity, Focusable, FontWeight, Global, ReadGlobal as _, ScrollHandle, Task,
11 TitlebarOptions, UniformListScrollHandle, Window, WindowHandle, WindowOptions, div, point,
12 prelude::*, px, size, uniform_list,
13};
14use project::WorktreeId;
15use settings::{
16 BottomDockLayout, CloseWindowWhenNoItems, CodeFade, CursorShape, OnLastWindowClosed,
17 RestoreOnStartupBehavior, SaturatingBool, SettingsContent, SettingsStore,
18};
19use std::{
20 any::{Any, TypeId, type_name},
21 cell::RefCell,
22 collections::HashMap,
23 num::NonZeroU32,
24 ops::Range,
25 rc::Rc,
26 sync::{Arc, LazyLock, RwLock, atomic::AtomicBool},
27};
28use ui::{
29 ButtonLike, ContextMenu, Divider, DropdownMenu, DropdownStyle, IconButtonShape, PopoverMenu,
30 Switch, SwitchColor, TreeViewItem, WithScrollbar, prelude::*,
31};
32use ui_input::{NumericStepper, NumericStepperStyle, NumericStepperType};
33use util::{ResultExt as _, paths::PathStyle, rel_path::RelPath};
34use zed_actions::OpenSettingsEditor;
35
36use crate::components::SettingsEditor;
37
38#[derive(Clone, Copy)]
39struct SettingField<T: 'static> {
40 pick: fn(&SettingsContent) -> &Option<T>,
41 pick_mut: fn(&mut SettingsContent) -> &mut Option<T>,
42}
43
44/// Helper for unimplemented settings, used in combination with `SettingField::unimplemented`
45/// to keep the setting around in the UI with valid pick and pick_mut implementations, but don't actually try to render it.
46/// TODO(settings_ui): In non-dev builds (`#[cfg(not(debug_assertions))]`) make this render as edit-in-json
47struct UnimplementedSettingField;
48
49impl<T: 'static> SettingField<T> {
50 /// Helper for settings with types that are not yet implemented.
51 #[allow(unused)]
52 fn unimplemented(self) -> SettingField<UnimplementedSettingField> {
53 SettingField {
54 pick: |_| &None,
55 pick_mut: |_| unreachable!(),
56 }
57 }
58}
59
60trait AnySettingField {
61 fn as_any(&self) -> &dyn Any;
62 fn type_name(&self) -> &'static str;
63 fn type_id(&self) -> TypeId;
64 fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> settings::SettingsFile;
65}
66
67impl<T> AnySettingField for SettingField<T> {
68 fn as_any(&self) -> &dyn Any {
69 self
70 }
71
72 fn type_name(&self) -> &'static str {
73 type_name::<T>()
74 }
75
76 fn type_id(&self) -> TypeId {
77 TypeId::of::<T>()
78 }
79
80 fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> settings::SettingsFile {
81 if AnySettingField::type_id(self) == TypeId::of::<UnimplementedSettingField>() {
82 return file.to_settings();
83 }
84
85 let (file, _) = cx
86 .global::<SettingsStore>()
87 .get_value_from_file(file.to_settings(), self.pick);
88 return file;
89 }
90}
91
92#[derive(Default, Clone)]
93struct SettingFieldRenderer {
94 renderers: Rc<
95 RefCell<
96 HashMap<
97 TypeId,
98 Box<
99 dyn Fn(
100 &dyn AnySettingField,
101 SettingsUiFile,
102 Option<&SettingsFieldMetadata>,
103 &mut Window,
104 &mut App,
105 ) -> AnyElement,
106 >,
107 >,
108 >,
109 >,
110}
111
112impl Global for SettingFieldRenderer {}
113
114impl SettingFieldRenderer {
115 fn add_renderer<T: 'static>(
116 &mut self,
117 renderer: impl Fn(
118 &SettingField<T>,
119 SettingsUiFile,
120 Option<&SettingsFieldMetadata>,
121 &mut Window,
122 &mut App,
123 ) -> AnyElement
124 + 'static,
125 ) -> &mut Self {
126 let key = TypeId::of::<T>();
127 let renderer = Box::new(
128 move |any_setting_field: &dyn AnySettingField,
129 settings_file: SettingsUiFile,
130 metadata: Option<&SettingsFieldMetadata>,
131 window: &mut Window,
132 cx: &mut App| {
133 let field = any_setting_field
134 .as_any()
135 .downcast_ref::<SettingField<T>>()
136 .unwrap();
137 renderer(field, settings_file, metadata, window, cx)
138 },
139 );
140 self.renderers.borrow_mut().insert(key, renderer);
141 self
142 }
143
144 fn render(
145 &self,
146 any_setting_field: &dyn AnySettingField,
147 settings_file: SettingsUiFile,
148 metadata: Option<&SettingsFieldMetadata>,
149 window: &mut Window,
150 cx: &mut App,
151 ) -> AnyElement {
152 let key = any_setting_field.type_id();
153 if let Some(renderer) = self.renderers.borrow().get(&key) {
154 renderer(any_setting_field, settings_file, metadata, window, cx)
155 } else {
156 panic!(
157 "No renderer found for type: {}",
158 any_setting_field.type_name()
159 )
160 }
161 }
162}
163
164struct SettingsFieldMetadata {
165 placeholder: Option<&'static str>,
166}
167
168pub struct SettingsUiFeatureFlag;
169
170impl FeatureFlag for SettingsUiFeatureFlag {
171 const NAME: &'static str = "settings-ui";
172}
173
174pub fn init(cx: &mut App) {
175 init_renderers(cx);
176
177 cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
178 workspace.register_action_renderer(|div, _, _, cx| {
179 let settings_ui_actions = [std::any::TypeId::of::<OpenSettingsEditor>()];
180 let has_flag = cx.has_flag::<SettingsUiFeatureFlag>();
181 command_palette_hooks::CommandPaletteFilter::update_global(cx, |filter, _| {
182 if has_flag {
183 filter.show_action_types(&settings_ui_actions);
184 } else {
185 filter.hide_action_types(&settings_ui_actions);
186 }
187 });
188 if has_flag {
189 div.on_action(cx.listener(|_, _: &OpenSettingsEditor, _, cx| {
190 open_settings_editor(cx).ok();
191 }))
192 } else {
193 div
194 }
195 });
196 })
197 .detach();
198}
199
200fn init_renderers(cx: &mut App) {
201 // fn (field: SettingsField, current_file: SettingsFile, cx) -> (currently_set_in: SettingsFile, overridden_in: Vec<SettingsFile>)
202 cx.default_global::<SettingFieldRenderer>()
203 .add_renderer::<UnimplementedSettingField>(|_, _, _, _, _| {
204 // TODO(settings_ui): In non-dev builds (`#[cfg(not(debug_assertions))]`) make this render as edit-in-json
205 Button::new("unimplemented-field", "UNIMPLEMENTED")
206 .size(ButtonSize::Medium)
207 .icon(IconName::XCircle)
208 .icon_position(IconPosition::Start)
209 .icon_color(Color::Error)
210 .icon_size(IconSize::Small)
211 .style(ButtonStyle::Outlined)
212 .into_any_element()
213 })
214 .add_renderer::<bool>(|settings_field, file, _, _, cx| {
215 render_toggle_button(*settings_field, file, cx).into_any_element()
216 })
217 .add_renderer::<String>(|settings_field, file, metadata, _, cx| {
218 render_text_field(settings_field.clone(), file, metadata, cx)
219 })
220 .add_renderer::<SaturatingBool>(|settings_field, file, _, _, cx| {
221 render_toggle_button(*settings_field, file, cx)
222 })
223 .add_renderer::<CursorShape>(|settings_field, file, _, window, cx| {
224 render_dropdown(*settings_field, file, window, cx)
225 })
226 .add_renderer::<RestoreOnStartupBehavior>(|settings_field, file, _, window, cx| {
227 render_dropdown(*settings_field, file, window, cx)
228 })
229 .add_renderer::<BottomDockLayout>(|settings_field, file, _, window, cx| {
230 render_dropdown(*settings_field, file, window, cx)
231 })
232 .add_renderer::<OnLastWindowClosed>(|settings_field, file, _, window, cx| {
233 render_dropdown(*settings_field, file, window, cx)
234 })
235 .add_renderer::<CloseWindowWhenNoItems>(|settings_field, file, _, window, cx| {
236 render_dropdown(*settings_field, file, window, cx)
237 })
238 .add_renderer::<settings::FontFamilyName>(|settings_field, file, _, window, cx| {
239 // todo(settings_ui): We need to pass in a validator for this to ensure that users that type in invalid font names
240 render_font_picker(settings_field.clone(), file, window, cx)
241 })
242 // todo(settings_ui): This needs custom ui
243 // .add_renderer::<settings::BufferLineHeight>(|settings_field, file, _, window, cx| {
244 // // todo(settings_ui): Do we want to expose the custom variant of buffer line height?
245 // // right now there's a manual impl of strum::VariantArray
246 // render_dropdown(*settings_field, file, window, cx)
247 // })
248 .add_renderer::<settings::BaseKeymapContent>(|settings_field, file, _, window, cx| {
249 render_dropdown(*settings_field, file, window, cx)
250 })
251 .add_renderer::<settings::MultiCursorModifier>(|settings_field, file, _, window, cx| {
252 render_dropdown(*settings_field, file, window, cx)
253 })
254 .add_renderer::<settings::HideMouseMode>(|settings_field, file, _, window, cx| {
255 render_dropdown(*settings_field, file, window, cx)
256 })
257 .add_renderer::<settings::CurrentLineHighlight>(|settings_field, file, _, window, cx| {
258 render_dropdown(*settings_field, file, window, cx)
259 })
260 .add_renderer::<settings::ShowWhitespaceSetting>(|settings_field, file, _, window, cx| {
261 render_dropdown(*settings_field, file, window, cx)
262 })
263 .add_renderer::<settings::SoftWrap>(|settings_field, file, _, window, cx| {
264 render_dropdown(*settings_field, file, window, cx)
265 })
266 .add_renderer::<settings::ScrollBeyondLastLine>(|settings_field, file, _, window, cx| {
267 render_dropdown(*settings_field, file, window, cx)
268 })
269 .add_renderer::<settings::SnippetSortOrder>(|settings_field, file, _, window, cx| {
270 render_dropdown(*settings_field, file, window, cx)
271 })
272 .add_renderer::<settings::ClosePosition>(|settings_field, file, _, window, cx| {
273 render_dropdown(*settings_field, file, window, cx)
274 })
275 .add_renderer::<settings::DockSide>(|settings_field, file, _, window, cx| {
276 render_dropdown(*settings_field, file, window, cx)
277 })
278 .add_renderer::<settings::TerminalDockPosition>(|settings_field, file, _, window, cx| {
279 render_dropdown(*settings_field, file, window, cx)
280 })
281 .add_renderer::<settings::DockPosition>(|settings_field, file, _, window, cx| {
282 render_dropdown(*settings_field, file, window, cx)
283 })
284 .add_renderer::<settings::GitGutterSetting>(|settings_field, file, _, window, cx| {
285 render_dropdown(*settings_field, file, window, cx)
286 })
287 .add_renderer::<settings::GitHunkStyleSetting>(|settings_field, file, _, window, cx| {
288 render_dropdown(*settings_field, file, window, cx)
289 })
290 .add_renderer::<settings::DiagnosticSeverityContent>(
291 |settings_field, file, _, window, cx| {
292 render_dropdown(*settings_field, file, window, cx)
293 },
294 )
295 .add_renderer::<settings::SeedQuerySetting>(|settings_field, file, _, window, cx| {
296 render_dropdown(*settings_field, file, window, cx)
297 })
298 .add_renderer::<settings::DoubleClickInMultibuffer>(
299 |settings_field, file, _, window, cx| {
300 render_dropdown(*settings_field, file, window, cx)
301 },
302 )
303 .add_renderer::<settings::GoToDefinitionFallback>(|settings_field, file, _, window, cx| {
304 render_dropdown(*settings_field, file, window, cx)
305 })
306 .add_renderer::<settings::ActivateOnClose>(|settings_field, file, _, window, cx| {
307 render_dropdown(*settings_field, file, window, cx)
308 })
309 .add_renderer::<settings::ShowDiagnostics>(|settings_field, file, _, window, cx| {
310 render_dropdown(*settings_field, file, window, cx)
311 })
312 .add_renderer::<settings::ShowCloseButton>(|settings_field, file, _, window, cx| {
313 render_dropdown(*settings_field, file, window, cx)
314 })
315 .add_renderer::<settings::ProjectPanelEntrySpacing>(
316 |settings_field, file, _, window, cx| {
317 render_dropdown(*settings_field, file, window, cx)
318 },
319 )
320 .add_renderer::<settings::RewrapBehavior>(|settings_field, file, _, window, cx| {
321 render_dropdown(*settings_field, file, window, cx)
322 })
323 .add_renderer::<settings::FormatOnSave>(|settings_field, file, _, window, cx| {
324 render_dropdown(*settings_field, file, window, cx)
325 })
326 .add_renderer::<settings::IndentGuideColoring>(|settings_field, file, _, window, cx| {
327 render_dropdown(*settings_field, file, window, cx)
328 })
329 .add_renderer::<settings::IndentGuideBackgroundColoring>(
330 |settings_field, file, _, window, cx| {
331 render_dropdown(*settings_field, file, window, cx)
332 },
333 )
334 .add_renderer::<settings::FileFinderWidthContent>(|settings_field, file, _, window, cx| {
335 render_dropdown(*settings_field, file, window, cx)
336 })
337 .add_renderer::<settings::ShowDiagnostics>(|settings_field, file, _, window, cx| {
338 render_dropdown(*settings_field, file, window, cx)
339 })
340 .add_renderer::<settings::WordsCompletionMode>(|settings_field, file, _, window, cx| {
341 render_dropdown(*settings_field, file, window, cx)
342 })
343 .add_renderer::<settings::LspInsertMode>(|settings_field, file, _, window, cx| {
344 render_dropdown(*settings_field, file, window, cx)
345 })
346 .add_renderer::<f32>(|settings_field, file, _, window, cx| {
347 render_numeric_stepper(*settings_field, file, window, cx)
348 })
349 .add_renderer::<u32>(|settings_field, file, _, window, cx| {
350 render_numeric_stepper(*settings_field, file, window, cx)
351 })
352 .add_renderer::<u64>(|settings_field, file, _, window, cx| {
353 render_numeric_stepper(*settings_field, file, window, cx)
354 })
355 .add_renderer::<NonZeroU32>(|settings_field, file, _, window, cx| {
356 render_numeric_stepper(*settings_field, file, window, cx)
357 })
358 .add_renderer::<CodeFade>(|settings_field, file, _, window, cx| {
359 render_numeric_stepper(*settings_field, file, window, cx)
360 })
361 .add_renderer::<FontWeight>(|settings_field, file, _, window, cx| {
362 render_numeric_stepper(*settings_field, file, window, cx)
363 });
364
365 // todo(settings_ui): Figure out how we want to handle discriminant unions
366 // .add_renderer::<ThemeSelection>(|settings_field, file, _, window, cx| {
367 // render_dropdown(*settings_field, file, window, cx)
368 // });
369}
370
371pub fn open_settings_editor(cx: &mut App) -> anyhow::Result<WindowHandle<SettingsWindow>> {
372 cx.open_window(
373 WindowOptions {
374 titlebar: Some(TitlebarOptions {
375 title: Some("Settings Window".into()),
376 appears_transparent: true,
377 traffic_light_position: Some(point(px(12.0), px(12.0))),
378 }),
379 focus: true,
380 show: true,
381 kind: gpui::WindowKind::Normal,
382 window_background: cx.theme().window_background_appearance(),
383 window_min_size: Some(size(px(800.), px(600.))), // 4:3 Aspect Ratio
384 ..Default::default()
385 },
386 |window, cx| cx.new(|cx| SettingsWindow::new(window, cx)),
387 )
388}
389
390/// The current sub page path that is selected.
391/// If this is empty the selected page is rendered,
392/// otherwise the last sub page gets rendered.
393///
394/// Global so that `pick` and `pick_mut` callbacks can access it
395/// and use it to dynamically render sub pages (e.g. for language settings)
396static SUB_PAGE_STACK: LazyLock<RwLock<Vec<SubPage>>> = LazyLock::new(|| RwLock::new(Vec::new()));
397
398fn sub_page_stack() -> std::sync::RwLockReadGuard<'static, Vec<SubPage>> {
399 SUB_PAGE_STACK
400 .read()
401 .expect("SUB_PAGE_STACK is never poisoned")
402}
403
404fn sub_page_stack_mut() -> std::sync::RwLockWriteGuard<'static, Vec<SubPage>> {
405 SUB_PAGE_STACK
406 .write()
407 .expect("SUB_PAGE_STACK is never poisoned")
408}
409
410pub struct SettingsWindow {
411 files: Vec<SettingsUiFile>,
412 current_file: SettingsUiFile,
413 pages: Vec<SettingsPage>,
414 search_bar: Entity<Editor>,
415 search_task: Option<Task<()>>,
416 navbar_entry: usize, // Index into pages - should probably be (usize, Option<usize>) for section + page
417 navbar_entries: Vec<NavBarEntry>,
418 list_handle: UniformListScrollHandle,
419 search_matches: Vec<Vec<bool>>,
420 scroll_handle: ScrollHandle,
421}
422
423struct SubPage {
424 link: SubPageLink,
425 section_header: &'static str,
426}
427
428#[derive(PartialEq, Debug)]
429struct NavBarEntry {
430 title: &'static str,
431 is_root: bool,
432 expanded: bool,
433 page_index: usize,
434 item_index: Option<usize>,
435}
436
437struct SettingsPage {
438 title: &'static str,
439 items: Vec<SettingsPageItem>,
440}
441
442#[derive(PartialEq)]
443enum SettingsPageItem {
444 SectionHeader(&'static str),
445 SettingItem(SettingItem),
446 SubPageLink(SubPageLink),
447}
448
449impl std::fmt::Debug for SettingsPageItem {
450 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
451 match self {
452 SettingsPageItem::SectionHeader(header) => write!(f, "SectionHeader({})", header),
453 SettingsPageItem::SettingItem(setting_item) => {
454 write!(f, "SettingItem({})", setting_item.title)
455 }
456 SettingsPageItem::SubPageLink(sub_page_link) => {
457 write!(f, "SubPageLink({})", sub_page_link.title)
458 }
459 }
460 }
461}
462
463impl SettingsPageItem {
464 fn render(
465 &self,
466 file: SettingsUiFile,
467 section_header: &'static str,
468 is_last: bool,
469 window: &mut Window,
470 cx: &mut Context<SettingsWindow>,
471 ) -> AnyElement {
472 match self {
473 SettingsPageItem::SectionHeader(header) => v_flex()
474 .w_full()
475 .gap_1()
476 .child(
477 Label::new(SharedString::new_static(header))
478 .size(LabelSize::XSmall)
479 .color(Color::Muted)
480 .buffer_font(cx),
481 )
482 .child(Divider::horizontal().color(ui::DividerColor::BorderVariant))
483 .into_any_element(),
484 SettingsPageItem::SettingItem(setting_item) => {
485 let renderer = cx.default_global::<SettingFieldRenderer>().clone();
486 let file_set_in =
487 SettingsUiFile::from_settings(setting_item.field.file_set_in(file.clone(), cx));
488
489 h_flex()
490 .id(setting_item.title)
491 .w_full()
492 .gap_2()
493 .flex_wrap()
494 .justify_between()
495 .map(|this| {
496 if is_last {
497 this.pb_6()
498 } else {
499 this.pb_4()
500 .border_b_1()
501 .border_color(cx.theme().colors().border_variant)
502 }
503 })
504 .child(
505 v_flex()
506 .max_w_1_2()
507 .flex_shrink()
508 .child(
509 h_flex()
510 .w_full()
511 .gap_1()
512 .child(Label::new(SharedString::new_static(setting_item.title)))
513 .when_some(
514 file_set_in.filter(|file_set_in| file_set_in != &file),
515 |this, file_set_in| {
516 this.child(
517 Label::new(format!(
518 "— set in {}",
519 file_set_in.name()
520 ))
521 .color(Color::Muted)
522 .size(LabelSize::Small),
523 )
524 },
525 ),
526 )
527 .child(
528 Label::new(SharedString::new_static(setting_item.description))
529 .size(LabelSize::Small)
530 .color(Color::Muted),
531 ),
532 )
533 .child(renderer.render(
534 setting_item.field.as_ref(),
535 file,
536 setting_item.metadata.as_deref(),
537 window,
538 cx,
539 ))
540 .into_any_element()
541 }
542 SettingsPageItem::SubPageLink(sub_page_link) => h_flex()
543 .id(sub_page_link.title)
544 .w_full()
545 .gap_2()
546 .flex_wrap()
547 .justify_between()
548 .when(!is_last, |this| {
549 this.pb_4()
550 .border_b_1()
551 .border_color(cx.theme().colors().border_variant)
552 })
553 .child(
554 v_flex()
555 .max_w_1_2()
556 .flex_shrink()
557 .child(Label::new(SharedString::new_static(sub_page_link.title))),
558 )
559 .child(
560 Button::new(("sub-page".into(), sub_page_link.title), "Configure")
561 .size(ButtonSize::Medium)
562 .icon(IconName::ChevronRight)
563 .icon_position(IconPosition::End)
564 .icon_color(Color::Muted)
565 .icon_size(IconSize::Small)
566 .style(ButtonStyle::Outlined),
567 )
568 .on_click({
569 let sub_page_link = sub_page_link.clone();
570 cx.listener(move |this, _, _, cx| {
571 this.push_sub_page(sub_page_link.clone(), section_header, cx)
572 })
573 })
574 .into_any_element(),
575 }
576 }
577}
578
579struct SettingItem {
580 title: &'static str,
581 description: &'static str,
582 field: Box<dyn AnySettingField>,
583 metadata: Option<Box<SettingsFieldMetadata>>,
584}
585
586impl PartialEq for SettingItem {
587 fn eq(&self, other: &Self) -> bool {
588 self.title == other.title
589 && self.description == other.description
590 && (match (&self.metadata, &other.metadata) {
591 (None, None) => true,
592 (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
593 _ => false,
594 })
595 }
596}
597
598#[derive(Clone)]
599struct SubPageLink {
600 title: &'static str,
601 render: Arc<
602 dyn Fn(&mut SettingsWindow, &mut Window, &mut Context<SettingsWindow>) -> AnyElement
603 + 'static
604 + Send
605 + Sync,
606 >,
607}
608
609impl PartialEq for SubPageLink {
610 fn eq(&self, other: &Self) -> bool {
611 self.title == other.title
612 }
613}
614
615#[allow(unused)]
616#[derive(Clone, PartialEq)]
617enum SettingsUiFile {
618 User, // Uses all settings.
619 Local((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
620 Server(&'static str), // Uses a special name, and the user settings
621}
622
623impl SettingsUiFile {
624 fn pages(&self) -> Vec<SettingsPage> {
625 match self {
626 SettingsUiFile::User => page_data::user_settings_data(),
627 SettingsUiFile::Local(_) => page_data::project_settings_data(),
628 SettingsUiFile::Server(_) => page_data::user_settings_data(),
629 }
630 }
631
632 fn name(&self) -> SharedString {
633 match self {
634 SettingsUiFile::User => SharedString::new_static("User"),
635 // TODO is PathStyle::local() ever not appropriate?
636 SettingsUiFile::Local((_, path)) => {
637 format!("Local ({})", path.display(PathStyle::local())).into()
638 }
639 SettingsUiFile::Server(file) => format!("Server ({})", file).into(),
640 }
641 }
642
643 fn from_settings(file: settings::SettingsFile) -> Option<Self> {
644 Some(match file {
645 settings::SettingsFile::User => SettingsUiFile::User,
646 settings::SettingsFile::Local(location) => SettingsUiFile::Local(location),
647 settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
648 settings::SettingsFile::Default => return None,
649 })
650 }
651
652 fn to_settings(&self) -> settings::SettingsFile {
653 match self {
654 SettingsUiFile::User => settings::SettingsFile::User,
655 SettingsUiFile::Local(location) => settings::SettingsFile::Local(location.clone()),
656 SettingsUiFile::Server(_) => settings::SettingsFile::Server,
657 }
658 }
659}
660
661impl SettingsWindow {
662 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
663 let font_family_cache = theme::FontFamilyCache::global(cx);
664
665 cx.spawn(async move |this, cx| {
666 font_family_cache.prefetch(cx).await;
667 this.update(cx, |_, cx| {
668 cx.notify();
669 })
670 })
671 .detach();
672
673 let current_file = SettingsUiFile::User;
674 let search_bar = cx.new(|cx| {
675 let mut editor = Editor::single_line(window, cx);
676 editor.set_placeholder_text("Search settings…", window, cx);
677 editor
678 });
679
680 cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
681 let EditorEvent::Edited { transaction_id: _ } = event else {
682 return;
683 };
684
685 this.update_matches(cx);
686 })
687 .detach();
688
689 cx.observe_global_in::<SettingsStore>(window, move |this, _, cx| {
690 this.fetch_files(cx);
691 cx.notify();
692 })
693 .detach();
694
695 let mut this = Self {
696 files: vec![],
697 current_file: current_file,
698 pages: vec![],
699 navbar_entries: vec![],
700 navbar_entry: 0,
701 list_handle: UniformListScrollHandle::default(),
702 search_bar,
703 search_task: None,
704 search_matches: vec![],
705 scroll_handle: ScrollHandle::new(),
706 };
707
708 this.fetch_files(cx);
709 this.build_ui(cx);
710
711 this.search_bar.update(cx, |editor, cx| {
712 editor.focus_handle(cx).focus(window);
713 });
714
715 this
716 }
717
718 fn toggle_navbar_entry(&mut self, ix: usize) {
719 // We can only toggle root entries
720 if !self.navbar_entries[ix].is_root {
721 return;
722 }
723
724 let toggle_page_index = self.page_index_from_navbar_index(ix);
725 let selected_page_index = self.page_index_from_navbar_index(self.navbar_entry);
726
727 let expanded = &mut self.navbar_entries[ix].expanded;
728 *expanded = !*expanded;
729 // if currently selected page is a child of the parent page we are folding,
730 // set the current page to the parent page
731 if !*expanded && selected_page_index == toggle_page_index {
732 self.navbar_entry = ix;
733 }
734 }
735
736 fn build_navbar(&mut self) {
737 let mut navbar_entries = Vec::with_capacity(self.navbar_entries.len());
738 for (page_index, page) in self.pages.iter().enumerate() {
739 navbar_entries.push(NavBarEntry {
740 title: page.title,
741 is_root: true,
742 expanded: false,
743 page_index,
744 item_index: None,
745 });
746
747 for (item_index, item) in page.items.iter().enumerate() {
748 let SettingsPageItem::SectionHeader(title) = item else {
749 continue;
750 };
751 navbar_entries.push(NavBarEntry {
752 title,
753 is_root: false,
754 expanded: false,
755 page_index,
756 item_index: Some(item_index),
757 });
758 }
759 }
760 self.navbar_entries = navbar_entries;
761 }
762
763 fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
764 let mut index = 0;
765 let entries = &self.navbar_entries;
766 let search_matches = &self.search_matches;
767 std::iter::from_fn(move || {
768 while index < entries.len() {
769 let entry = &entries[index];
770 let included_in_search = if let Some(item_index) = entry.item_index {
771 search_matches[entry.page_index][item_index]
772 } else {
773 search_matches[entry.page_index].iter().any(|b| *b)
774 || search_matches[entry.page_index].is_empty()
775 };
776 if included_in_search {
777 break;
778 }
779 index += 1;
780 }
781 if index >= self.navbar_entries.len() {
782 return None;
783 }
784 let entry = &entries[index];
785 let entry_index = index;
786
787 index += 1;
788 if entry.is_root && !entry.expanded {
789 while index < entries.len() {
790 if entries[index].is_root {
791 break;
792 }
793 index += 1;
794 }
795 }
796
797 return Some((entry_index, entry));
798 })
799 }
800
801 fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
802 self.search_task.take();
803 let query = self.search_bar.read(cx).text(cx);
804 if query.is_empty() {
805 for page in &mut self.search_matches {
806 page.fill(true);
807 }
808 cx.notify();
809 return;
810 }
811
812 struct ItemKey {
813 page_index: usize,
814 header_index: usize,
815 item_index: usize,
816 }
817 let mut key_lut: Vec<ItemKey> = vec![];
818 let mut candidates = Vec::default();
819
820 for (page_index, page) in self.pages.iter().enumerate() {
821 let mut header_index = 0;
822 for (item_index, item) in page.items.iter().enumerate() {
823 let key_index = key_lut.len();
824 match item {
825 SettingsPageItem::SettingItem(item) => {
826 candidates.push(StringMatchCandidate::new(key_index, item.title));
827 candidates.push(StringMatchCandidate::new(key_index, item.description));
828 }
829 SettingsPageItem::SectionHeader(header) => {
830 candidates.push(StringMatchCandidate::new(key_index, header));
831 header_index = item_index;
832 }
833 SettingsPageItem::SubPageLink(sub_page_link) => {
834 candidates.push(StringMatchCandidate::new(key_index, sub_page_link.title));
835 }
836 }
837 key_lut.push(ItemKey {
838 page_index,
839 header_index,
840 item_index,
841 });
842 }
843 }
844 let atomic_bool = AtomicBool::new(false);
845
846 self.search_task = Some(cx.spawn(async move |this, cx| {
847 let string_matches = fuzzy::match_strings(
848 candidates.as_slice(),
849 &query,
850 false,
851 true,
852 candidates.len(),
853 &atomic_bool,
854 cx.background_executor().clone(),
855 );
856 let string_matches = string_matches.await;
857
858 this.update(cx, |this, cx| {
859 for page in &mut this.search_matches {
860 page.fill(false);
861 }
862
863 for string_match in string_matches {
864 let ItemKey {
865 page_index,
866 header_index,
867 item_index,
868 } = key_lut[string_match.candidate_id];
869 let page = &mut this.search_matches[page_index];
870 page[header_index] = true;
871 page[item_index] = true;
872 }
873 let first_navbar_entry_index = this
874 .visible_navbar_entries()
875 .next()
876 .map(|e| e.0)
877 .unwrap_or(0);
878 this.navbar_entry = first_navbar_entry_index;
879 cx.notify();
880 })
881 .ok();
882 }));
883 }
884
885 fn build_search_matches(&mut self) {
886 self.search_matches = self
887 .pages
888 .iter()
889 .map(|page| vec![true; page.items.len()])
890 .collect::<Vec<_>>();
891 }
892
893 fn build_ui(&mut self, cx: &mut Context<SettingsWindow>) {
894 self.pages = self.current_file.pages();
895 self.build_search_matches();
896 self.build_navbar();
897
898 if !self.search_bar.read(cx).is_empty(cx) {
899 self.update_matches(cx);
900 }
901
902 cx.notify();
903 }
904
905 fn fetch_files(&mut self, cx: &mut Context<SettingsWindow>) {
906 let settings_store = cx.global::<SettingsStore>();
907 let mut ui_files = vec![];
908 let all_files = settings_store.get_all_files();
909 for file in all_files {
910 let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
911 continue;
912 };
913 ui_files.push(settings_ui_file);
914 }
915 ui_files.reverse();
916 self.files = ui_files;
917 if !self.files.contains(&self.current_file) {
918 self.change_file(0, cx);
919 }
920 }
921
922 fn change_file(&mut self, ix: usize, cx: &mut Context<SettingsWindow>) {
923 if ix >= self.files.len() {
924 self.current_file = SettingsUiFile::User;
925 return;
926 }
927 if self.files[ix] == self.current_file {
928 return;
929 }
930 self.current_file = self.files[ix].clone();
931 self.navbar_entry = 0;
932 self.build_ui(cx);
933 }
934
935 fn render_files(&self, _window: &mut Window, cx: &mut Context<SettingsWindow>) -> Div {
936 h_flex()
937 .gap_1()
938 .children(self.files.iter().enumerate().map(|(ix, file)| {
939 Button::new(ix, file.name())
940 .toggle_state(file == &self.current_file)
941 .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
942 .on_click(cx.listener(move |this, _, _window, cx| this.change_file(ix, cx)))
943 }))
944 }
945
946 fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
947 h_flex()
948 .py_1()
949 .px_1p5()
950 .gap_1p5()
951 .rounded_sm()
952 .bg(cx.theme().colors().editor_background)
953 .border_1()
954 .border_color(cx.theme().colors().border)
955 .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
956 .child(self.search_bar.clone())
957 }
958
959 fn render_nav(
960 &self,
961 window: &mut Window,
962 cx: &mut Context<SettingsWindow>,
963 ) -> impl IntoElement {
964 let visible_entries: Vec<_> = self.visible_navbar_entries().collect();
965 let visible_count = visible_entries.len();
966
967 v_flex()
968 .w_64()
969 .p_2p5()
970 .pt_10()
971 .gap_3()
972 .flex_none()
973 .border_r_1()
974 .border_color(cx.theme().colors().border)
975 .bg(cx.theme().colors().panel_background)
976 .child(self.render_search(window, cx))
977 .child(
978 v_flex()
979 .size_full()
980 .child(
981 uniform_list(
982 "settings-ui-nav-bar",
983 visible_count,
984 cx.processor(move |this, range: Range<usize>, _, cx| {
985 let entries: Vec<_> = this.visible_navbar_entries().collect();
986 range
987 .filter_map(|ix| entries.get(ix).copied())
988 .map(|(ix, entry)| {
989 TreeViewItem::new(
990 ("settings-ui-navbar-entry", ix),
991 entry.title,
992 )
993 .root_item(entry.is_root)
994 .toggle_state(this.is_navbar_entry_selected(ix))
995 .when(entry.is_root, |item| {
996 item.expanded(entry.expanded).on_toggle(cx.listener(
997 move |this, _, _, cx| {
998 this.toggle_navbar_entry(ix);
999 cx.notify();
1000 },
1001 ))
1002 })
1003 .on_click(cx.listener(move |this, _, _, cx| {
1004 this.navbar_entry = ix;
1005 cx.notify();
1006 }))
1007 .into_any_element()
1008 })
1009 .collect()
1010 }),
1011 )
1012 .track_scroll(self.list_handle.clone())
1013 .flex_grow(),
1014 )
1015 .vertical_scrollbar_for(self.list_handle.clone(), window, cx),
1016 )
1017 }
1018
1019 fn page_items(&self) -> impl Iterator<Item = &SettingsPageItem> {
1020 let page_idx = self.current_page_index();
1021
1022 self.current_page()
1023 .items
1024 .iter()
1025 .enumerate()
1026 .filter_map(move |(item_index, item)| {
1027 self.search_matches[page_idx][item_index].then_some(item)
1028 })
1029 }
1030
1031 fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
1032 let mut items = vec![];
1033 items.push(self.current_page().title);
1034 items.extend(
1035 sub_page_stack()
1036 .iter()
1037 .flat_map(|page| [page.section_header, page.link.title]),
1038 );
1039
1040 let last = items.pop().unwrap();
1041 h_flex()
1042 .gap_1()
1043 .children(
1044 items
1045 .into_iter()
1046 .flat_map(|item| [item, "/"])
1047 .map(|item| Label::new(item).color(Color::Muted)),
1048 )
1049 .child(Label::new(last))
1050 }
1051
1052 fn render_page_items<'a, Items: Iterator<Item = &'a SettingsPageItem>>(
1053 &self,
1054 items: Items,
1055 window: &mut Window,
1056 cx: &mut Context<SettingsWindow>,
1057 ) -> impl IntoElement {
1058 let mut page_content = v_flex()
1059 .id("settings-ui-page")
1060 .size_full()
1061 .gap_4()
1062 .overflow_y_scroll()
1063 .track_scroll(&self.scroll_handle);
1064
1065 let items: Vec<_> = items.collect();
1066 let items_len = items.len();
1067 let mut section_header = None;
1068
1069 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
1070 let has_no_results = items_len == 0 && has_active_search;
1071
1072 if has_no_results {
1073 let search_query = self.search_bar.read(cx).text(cx);
1074 page_content = page_content.child(
1075 v_flex()
1076 .size_full()
1077 .items_center()
1078 .justify_center()
1079 .gap_1()
1080 .child(div().child("No Results"))
1081 .child(
1082 div()
1083 .text_sm()
1084 .text_color(cx.theme().colors().text_muted)
1085 .child(format!("No settings match \"{}\"", search_query)),
1086 ),
1087 )
1088 } else {
1089 let last_non_header_index = items
1090 .iter()
1091 .enumerate()
1092 .rev()
1093 .find(|(_, item)| !matches!(item, SettingsPageItem::SectionHeader(_)))
1094 .map(|(index, _)| index);
1095
1096 page_content =
1097 page_content.children(items.clone().into_iter().enumerate().map(|(index, item)| {
1098 let no_bottom_border = items
1099 .get(index + 1)
1100 .map(|next_item| matches!(next_item, SettingsPageItem::SectionHeader(_)))
1101 .unwrap_or(false);
1102 let is_last = Some(index) == last_non_header_index;
1103
1104 if let SettingsPageItem::SectionHeader(header) = item {
1105 section_header = Some(*header);
1106 }
1107 item.render(
1108 self.current_file.clone(),
1109 section_header.expect("All items rendered after a section header"),
1110 no_bottom_border || is_last,
1111 window,
1112 cx,
1113 )
1114 }))
1115 }
1116 page_content
1117 }
1118
1119 fn render_page(
1120 &mut self,
1121 window: &mut Window,
1122 cx: &mut Context<SettingsWindow>,
1123 ) -> impl IntoElement {
1124 let mut page = v_flex()
1125 .w_full()
1126 .pt_4()
1127 .pb_6()
1128 .px_6()
1129 .gap_4()
1130 .bg(cx.theme().colors().editor_background)
1131 .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx);
1132
1133 let page_content;
1134
1135 if sub_page_stack().len() == 0 {
1136 page = page.child(self.render_files(window, cx));
1137 page_content = self
1138 .render_page_items(self.page_items(), window, cx)
1139 .into_any_element();
1140 } else {
1141 page = page.child(
1142 h_flex()
1143 .ml_neg_1p5()
1144 .gap_1()
1145 .child(
1146 IconButton::new("back-btn", IconName::ArrowLeft)
1147 .icon_size(IconSize::Small)
1148 .shape(IconButtonShape::Square)
1149 .on_click(cx.listener(|this, _, _, cx| {
1150 this.pop_sub_page(cx);
1151 })),
1152 )
1153 .child(self.render_sub_page_breadcrumbs()),
1154 );
1155
1156 let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
1157 page_content = (active_page_render_fn)(self, window, cx);
1158 }
1159
1160 return page.child(page_content);
1161 }
1162
1163 fn current_page_index(&self) -> usize {
1164 self.page_index_from_navbar_index(self.navbar_entry)
1165 }
1166
1167 fn current_page(&self) -> &SettingsPage {
1168 &self.pages[self.current_page_index()]
1169 }
1170
1171 fn page_index_from_navbar_index(&self, index: usize) -> usize {
1172 if self.navbar_entries.is_empty() {
1173 return 0;
1174 }
1175
1176 self.navbar_entries[index].page_index
1177 }
1178
1179 fn is_navbar_entry_selected(&self, ix: usize) -> bool {
1180 ix == self.navbar_entry
1181 }
1182
1183 fn push_sub_page(
1184 &mut self,
1185 sub_page_link: SubPageLink,
1186 section_header: &'static str,
1187 cx: &mut Context<SettingsWindow>,
1188 ) {
1189 sub_page_stack_mut().push(SubPage {
1190 link: sub_page_link,
1191 section_header,
1192 });
1193 cx.notify();
1194 }
1195
1196 fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
1197 sub_page_stack_mut().pop();
1198 cx.notify();
1199 }
1200}
1201
1202impl Render for SettingsWindow {
1203 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1204 let ui_font = theme::setup_ui_font(window, cx);
1205
1206 div()
1207 .key_context("SettingsWindow")
1208 .flex()
1209 .flex_row()
1210 .size_full()
1211 .font(ui_font)
1212 .bg(cx.theme().colors().background)
1213 .text_color(cx.theme().colors().text)
1214 .child(self.render_nav(window, cx))
1215 .child(self.render_page(window, cx))
1216 }
1217}
1218
1219fn update_settings_file(
1220 file: SettingsUiFile,
1221 cx: &mut App,
1222 update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
1223) -> Result<()> {
1224 match file {
1225 SettingsUiFile::Local((worktree_id, rel_path)) => {
1226 fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
1227 workspace::AppState::global(cx)
1228 .upgrade()
1229 .map(|app_state| {
1230 app_state
1231 .workspace_store
1232 .read(cx)
1233 .workspaces()
1234 .iter()
1235 .filter_map(|workspace| {
1236 Some(workspace.read(cx).ok()?.project().clone())
1237 })
1238 })
1239 .into_iter()
1240 .flatten()
1241 }
1242 let rel_path = rel_path.join(paths::local_settings_file_relative_path());
1243 let project = all_projects(cx).find(|project| {
1244 project.read_with(cx, |project, cx| {
1245 project.contains_local_settings_file(worktree_id, &rel_path, cx)
1246 })
1247 });
1248 let Some(project) = project else {
1249 anyhow::bail!(
1250 "Could not find worktree containing settings file: {}",
1251 &rel_path.display(PathStyle::local())
1252 );
1253 };
1254 project.update(cx, |project, cx| {
1255 project.update_local_settings_file(worktree_id, rel_path, cx, update);
1256 });
1257 return Ok(());
1258 }
1259 SettingsUiFile::User => {
1260 // todo(settings_ui) error?
1261 SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
1262 Ok(())
1263 }
1264 SettingsUiFile::Server(_) => unimplemented!(),
1265 }
1266}
1267
1268fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
1269 field: SettingField<T>,
1270 file: SettingsUiFile,
1271 metadata: Option<&SettingsFieldMetadata>,
1272 cx: &mut App,
1273) -> AnyElement {
1274 let (_, initial_text) =
1275 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1276 let initial_text = Some(initial_text.clone()).filter(|s| !s.as_ref().is_empty());
1277
1278 SettingsEditor::new()
1279 .when_some(initial_text, |editor, text| {
1280 editor.with_initial_text(text.into())
1281 })
1282 .when_some(
1283 metadata.and_then(|metadata| metadata.placeholder),
1284 |editor, placeholder| editor.with_placeholder(placeholder),
1285 )
1286 .on_confirm({
1287 move |new_text, cx| {
1288 update_settings_file(file.clone(), cx, move |settings, _cx| {
1289 *(field.pick_mut)(settings) = new_text.map(Into::into);
1290 })
1291 .log_err(); // todo(settings_ui) don't log err
1292 }
1293 })
1294 .into_any_element()
1295}
1296
1297fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
1298 field: SettingField<B>,
1299 file: SettingsUiFile,
1300 cx: &mut App,
1301) -> AnyElement {
1302 let (_, &value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1303
1304 let toggle_state = if value.into() {
1305 ToggleState::Selected
1306 } else {
1307 ToggleState::Unselected
1308 };
1309
1310 Switch::new("toggle_button", toggle_state)
1311 .color(ui::SwitchColor::Accent)
1312 .on_click({
1313 move |state, _window, cx| {
1314 let state = *state == ui::ToggleState::Selected;
1315 update_settings_file(file.clone(), cx, move |settings, _cx| {
1316 *(field.pick_mut)(settings) = Some(state.into());
1317 })
1318 .log_err(); // todo(settings_ui) don't log err
1319 }
1320 })
1321 .color(SwitchColor::Accent)
1322 .into_any_element()
1323}
1324
1325fn render_font_picker(
1326 field: SettingField<settings::FontFamilyName>,
1327 file: SettingsUiFile,
1328 window: &mut Window,
1329 cx: &mut App,
1330) -> AnyElement {
1331 let current_value = SettingsStore::global(cx)
1332 .get_value_from_file(file.to_settings(), field.pick)
1333 .1
1334 .clone();
1335
1336 let font_picker = cx.new(|cx| {
1337 ui_input::font_picker(
1338 current_value.clone().into(),
1339 move |font_name, cx| {
1340 update_settings_file(file.clone(), cx, move |settings, _cx| {
1341 *(field.pick_mut)(settings) = Some(font_name.into());
1342 })
1343 .log_err(); // todo(settings_ui) don't log err
1344 },
1345 window,
1346 cx,
1347 )
1348 });
1349
1350 div()
1351 .child(
1352 PopoverMenu::new("font-picker")
1353 .menu(move |_window, _cx| Some(font_picker.clone()))
1354 .trigger(
1355 ButtonLike::new("font-family-button")
1356 .style(ButtonStyle::Outlined)
1357 .size(ButtonSize::Medium)
1358 .full_width()
1359 .child(
1360 h_flex()
1361 .w_full()
1362 .justify_between()
1363 .child(Label::new(current_value))
1364 .child(
1365 Icon::new(IconName::ChevronUpDown)
1366 .color(Color::Muted)
1367 .size(IconSize::XSmall),
1368 ),
1369 ),
1370 )
1371 .full_width(true)
1372 .anchor(gpui::Corner::TopLeft)
1373 .offset(gpui::Point {
1374 x: px(0.0),
1375 y: px(4.0),
1376 })
1377 .with_handle(ui::PopoverMenuHandle::default()),
1378 )
1379 .into_any_element()
1380}
1381
1382fn render_numeric_stepper<T: NumericStepperType + Send + Sync>(
1383 field: SettingField<T>,
1384 file: SettingsUiFile,
1385 window: &mut Window,
1386 cx: &mut App,
1387) -> AnyElement {
1388 let (_, &value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1389
1390 NumericStepper::new("numeric_stepper", value, window, cx)
1391 .on_change({
1392 move |value, _window, cx| {
1393 let value = *value;
1394 update_settings_file(file.clone(), cx, move |settings, _cx| {
1395 *(field.pick_mut)(settings) = Some(value);
1396 })
1397 .log_err(); // todo(settings_ui) don't log err
1398 }
1399 })
1400 .style(NumericStepperStyle::Outlined)
1401 .into_any_element()
1402}
1403
1404fn render_dropdown<T>(
1405 field: SettingField<T>,
1406 file: SettingsUiFile,
1407 window: &mut Window,
1408 cx: &mut App,
1409) -> AnyElement
1410where
1411 T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
1412{
1413 let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
1414 let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
1415
1416 let (_, ¤t_value) =
1417 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1418
1419 let current_value_label =
1420 labels()[variants().iter().position(|v| *v == current_value).unwrap()];
1421
1422 DropdownMenu::new(
1423 "dropdown",
1424 current_value_label,
1425 ContextMenu::build(window, cx, move |mut menu, _, _| {
1426 for (&value, &label) in std::iter::zip(variants(), labels()) {
1427 let file = file.clone();
1428 menu = menu.toggleable_entry(
1429 label,
1430 value == current_value,
1431 IconPosition::Start,
1432 None,
1433 move |_, cx| {
1434 if value == current_value {
1435 return;
1436 }
1437 update_settings_file(file.clone(), cx, move |settings, _cx| {
1438 *(field.pick_mut)(settings) = Some(value);
1439 })
1440 .log_err(); // todo(settings_ui) don't log err
1441 },
1442 );
1443 }
1444 menu
1445 }),
1446 )
1447 .trigger_size(ButtonSize::Medium)
1448 .style(DropdownStyle::Outlined)
1449 .offset(gpui::Point {
1450 x: px(0.0),
1451 y: px(2.0),
1452 })
1453 .into_any_element()
1454}
1455
1456#[cfg(test)]
1457mod test {
1458
1459 use super::*;
1460
1461 impl SettingsWindow {
1462 fn navbar_entry(&self) -> usize {
1463 self.navbar_entry
1464 }
1465
1466 fn new_builder(window: &mut Window, cx: &mut Context<Self>) -> Self {
1467 let mut this = Self::new(window, cx);
1468 this.navbar_entries.clear();
1469 this.pages.clear();
1470 this
1471 }
1472
1473 fn build(mut self) -> Self {
1474 self.build_search_matches();
1475 self.build_navbar();
1476 self
1477 }
1478
1479 fn add_page(
1480 mut self,
1481 title: &'static str,
1482 build_page: impl Fn(SettingsPage) -> SettingsPage,
1483 ) -> Self {
1484 let page = SettingsPage {
1485 title,
1486 items: Vec::default(),
1487 };
1488
1489 self.pages.push(build_page(page));
1490 self
1491 }
1492
1493 fn search(&mut self, search_query: &str, window: &mut Window, cx: &mut Context<Self>) {
1494 self.search_task.take();
1495 self.search_bar.update(cx, |editor, cx| {
1496 editor.set_text(search_query, window, cx);
1497 });
1498 self.update_matches(cx);
1499 }
1500
1501 fn assert_search_results(&self, other: &Self) {
1502 // page index could be different because of filtered out pages
1503 #[derive(Debug, PartialEq)]
1504 struct EntryMinimal {
1505 is_root: bool,
1506 title: &'static str,
1507 }
1508 pretty_assertions::assert_eq!(
1509 other
1510 .visible_navbar_entries()
1511 .map(|(_, entry)| EntryMinimal {
1512 is_root: entry.is_root,
1513 title: entry.title,
1514 })
1515 .collect::<Vec<_>>(),
1516 self.visible_navbar_entries()
1517 .map(|(_, entry)| EntryMinimal {
1518 is_root: entry.is_root,
1519 title: entry.title,
1520 })
1521 .collect::<Vec<_>>(),
1522 );
1523 assert_eq!(
1524 self.current_page().items.iter().collect::<Vec<_>>(),
1525 other.page_items().collect::<Vec<_>>()
1526 );
1527 }
1528 }
1529
1530 impl SettingsPage {
1531 fn item(mut self, item: SettingsPageItem) -> Self {
1532 self.items.push(item);
1533 self
1534 }
1535 }
1536
1537 impl SettingsPageItem {
1538 fn basic_item(title: &'static str, description: &'static str) -> Self {
1539 SettingsPageItem::SettingItem(SettingItem {
1540 title,
1541 description,
1542 field: Box::new(SettingField {
1543 pick: |settings_content| &settings_content.auto_update,
1544 pick_mut: |settings_content| &mut settings_content.auto_update,
1545 }),
1546 metadata: None,
1547 })
1548 }
1549 }
1550
1551 fn register_settings(cx: &mut App) {
1552 settings::init(cx);
1553 theme::init(theme::LoadThemes::JustBase, cx);
1554 workspace::init_settings(cx);
1555 project::Project::init_settings(cx);
1556 language::init(cx);
1557 editor::init(cx);
1558 menu::init();
1559 }
1560
1561 fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
1562 let mut pages: Vec<SettingsPage> = Vec::new();
1563 let mut expanded_pages = Vec::new();
1564 let mut selected_idx = None;
1565 let mut index = 0;
1566 let mut in_expanded_section = false;
1567
1568 for mut line in input
1569 .lines()
1570 .map(|line| line.trim())
1571 .filter(|line| !line.is_empty())
1572 {
1573 if let Some(pre) = line.strip_suffix('*') {
1574 assert!(selected_idx.is_none(), "Only one selected entry allowed");
1575 selected_idx = Some(index);
1576 line = pre;
1577 }
1578 let (kind, title) = line.split_once(" ").unwrap();
1579 assert_eq!(kind.len(), 1);
1580 let kind = kind.chars().next().unwrap();
1581 if kind == 'v' {
1582 let page_idx = pages.len();
1583 expanded_pages.push(page_idx);
1584 pages.push(SettingsPage {
1585 title,
1586 items: vec![],
1587 });
1588 index += 1;
1589 in_expanded_section = true;
1590 } else if kind == '>' {
1591 pages.push(SettingsPage {
1592 title,
1593 items: vec![],
1594 });
1595 index += 1;
1596 in_expanded_section = false;
1597 } else if kind == '-' {
1598 pages
1599 .last_mut()
1600 .unwrap()
1601 .items
1602 .push(SettingsPageItem::SectionHeader(title));
1603 if selected_idx == Some(index) && !in_expanded_section {
1604 panic!("Items in unexpanded sections cannot be selected");
1605 }
1606 index += 1;
1607 } else {
1608 panic!(
1609 "Entries must start with one of 'v', '>', or '-'\n line: {}",
1610 line
1611 );
1612 }
1613 }
1614
1615 let mut settings_window = SettingsWindow {
1616 files: Vec::default(),
1617 current_file: crate::SettingsUiFile::User,
1618 pages,
1619 search_bar: cx.new(|cx| Editor::single_line(window, cx)),
1620 navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
1621 navbar_entries: Vec::default(),
1622 list_handle: UniformListScrollHandle::default(),
1623 search_matches: vec![],
1624 search_task: None,
1625 scroll_handle: ScrollHandle::new(),
1626 };
1627
1628 settings_window.build_search_matches();
1629 settings_window.build_navbar();
1630 for expanded_page_index in expanded_pages {
1631 for entry in &mut settings_window.navbar_entries {
1632 if entry.page_index == expanded_page_index && entry.is_root {
1633 entry.expanded = true;
1634 }
1635 }
1636 }
1637 settings_window
1638 }
1639
1640 #[track_caller]
1641 fn check_navbar_toggle(
1642 before: &'static str,
1643 toggle_page: &'static str,
1644 after: &'static str,
1645 window: &mut Window,
1646 cx: &mut App,
1647 ) {
1648 let mut settings_window = parse(before, window, cx);
1649 let toggle_page_idx = settings_window
1650 .pages
1651 .iter()
1652 .position(|page| page.title == toggle_page)
1653 .expect("page not found");
1654 let toggle_idx = settings_window
1655 .navbar_entries
1656 .iter()
1657 .position(|entry| entry.page_index == toggle_page_idx)
1658 .expect("page not found");
1659 settings_window.toggle_navbar_entry(toggle_idx);
1660
1661 let expected_settings_window = parse(after, window, cx);
1662
1663 pretty_assertions::assert_eq!(
1664 settings_window
1665 .visible_navbar_entries()
1666 .map(|(_, entry)| entry)
1667 .collect::<Vec<_>>(),
1668 expected_settings_window
1669 .visible_navbar_entries()
1670 .map(|(_, entry)| entry)
1671 .collect::<Vec<_>>(),
1672 );
1673 pretty_assertions::assert_eq!(
1674 settings_window.navbar_entries[settings_window.navbar_entry()],
1675 expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
1676 );
1677 }
1678
1679 macro_rules! check_navbar_toggle {
1680 ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
1681 #[gpui::test]
1682 fn $name(cx: &mut gpui::TestAppContext) {
1683 let window = cx.add_empty_window();
1684 window.update(|window, cx| {
1685 register_settings(cx);
1686 check_navbar_toggle($before, $toggle_page, $after, window, cx);
1687 });
1688 }
1689 };
1690 }
1691
1692 check_navbar_toggle!(
1693 navbar_basic_open,
1694 before: r"
1695 v General
1696 - General
1697 - Privacy*
1698 v Project
1699 - Project Settings
1700 ",
1701 toggle_page: "General",
1702 after: r"
1703 > General*
1704 v Project
1705 - Project Settings
1706 "
1707 );
1708
1709 check_navbar_toggle!(
1710 navbar_basic_close,
1711 before: r"
1712 > General*
1713 - General
1714 - Privacy
1715 v Project
1716 - Project Settings
1717 ",
1718 toggle_page: "General",
1719 after: r"
1720 v General*
1721 - General
1722 - Privacy
1723 v Project
1724 - Project Settings
1725 "
1726 );
1727
1728 check_navbar_toggle!(
1729 navbar_basic_second_root_entry_close,
1730 before: r"
1731 > General
1732 - General
1733 - Privacy
1734 v Project
1735 - Project Settings*
1736 ",
1737 toggle_page: "Project",
1738 after: r"
1739 > General
1740 > Project*
1741 "
1742 );
1743
1744 check_navbar_toggle!(
1745 navbar_toggle_subroot,
1746 before: r"
1747 v General Page
1748 - General
1749 - Privacy
1750 v Project
1751 - Worktree Settings Content*
1752 v AI
1753 - General
1754 > Appearance & Behavior
1755 ",
1756 toggle_page: "Project",
1757 after: r"
1758 v General Page
1759 - General
1760 - Privacy
1761 > Project*
1762 v AI
1763 - General
1764 > Appearance & Behavior
1765 "
1766 );
1767
1768 check_navbar_toggle!(
1769 navbar_toggle_close_propagates_selected_index,
1770 before: r"
1771 v General Page
1772 - General
1773 - Privacy
1774 v Project
1775 - Worktree Settings Content
1776 v AI
1777 - General*
1778 > Appearance & Behavior
1779 ",
1780 toggle_page: "General Page",
1781 after: r"
1782 > General Page
1783 v Project
1784 - Worktree Settings Content
1785 v AI
1786 - General*
1787 > Appearance & Behavior
1788 "
1789 );
1790
1791 check_navbar_toggle!(
1792 navbar_toggle_expand_propagates_selected_index,
1793 before: r"
1794 > General Page
1795 - General
1796 - Privacy
1797 v Project
1798 - Worktree Settings Content
1799 v AI
1800 - General*
1801 > Appearance & Behavior
1802 ",
1803 toggle_page: "General Page",
1804 after: r"
1805 v General Page
1806 - General
1807 - Privacy
1808 v Project
1809 - Worktree Settings Content
1810 v AI
1811 - General*
1812 > Appearance & Behavior
1813 "
1814 );
1815
1816 #[gpui::test]
1817 fn test_basic_search(cx: &mut gpui::TestAppContext) {
1818 let cx = cx.add_empty_window();
1819 let (actual, expected) = cx.update(|window, cx| {
1820 register_settings(cx);
1821
1822 let expected = cx.new(|cx| {
1823 SettingsWindow::new_builder(window, cx)
1824 .add_page("General", |page| {
1825 page.item(SettingsPageItem::SectionHeader("General settings"))
1826 .item(SettingsPageItem::basic_item("test title", "General test"))
1827 })
1828 .build()
1829 });
1830
1831 let actual = cx.new(|cx| {
1832 SettingsWindow::new_builder(window, cx)
1833 .add_page("General", |page| {
1834 page.item(SettingsPageItem::SectionHeader("General settings"))
1835 .item(SettingsPageItem::basic_item("test title", "General test"))
1836 })
1837 .add_page("Theme", |page| {
1838 page.item(SettingsPageItem::SectionHeader("Theme settings"))
1839 })
1840 .build()
1841 });
1842
1843 actual.update(cx, |settings, cx| settings.search("gen", window, cx));
1844
1845 (actual, expected)
1846 });
1847
1848 cx.cx.run_until_parked();
1849
1850 cx.update(|_window, cx| {
1851 let expected = expected.read(cx);
1852 let actual = actual.read(cx);
1853 expected.assert_search_results(&actual);
1854 })
1855 }
1856
1857 #[gpui::test]
1858 fn test_search_render_page_with_filtered_out_navbar_entries(cx: &mut gpui::TestAppContext) {
1859 let cx = cx.add_empty_window();
1860 let (actual, expected) = cx.update(|window, cx| {
1861 register_settings(cx);
1862
1863 let actual = cx.new(|cx| {
1864 SettingsWindow::new_builder(window, cx)
1865 .add_page("General", |page| {
1866 page.item(SettingsPageItem::SectionHeader("General settings"))
1867 .item(SettingsPageItem::basic_item(
1868 "Confirm Quit",
1869 "Whether to confirm before quitting Zed",
1870 ))
1871 .item(SettingsPageItem::basic_item(
1872 "Auto Update",
1873 "Automatically update Zed",
1874 ))
1875 })
1876 .add_page("AI", |page| {
1877 page.item(SettingsPageItem::basic_item(
1878 "Disable AI",
1879 "Whether to disable all AI features in Zed",
1880 ))
1881 })
1882 .add_page("Appearance & Behavior", |page| {
1883 page.item(SettingsPageItem::SectionHeader("Cursor")).item(
1884 SettingsPageItem::basic_item(
1885 "Cursor Shape",
1886 "Cursor shape for the editor",
1887 ),
1888 )
1889 })
1890 .build()
1891 });
1892
1893 let expected = cx.new(|cx| {
1894 SettingsWindow::new_builder(window, cx)
1895 .add_page("Appearance & Behavior", |page| {
1896 page.item(SettingsPageItem::SectionHeader("Cursor")).item(
1897 SettingsPageItem::basic_item(
1898 "Cursor Shape",
1899 "Cursor shape for the editor",
1900 ),
1901 )
1902 })
1903 .build()
1904 });
1905
1906 actual.update(cx, |settings, cx| settings.search("cursor", window, cx));
1907
1908 (actual, expected)
1909 });
1910
1911 cx.cx.run_until_parked();
1912
1913 cx.update(|_window, cx| {
1914 let expected = expected.read(cx);
1915 let actual = actual.read(cx);
1916 expected.assert_search_results(&actual);
1917 })
1918 }
1919}