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