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::{NumberField, NumberFieldType};
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_number_field(*settings_field, file, window, cx)
381 })
382 .add_renderer::<u32>(|settings_field, file, _, window, cx| {
383 render_number_field(*settings_field, file, window, cx)
384 })
385 .add_renderer::<u64>(|settings_field, file, _, window, cx| {
386 render_number_field(*settings_field, file, window, cx)
387 })
388 .add_renderer::<usize>(|settings_field, file, _, window, cx| {
389 render_number_field(*settings_field, file, window, cx)
390 })
391 .add_renderer::<NonZero<usize>>(|settings_field, file, _, window, cx| {
392 render_number_field(*settings_field, file, window, cx)
393 })
394 .add_renderer::<NonZeroU32>(|settings_field, file, _, window, cx| {
395 render_number_field(*settings_field, file, window, cx)
396 })
397 .add_renderer::<CodeFade>(|settings_field, file, _, window, cx| {
398 render_number_field(*settings_field, file, window, cx)
399 })
400 .add_renderer::<FontWeight>(|settings_field, file, _, window, cx| {
401 render_number_field(*settings_field, file, window, cx)
402 })
403 .add_renderer::<settings::MinimumContrast>(|settings_field, file, _, window, cx| {
404 render_number_field(*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 /// Index into navbar_entries
494 navbar_entry: usize,
495 navbar_entries: Vec<NavBarEntry>,
496 list_handle: UniformListScrollHandle,
497 search_matches: Vec<Vec<bool>>,
498 scroll_handle: ScrollHandle,
499 focus_handle: FocusHandle,
500 navbar_focus_handle: FocusHandle,
501 content_focus_handle: FocusHandle,
502 files_focus_handle: FocusHandle,
503}
504
505struct SubPage {
506 link: SubPageLink,
507 section_header: &'static str,
508}
509
510#[derive(PartialEq, Debug)]
511struct NavBarEntry {
512 title: &'static str,
513 is_root: bool,
514 expanded: bool,
515 page_index: usize,
516 item_index: Option<usize>,
517}
518
519struct SettingsPage {
520 title: &'static str,
521 items: Vec<SettingsPageItem>,
522}
523
524#[derive(PartialEq)]
525enum SettingsPageItem {
526 SectionHeader(&'static str),
527 SettingItem(SettingItem),
528 SubPageLink(SubPageLink),
529}
530
531impl std::fmt::Debug for SettingsPageItem {
532 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
533 match self {
534 SettingsPageItem::SectionHeader(header) => write!(f, "SectionHeader({})", header),
535 SettingsPageItem::SettingItem(setting_item) => {
536 write!(f, "SettingItem({})", setting_item.title)
537 }
538 SettingsPageItem::SubPageLink(sub_page_link) => {
539 write!(f, "SubPageLink({})", sub_page_link.title)
540 }
541 }
542 }
543}
544
545impl SettingsPageItem {
546 fn render(
547 &self,
548 file: SettingsUiFile,
549 section_header: &'static str,
550 is_last: bool,
551 window: &mut Window,
552 cx: &mut Context<SettingsWindow>,
553 ) -> AnyElement {
554 match self {
555 SettingsPageItem::SectionHeader(header) => v_flex()
556 .w_full()
557 .gap_1()
558 .child(
559 Label::new(SharedString::new_static(header))
560 .size(LabelSize::XSmall)
561 .color(Color::Muted)
562 .buffer_font(cx),
563 )
564 .child(Divider::horizontal().color(ui::DividerColor::BorderVariant))
565 .into_any_element(),
566 SettingsPageItem::SettingItem(setting_item) => {
567 let renderer = cx.default_global::<SettingFieldRenderer>().clone();
568 let (found_in_file, found) = setting_item.field.file_set_in(file.clone(), cx);
569 let file_set_in = SettingsUiFile::from_settings(found_in_file);
570
571 h_flex()
572 .id(setting_item.title)
573 .w_full()
574 .gap_2()
575 .flex_wrap()
576 .justify_between()
577 .map(|this| {
578 if is_last {
579 this.pb_6()
580 } else {
581 this.pb_4()
582 .border_b_1()
583 .border_color(cx.theme().colors().border_variant)
584 }
585 })
586 .child(
587 v_flex()
588 .max_w_1_2()
589 .flex_shrink()
590 .child(
591 h_flex()
592 .w_full()
593 .gap_1()
594 .child(Label::new(SharedString::new_static(setting_item.title)))
595 .when_some(
596 file_set_in.filter(|file_set_in| file_set_in != &file),
597 |this, file_set_in| {
598 this.child(
599 Label::new(format!(
600 "— set in {}",
601 file_set_in.name()
602 ))
603 .color(Color::Muted)
604 .size(LabelSize::Small),
605 )
606 },
607 ),
608 )
609 .child(
610 Label::new(SharedString::new_static(setting_item.description))
611 .size(LabelSize::Small)
612 .color(Color::Muted),
613 ),
614 )
615 .child(if cfg!(debug_assertions) && !found {
616 Button::new("no-default-field", "NO DEFAULT")
617 .size(ButtonSize::Medium)
618 .icon(IconName::XCircle)
619 .icon_position(IconPosition::Start)
620 .icon_color(Color::Error)
621 .icon_size(IconSize::Small)
622 .style(ButtonStyle::Outlined)
623 .into_any_element()
624 } else {
625 renderer.render(
626 setting_item.field.as_ref(),
627 file,
628 setting_item.metadata.as_deref(),
629 window,
630 cx,
631 )
632 })
633 .into_any_element()
634 }
635 SettingsPageItem::SubPageLink(sub_page_link) => h_flex()
636 .id(sub_page_link.title)
637 .w_full()
638 .gap_2()
639 .flex_wrap()
640 .justify_between()
641 .when(!is_last, |this| {
642 this.pb_4()
643 .border_b_1()
644 .border_color(cx.theme().colors().border_variant)
645 })
646 .child(
647 v_flex()
648 .max_w_1_2()
649 .flex_shrink()
650 .child(Label::new(SharedString::new_static(sub_page_link.title))),
651 )
652 .child(
653 Button::new(("sub-page".into(), sub_page_link.title), "Configure")
654 .size(ButtonSize::Medium)
655 .icon(IconName::ChevronRight)
656 .icon_position(IconPosition::End)
657 .icon_color(Color::Muted)
658 .icon_size(IconSize::Small)
659 .style(ButtonStyle::Outlined),
660 )
661 .on_click({
662 let sub_page_link = sub_page_link.clone();
663 cx.listener(move |this, _, _, cx| {
664 this.push_sub_page(sub_page_link.clone(), section_header, cx)
665 })
666 })
667 .into_any_element(),
668 }
669 }
670}
671
672struct SettingItem {
673 title: &'static str,
674 description: &'static str,
675 field: Box<dyn AnySettingField>,
676 metadata: Option<Box<SettingsFieldMetadata>>,
677 files: FileMask,
678}
679
680#[derive(PartialEq, Eq, Clone, Copy)]
681struct FileMask(u8);
682
683impl std::fmt::Debug for FileMask {
684 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
685 write!(f, "FileMask(")?;
686 let mut items = vec![];
687
688 if self.contains(USER) {
689 items.push("USER");
690 }
691 if self.contains(LOCAL) {
692 items.push("LOCAL");
693 }
694 if self.contains(SERVER) {
695 items.push("SERVER");
696 }
697
698 write!(f, "{})", items.join(" | "))
699 }
700}
701
702const USER: FileMask = FileMask(1 << 0);
703const LOCAL: FileMask = FileMask(1 << 2);
704const SERVER: FileMask = FileMask(1 << 3);
705
706impl std::ops::BitAnd for FileMask {
707 type Output = Self;
708
709 fn bitand(self, other: Self) -> Self {
710 Self(self.0 & other.0)
711 }
712}
713
714impl std::ops::BitOr for FileMask {
715 type Output = Self;
716
717 fn bitor(self, other: Self) -> Self {
718 Self(self.0 | other.0)
719 }
720}
721
722impl FileMask {
723 fn contains(&self, other: FileMask) -> bool {
724 self.0 & other.0 != 0
725 }
726}
727
728impl PartialEq for SettingItem {
729 fn eq(&self, other: &Self) -> bool {
730 self.title == other.title
731 && self.description == other.description
732 && (match (&self.metadata, &other.metadata) {
733 (None, None) => true,
734 (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
735 _ => false,
736 })
737 }
738}
739
740#[derive(Clone)]
741struct SubPageLink {
742 title: &'static str,
743 files: FileMask,
744 render: Arc<
745 dyn Fn(&mut SettingsWindow, &mut Window, &mut Context<SettingsWindow>) -> AnyElement
746 + 'static
747 + Send
748 + Sync,
749 >,
750}
751
752impl PartialEq for SubPageLink {
753 fn eq(&self, other: &Self) -> bool {
754 self.title == other.title
755 }
756}
757
758#[allow(unused)]
759#[derive(Clone, PartialEq)]
760enum SettingsUiFile {
761 User, // Uses all settings.
762 Local((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
763 Server(&'static str), // Uses a special name, and the user settings
764}
765
766impl SettingsUiFile {
767 fn name(&self) -> SharedString {
768 match self {
769 SettingsUiFile::User => SharedString::new_static("User"),
770 // TODO is PathStyle::local() ever not appropriate?
771 SettingsUiFile::Local((_, path)) => {
772 format!("Local ({})", path.display(PathStyle::local())).into()
773 }
774 SettingsUiFile::Server(file) => format!("Server ({})", file).into(),
775 }
776 }
777
778 fn from_settings(file: settings::SettingsFile) -> Option<Self> {
779 Some(match file {
780 settings::SettingsFile::User => SettingsUiFile::User,
781 settings::SettingsFile::Local(location) => SettingsUiFile::Local(location),
782 settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
783 settings::SettingsFile::Default => return None,
784 })
785 }
786
787 fn to_settings(&self) -> settings::SettingsFile {
788 match self {
789 SettingsUiFile::User => settings::SettingsFile::User,
790 SettingsUiFile::Local(location) => settings::SettingsFile::Local(location.clone()),
791 SettingsUiFile::Server(_) => settings::SettingsFile::Server,
792 }
793 }
794
795 fn mask(&self) -> FileMask {
796 match self {
797 SettingsUiFile::User => USER,
798 SettingsUiFile::Local(_) => LOCAL,
799 SettingsUiFile::Server(_) => SERVER,
800 }
801 }
802}
803
804impl SettingsWindow {
805 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
806 let font_family_cache = theme::FontFamilyCache::global(cx);
807
808 cx.spawn(async move |this, cx| {
809 font_family_cache.prefetch(cx).await;
810 this.update(cx, |_, cx| {
811 cx.notify();
812 })
813 })
814 .detach();
815
816 let current_file = SettingsUiFile::User;
817 let search_bar = cx.new(|cx| {
818 let mut editor = Editor::single_line(window, cx);
819 editor.set_placeholder_text("Search settings…", window, cx);
820 editor
821 });
822
823 cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
824 let EditorEvent::Edited { transaction_id: _ } = event else {
825 return;
826 };
827
828 this.update_matches(cx);
829 })
830 .detach();
831
832 cx.observe_global_in::<SettingsStore>(window, move |this, _, cx| {
833 this.fetch_files(cx);
834 cx.notify();
835 })
836 .detach();
837
838 let mut this = Self {
839 files: vec![],
840 current_file: current_file,
841 pages: vec![],
842 navbar_entries: vec![],
843 navbar_entry: 0,
844 list_handle: UniformListScrollHandle::default(),
845 search_bar,
846 search_task: None,
847 search_matches: vec![],
848 scroll_handle: ScrollHandle::new(),
849 focus_handle: cx.focus_handle(),
850 navbar_focus_handle: cx
851 .focus_handle()
852 .tab_index(NAVBAR_CONTAINER_TAB_INDEX)
853 .tab_stop(false),
854 content_focus_handle: cx
855 .focus_handle()
856 .tab_index(CONTENT_CONTAINER_TAB_INDEX)
857 .tab_stop(false),
858 files_focus_handle: cx.focus_handle().tab_stop(false),
859 };
860
861 this.fetch_files(cx);
862 this.build_ui(cx);
863
864 this.search_bar.update(cx, |editor, cx| {
865 editor.focus_handle(cx).focus(window);
866 });
867
868 this
869 }
870
871 fn toggle_navbar_entry(&mut self, ix: usize) {
872 // We can only toggle root entries
873 if !self.navbar_entries[ix].is_root {
874 return;
875 }
876
877 let toggle_page_index = self.page_index_from_navbar_index(ix);
878 let selected_page_index = self.page_index_from_navbar_index(self.navbar_entry);
879
880 let expanded = &mut self.navbar_entries[ix].expanded;
881 *expanded = !*expanded;
882 // if currently selected page is a child of the parent page we are folding,
883 // set the current page to the parent page
884 if !*expanded && selected_page_index == toggle_page_index {
885 self.navbar_entry = ix;
886 }
887 }
888
889 fn build_navbar(&mut self) {
890 let mut prev_navbar_state = HashMap::new();
891 let mut root_entry = "";
892 let mut prev_selected_entry = None;
893 for (index, entry) in self.navbar_entries.iter().enumerate() {
894 let sub_entry_title;
895 if entry.is_root {
896 sub_entry_title = None;
897 root_entry = entry.title;
898 } else {
899 sub_entry_title = Some(entry.title);
900 }
901 let key = (root_entry, sub_entry_title);
902 if index == self.navbar_entry {
903 prev_selected_entry = Some(key);
904 }
905 prev_navbar_state.insert(key, entry.expanded);
906 }
907
908 let mut navbar_entries = Vec::with_capacity(self.navbar_entries.len());
909 for (page_index, page) in self.pages.iter().enumerate() {
910 navbar_entries.push(NavBarEntry {
911 title: page.title,
912 is_root: true,
913 expanded: false,
914 page_index,
915 item_index: None,
916 });
917
918 for (item_index, item) in page.items.iter().enumerate() {
919 let SettingsPageItem::SectionHeader(title) = item else {
920 continue;
921 };
922 navbar_entries.push(NavBarEntry {
923 title,
924 is_root: false,
925 expanded: false,
926 page_index,
927 item_index: Some(item_index),
928 });
929 }
930 }
931
932 let mut root_entry = "";
933 let mut found_nav_entry = false;
934 for (index, entry) in navbar_entries.iter_mut().enumerate() {
935 let sub_entry_title;
936 if entry.is_root {
937 root_entry = entry.title;
938 sub_entry_title = None;
939 } else {
940 sub_entry_title = Some(entry.title);
941 };
942 let key = (root_entry, sub_entry_title);
943 if Some(key) == prev_selected_entry {
944 self.navbar_entry = index;
945 found_nav_entry = true;
946 }
947 entry.expanded = *prev_navbar_state.get(&key).unwrap_or(&false);
948 }
949 if !found_nav_entry {
950 self.navbar_entry = 0;
951 }
952 self.navbar_entries = navbar_entries;
953 }
954
955 fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
956 let mut index = 0;
957 let entries = &self.navbar_entries;
958 let search_matches = &self.search_matches;
959 std::iter::from_fn(move || {
960 while index < entries.len() {
961 let entry = &entries[index];
962 let included_in_search = if let Some(item_index) = entry.item_index {
963 search_matches[entry.page_index][item_index]
964 } else {
965 search_matches[entry.page_index].iter().any(|b| *b)
966 || search_matches[entry.page_index].is_empty()
967 };
968 if included_in_search {
969 break;
970 }
971 index += 1;
972 }
973 if index >= self.navbar_entries.len() {
974 return None;
975 }
976 let entry = &entries[index];
977 let entry_index = index;
978
979 index += 1;
980 if entry.is_root && !entry.expanded {
981 while index < entries.len() {
982 if entries[index].is_root {
983 break;
984 }
985 index += 1;
986 }
987 }
988
989 return Some((entry_index, entry));
990 })
991 }
992
993 fn filter_matches_to_file(&mut self) {
994 let current_file = self.current_file.mask();
995 for (page, page_filter) in std::iter::zip(&self.pages, &mut self.search_matches) {
996 let mut header_index = 0;
997 let mut any_found_since_last_header = true;
998
999 for (index, item) in page.items.iter().enumerate() {
1000 match item {
1001 SettingsPageItem::SectionHeader(_) => {
1002 if !any_found_since_last_header {
1003 page_filter[header_index] = false;
1004 }
1005 header_index = index;
1006 any_found_since_last_header = false;
1007 }
1008 SettingsPageItem::SettingItem(setting_item) => {
1009 if !setting_item.files.contains(current_file) {
1010 page_filter[index] = false;
1011 } else {
1012 any_found_since_last_header = true;
1013 }
1014 }
1015 SettingsPageItem::SubPageLink(sub_page_link) => {
1016 if !sub_page_link.files.contains(current_file) {
1017 page_filter[index] = false;
1018 } else {
1019 any_found_since_last_header = true;
1020 }
1021 }
1022 }
1023 }
1024 if let Some(last_header) = page_filter.get_mut(header_index)
1025 && !any_found_since_last_header
1026 {
1027 *last_header = false;
1028 }
1029 }
1030 }
1031
1032 fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
1033 self.search_task.take();
1034 let query = self.search_bar.read(cx).text(cx);
1035 if query.is_empty() {
1036 for page in &mut self.search_matches {
1037 page.fill(true);
1038 }
1039 self.filter_matches_to_file();
1040 cx.notify();
1041 return;
1042 }
1043
1044 struct ItemKey {
1045 page_index: usize,
1046 header_index: usize,
1047 item_index: usize,
1048 }
1049 let mut key_lut: Vec<ItemKey> = vec![];
1050 let mut candidates = Vec::default();
1051
1052 for (page_index, page) in self.pages.iter().enumerate() {
1053 let mut header_index = 0;
1054 for (item_index, item) in page.items.iter().enumerate() {
1055 let key_index = key_lut.len();
1056 match item {
1057 SettingsPageItem::SettingItem(item) => {
1058 candidates.push(StringMatchCandidate::new(key_index, item.title));
1059 candidates.push(StringMatchCandidate::new(key_index, item.description));
1060 }
1061 SettingsPageItem::SectionHeader(header) => {
1062 candidates.push(StringMatchCandidate::new(key_index, header));
1063 header_index = item_index;
1064 }
1065 SettingsPageItem::SubPageLink(sub_page_link) => {
1066 candidates.push(StringMatchCandidate::new(key_index, sub_page_link.title));
1067 }
1068 }
1069 key_lut.push(ItemKey {
1070 page_index,
1071 header_index,
1072 item_index,
1073 });
1074 }
1075 }
1076 let atomic_bool = AtomicBool::new(false);
1077
1078 self.search_task = Some(cx.spawn(async move |this, cx| {
1079 let string_matches = fuzzy::match_strings(
1080 candidates.as_slice(),
1081 &query,
1082 false,
1083 true,
1084 candidates.len(),
1085 &atomic_bool,
1086 cx.background_executor().clone(),
1087 );
1088 let string_matches = string_matches.await;
1089
1090 this.update(cx, |this, cx| {
1091 for page in &mut this.search_matches {
1092 page.fill(false);
1093 }
1094
1095 for string_match in string_matches {
1096 let ItemKey {
1097 page_index,
1098 header_index,
1099 item_index,
1100 } = key_lut[string_match.candidate_id];
1101 let page = &mut this.search_matches[page_index];
1102 page[header_index] = true;
1103 page[item_index] = true;
1104 }
1105 this.filter_matches_to_file();
1106 let first_navbar_entry_index = this
1107 .visible_navbar_entries()
1108 .next()
1109 .map(|e| e.0)
1110 .unwrap_or(0);
1111 this.navbar_entry = first_navbar_entry_index;
1112 cx.notify();
1113 })
1114 .ok();
1115 }));
1116 }
1117
1118 fn build_search_matches(&mut self) {
1119 self.search_matches = self
1120 .pages
1121 .iter()
1122 .map(|page| vec![true; page.items.len()])
1123 .collect::<Vec<_>>();
1124 }
1125
1126 fn build_ui(&mut self, cx: &mut Context<SettingsWindow>) {
1127 if self.pages.is_empty() {
1128 self.pages = page_data::settings_data();
1129 }
1130 self.build_search_matches();
1131 self.build_navbar();
1132
1133 self.update_matches(cx);
1134
1135 cx.notify();
1136 }
1137
1138 fn fetch_files(&mut self, cx: &mut Context<SettingsWindow>) {
1139 let prev_files = self.files.clone();
1140 let settings_store = cx.global::<SettingsStore>();
1141 let mut ui_files = vec![];
1142 let all_files = settings_store.get_all_files();
1143 for file in all_files {
1144 let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
1145 continue;
1146 };
1147 let focus_handle = prev_files
1148 .iter()
1149 .find_map(|(prev_file, handle)| {
1150 (prev_file == &settings_ui_file).then(|| handle.clone())
1151 })
1152 .unwrap_or_else(|| cx.focus_handle());
1153 ui_files.push((settings_ui_file, focus_handle));
1154 }
1155 ui_files.reverse();
1156 self.files = ui_files;
1157 let current_file_still_exists = self
1158 .files
1159 .iter()
1160 .any(|(file, _)| file == &self.current_file);
1161 if !current_file_still_exists {
1162 self.change_file(0, cx);
1163 }
1164 }
1165
1166 fn change_file(&mut self, ix: usize, cx: &mut Context<SettingsWindow>) {
1167 if ix >= self.files.len() {
1168 self.current_file = SettingsUiFile::User;
1169 return;
1170 }
1171 if self.files[ix].0 == self.current_file {
1172 return;
1173 }
1174 self.current_file = self.files[ix].0.clone();
1175 // self.navbar_entry = 0;
1176 self.build_ui(cx);
1177 }
1178
1179 fn render_files(
1180 &self,
1181 _window: &mut Window,
1182 cx: &mut Context<SettingsWindow>,
1183 ) -> impl IntoElement {
1184 h_flex()
1185 .w_full()
1186 .gap_1()
1187 .justify_between()
1188 .child(
1189 h_flex()
1190 .id("file_buttons_container")
1191 .w_64() // Temporary fix until long-term solution is a fixed set of buttons representing a file location (User, Project, and Remote)
1192 .gap_1()
1193 .overflow_x_scroll()
1194 .children(
1195 self.files
1196 .iter()
1197 .enumerate()
1198 .map(|(ix, (file, focus_handle))| {
1199 Button::new(ix, file.name())
1200 .toggle_state(file == &self.current_file)
1201 .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
1202 .track_focus(focus_handle)
1203 .on_click(cx.listener(
1204 move |this, evt: &gpui::ClickEvent, window, cx| {
1205 this.change_file(ix, cx);
1206 if evt.is_keyboard() {
1207 this.focus_first_nav_item(window, cx);
1208 }
1209 },
1210 ))
1211 }),
1212 ),
1213 )
1214 .child(Button::new("temp", "Edit in settings.json").style(ButtonStyle::Outlined)) // This should be replaced by the actual, functioning button
1215 }
1216
1217 fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
1218 h_flex()
1219 .py_1()
1220 .px_1p5()
1221 .gap_1p5()
1222 .rounded_sm()
1223 .bg(cx.theme().colors().editor_background)
1224 .border_1()
1225 .border_color(cx.theme().colors().border)
1226 .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
1227 .child(self.search_bar.clone())
1228 }
1229
1230 fn render_nav(
1231 &self,
1232 window: &mut Window,
1233 cx: &mut Context<SettingsWindow>,
1234 ) -> impl IntoElement {
1235 let visible_count = self.visible_navbar_entries().count();
1236 let nav_background = cx.theme().colors().panel_background;
1237 let focus_keybind_label = if self.navbar_focus_handle.contains_focused(window, cx) {
1238 "Focus Content"
1239 } else {
1240 "Focus Navbar"
1241 };
1242
1243 v_flex()
1244 .w_64()
1245 .p_2p5()
1246 .pt_10()
1247 .gap_3()
1248 .flex_none()
1249 .border_r_1()
1250 .border_color(cx.theme().colors().border)
1251 .bg(nav_background)
1252 .child(self.render_search(window, cx))
1253 .child(
1254 v_flex()
1255 .flex_grow()
1256 .track_focus(&self.navbar_focus_handle)
1257 .tab_group()
1258 .tab_index(NAVBAR_GROUP_TAB_INDEX)
1259 .child(
1260 uniform_list(
1261 "settings-ui-nav-bar",
1262 visible_count,
1263 cx.processor(move |this, range: Range<usize>, _, cx| {
1264 let entries: Vec<_> = this.visible_navbar_entries().collect();
1265 range
1266 .filter_map(|ix| entries.get(ix).copied())
1267 .map(|(ix, entry)| {
1268 TreeViewItem::new(
1269 ("settings-ui-navbar-entry", ix),
1270 entry.title,
1271 )
1272 .tab_index(0)
1273 .root_item(entry.is_root)
1274 .toggle_state(this.is_navbar_entry_selected(ix))
1275 .when(entry.is_root, |item| {
1276 item.expanded(entry.expanded).on_toggle(cx.listener(
1277 move |this, _, _, cx| {
1278 this.toggle_navbar_entry(ix);
1279 cx.notify();
1280 },
1281 ))
1282 })
1283 .on_click(cx.listener(
1284 move |this, evt: &gpui::ClickEvent, window, cx| {
1285 this.navbar_entry = ix;
1286
1287 if !this.navbar_entries[ix].is_root {
1288 let mut selected_page_ix = ix;
1289
1290 while !this.navbar_entries[selected_page_ix]
1291 .is_root
1292 {
1293 selected_page_ix -= 1;
1294 }
1295
1296 let section_header = ix - selected_page_ix;
1297
1298 if let Some(section_index) = this
1299 .page_items()
1300 .enumerate()
1301 .filter(|item| {
1302 matches!(
1303 item.1,
1304 SettingsPageItem::SectionHeader(_)
1305 )
1306 })
1307 .take(section_header)
1308 .last()
1309 .map(|pair| pair.0)
1310 {
1311 this.scroll_handle
1312 .scroll_to_top_of_item(section_index);
1313 }
1314 }
1315
1316 if evt.is_keyboard() {
1317 // todo(settings_ui): Focus the actual item and scroll to it
1318 this.focus_first_content_item(window, cx);
1319 }
1320 cx.notify();
1321 },
1322 ))
1323 .into_any_element()
1324 })
1325 .collect()
1326 }),
1327 )
1328 .track_scroll(self.list_handle.clone())
1329 .flex_grow(),
1330 )
1331 .vertical_scrollbar_for(self.list_handle.clone(), window, cx),
1332 )
1333 .child(
1334 h_flex()
1335 .w_full()
1336 .p_2()
1337 .pb_0p5()
1338 .border_t_1()
1339 .border_color(cx.theme().colors().border_variant)
1340 .children(
1341 KeyBinding::for_action(&ToggleFocusNav, window, cx).map(|this| {
1342 KeybindingHint::new(
1343 this,
1344 cx.theme().colors().surface_background.opacity(0.5),
1345 )
1346 .suffix(focus_keybind_label)
1347 }),
1348 ),
1349 )
1350 }
1351
1352 fn focus_first_nav_item(&self, window: &mut Window, cx: &mut Context<Self>) {
1353 self.navbar_focus_handle.focus(window);
1354 window.focus_next();
1355 cx.notify();
1356 }
1357
1358 fn focus_first_content_item(&self, window: &mut Window, cx: &mut Context<Self>) {
1359 self.content_focus_handle.focus(window);
1360 window.focus_next();
1361 cx.notify();
1362 }
1363
1364 fn page_items(&self) -> impl Iterator<Item = &SettingsPageItem> {
1365 let page_idx = self.current_page_index();
1366
1367 self.current_page()
1368 .items
1369 .iter()
1370 .enumerate()
1371 .filter_map(move |(item_index, item)| {
1372 self.search_matches[page_idx][item_index].then_some(item)
1373 })
1374 }
1375
1376 fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
1377 let mut items = vec![];
1378 items.push(self.current_page().title);
1379 items.extend(
1380 sub_page_stack()
1381 .iter()
1382 .flat_map(|page| [page.section_header, page.link.title]),
1383 );
1384
1385 let last = items.pop().unwrap();
1386 h_flex()
1387 .gap_1()
1388 .children(
1389 items
1390 .into_iter()
1391 .flat_map(|item| [item, "/"])
1392 .map(|item| Label::new(item).color(Color::Muted)),
1393 )
1394 .child(Label::new(last))
1395 }
1396
1397 fn render_page_items<'a, Items: Iterator<Item = &'a SettingsPageItem>>(
1398 &self,
1399 items: Items,
1400 window: &mut Window,
1401 cx: &mut Context<SettingsWindow>,
1402 ) -> impl IntoElement {
1403 let mut page_content = v_flex()
1404 .id("settings-ui-page")
1405 .size_full()
1406 .gap_4()
1407 .overflow_y_scroll()
1408 .track_scroll(&self.scroll_handle);
1409
1410 let items: Vec<_> = items.collect();
1411 let items_len = items.len();
1412 let mut section_header = None;
1413
1414 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
1415 let has_no_results = items_len == 0 && has_active_search;
1416
1417 if has_no_results {
1418 let search_query = self.search_bar.read(cx).text(cx);
1419 page_content = page_content.child(
1420 v_flex()
1421 .size_full()
1422 .items_center()
1423 .justify_center()
1424 .gap_1()
1425 .child(div().child("No Results"))
1426 .child(
1427 div()
1428 .text_sm()
1429 .text_color(cx.theme().colors().text_muted)
1430 .child(format!("No settings match \"{}\"", search_query)),
1431 ),
1432 )
1433 } else {
1434 let last_non_header_index = items
1435 .iter()
1436 .enumerate()
1437 .rev()
1438 .find(|(_, item)| !matches!(item, SettingsPageItem::SectionHeader(_)))
1439 .map(|(index, _)| index);
1440
1441 page_content =
1442 page_content.children(items.clone().into_iter().enumerate().map(|(index, item)| {
1443 let no_bottom_border = items
1444 .get(index + 1)
1445 .map(|next_item| matches!(next_item, SettingsPageItem::SectionHeader(_)))
1446 .unwrap_or(false);
1447 let is_last = Some(index) == last_non_header_index;
1448
1449 if let SettingsPageItem::SectionHeader(header) = item {
1450 section_header = Some(*header);
1451 }
1452 item.render(
1453 self.current_file.clone(),
1454 section_header.expect("All items rendered after a section header"),
1455 no_bottom_border || is_last,
1456 window,
1457 cx,
1458 )
1459 }))
1460 }
1461 page_content
1462 }
1463
1464 fn render_page(
1465 &mut self,
1466 window: &mut Window,
1467 cx: &mut Context<SettingsWindow>,
1468 ) -> impl IntoElement {
1469 let page_header;
1470 let page_content;
1471
1472 if sub_page_stack().len() == 0 {
1473 page_header = self.render_files(window, cx).into_any_element();
1474 page_content = self
1475 .render_page_items(self.page_items(), window, cx)
1476 .into_any_element();
1477 } else {
1478 page_header = h_flex()
1479 .ml_neg_1p5()
1480 .gap_1()
1481 .child(
1482 IconButton::new("back-btn", IconName::ArrowLeft)
1483 .icon_size(IconSize::Small)
1484 .shape(IconButtonShape::Square)
1485 .on_click(cx.listener(|this, _, _, cx| {
1486 this.pop_sub_page(cx);
1487 })),
1488 )
1489 .child(self.render_sub_page_breadcrumbs())
1490 .into_any_element();
1491
1492 let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
1493 page_content = (active_page_render_fn)(self, window, cx);
1494 }
1495
1496 return v_flex()
1497 .w_full()
1498 .pt_4()
1499 .pb_6()
1500 .px_6()
1501 .gap_4()
1502 .track_focus(&self.content_focus_handle)
1503 .bg(cx.theme().colors().editor_background)
1504 .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx)
1505 .child(page_header)
1506 .child(
1507 div()
1508 .size_full()
1509 .track_focus(&self.content_focus_handle)
1510 .tab_group()
1511 .tab_index(CONTENT_GROUP_TAB_INDEX)
1512 .child(page_content),
1513 );
1514 }
1515
1516 fn current_page_index(&self) -> usize {
1517 self.page_index_from_navbar_index(self.navbar_entry)
1518 }
1519
1520 fn current_page(&self) -> &SettingsPage {
1521 &self.pages[self.current_page_index()]
1522 }
1523
1524 fn page_index_from_navbar_index(&self, index: usize) -> usize {
1525 if self.navbar_entries.is_empty() {
1526 return 0;
1527 }
1528
1529 self.navbar_entries[index].page_index
1530 }
1531
1532 fn is_navbar_entry_selected(&self, ix: usize) -> bool {
1533 ix == self.navbar_entry
1534 }
1535
1536 fn push_sub_page(
1537 &mut self,
1538 sub_page_link: SubPageLink,
1539 section_header: &'static str,
1540 cx: &mut Context<SettingsWindow>,
1541 ) {
1542 sub_page_stack_mut().push(SubPage {
1543 link: sub_page_link,
1544 section_header,
1545 });
1546 cx.notify();
1547 }
1548
1549 fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
1550 sub_page_stack_mut().pop();
1551 cx.notify();
1552 }
1553
1554 fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
1555 if let Some((_, handle)) = self.files.get(index) {
1556 handle.focus(window);
1557 }
1558 }
1559
1560 fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
1561 if self.files_focus_handle.contains_focused(window, cx)
1562 && let Some(index) = self
1563 .files
1564 .iter()
1565 .position(|(_, handle)| handle.is_focused(window))
1566 {
1567 return index;
1568 }
1569 if let Some(current_file_index) = self
1570 .files
1571 .iter()
1572 .position(|(file, _)| file == &self.current_file)
1573 {
1574 return current_file_index;
1575 }
1576 0
1577 }
1578}
1579
1580impl Render for SettingsWindow {
1581 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1582 let ui_font = theme::setup_ui_font(window, cx);
1583
1584 div()
1585 .id("settings-window")
1586 .key_context("SettingsWindow")
1587 .track_focus(&self.focus_handle)
1588 .on_action(|_: &Minimize, window, _cx| {
1589 window.minimize_window();
1590 })
1591 .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
1592 this.search_bar.focus_handle(cx).focus(window);
1593 }))
1594 .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
1595 if this.navbar_focus_handle.contains_focused(window, cx) {
1596 this.focus_first_content_item(window, cx);
1597 } else {
1598 this.focus_first_nav_item(window, cx);
1599 }
1600 }))
1601 .on_action(
1602 cx.listener(|this, FocusFile(file_index): &FocusFile, window, _| {
1603 this.focus_file_at_index(*file_index as usize, window);
1604 }),
1605 )
1606 .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
1607 let next_index = usize::min(
1608 this.focused_file_index(window, cx) + 1,
1609 this.files.len().saturating_sub(1),
1610 );
1611 this.focus_file_at_index(next_index, window);
1612 }))
1613 .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
1614 let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
1615 this.focus_file_at_index(prev_index, window);
1616 }))
1617 .on_action(|_: &menu::SelectNext, window, _| {
1618 window.focus_next();
1619 })
1620 .on_action(|_: &menu::SelectPrevious, window, _| {
1621 window.focus_prev();
1622 })
1623 .flex()
1624 .flex_row()
1625 .size_full()
1626 .font(ui_font)
1627 .bg(cx.theme().colors().background)
1628 .text_color(cx.theme().colors().text)
1629 .child(self.render_nav(window, cx))
1630 .child(self.render_page(window, cx))
1631 }
1632}
1633
1634fn update_settings_file(
1635 file: SettingsUiFile,
1636 cx: &mut App,
1637 update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
1638) -> Result<()> {
1639 match file {
1640 SettingsUiFile::Local((worktree_id, rel_path)) => {
1641 fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
1642 workspace::AppState::global(cx)
1643 .upgrade()
1644 .map(|app_state| {
1645 app_state
1646 .workspace_store
1647 .read(cx)
1648 .workspaces()
1649 .iter()
1650 .filter_map(|workspace| {
1651 Some(workspace.read(cx).ok()?.project().clone())
1652 })
1653 })
1654 .into_iter()
1655 .flatten()
1656 }
1657 let rel_path = rel_path.join(paths::local_settings_file_relative_path());
1658 let project = all_projects(cx).find(|project| {
1659 project.read_with(cx, |project, cx| {
1660 project.contains_local_settings_file(worktree_id, &rel_path, cx)
1661 })
1662 });
1663 let Some(project) = project else {
1664 anyhow::bail!(
1665 "Could not find worktree containing settings file: {}",
1666 &rel_path.display(PathStyle::local())
1667 );
1668 };
1669 project.update(cx, |project, cx| {
1670 project.update_local_settings_file(worktree_id, rel_path, cx, update);
1671 });
1672 return Ok(());
1673 }
1674 SettingsUiFile::User => {
1675 // todo(settings_ui) error?
1676 SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
1677 Ok(())
1678 }
1679 SettingsUiFile::Server(_) => unimplemented!(),
1680 }
1681}
1682
1683fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
1684 field: SettingField<T>,
1685 file: SettingsUiFile,
1686 metadata: Option<&SettingsFieldMetadata>,
1687 cx: &mut App,
1688) -> AnyElement {
1689 let (_, initial_text) =
1690 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1691 let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
1692
1693 SettingsEditor::new()
1694 .tab_index(0)
1695 .when_some(initial_text, |editor, text| {
1696 editor.with_initial_text(text.as_ref().to_string())
1697 })
1698 .when_some(
1699 metadata.and_then(|metadata| metadata.placeholder),
1700 |editor, placeholder| editor.with_placeholder(placeholder),
1701 )
1702 .on_confirm({
1703 move |new_text, cx| {
1704 update_settings_file(file.clone(), cx, move |settings, _cx| {
1705 *(field.pick_mut)(settings) = new_text.map(Into::into);
1706 })
1707 .log_err(); // todo(settings_ui) don't log err
1708 }
1709 })
1710 .into_any_element()
1711}
1712
1713fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
1714 field: SettingField<B>,
1715 file: SettingsUiFile,
1716 cx: &mut App,
1717) -> AnyElement {
1718 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1719
1720 let toggle_state = if value.copied().map_or(false, Into::into) {
1721 ToggleState::Selected
1722 } else {
1723 ToggleState::Unselected
1724 };
1725
1726 Switch::new("toggle_button", toggle_state)
1727 .color(ui::SwitchColor::Accent)
1728 .on_click({
1729 move |state, _window, cx| {
1730 let state = *state == ui::ToggleState::Selected;
1731 update_settings_file(file.clone(), cx, move |settings, _cx| {
1732 *(field.pick_mut)(settings) = Some(state.into());
1733 })
1734 .log_err(); // todo(settings_ui) don't log err
1735 }
1736 })
1737 .tab_index(0_isize)
1738 .color(SwitchColor::Accent)
1739 .into_any_element()
1740}
1741
1742fn render_font_picker(
1743 field: SettingField<settings::FontFamilyName>,
1744 file: SettingsUiFile,
1745 window: &mut Window,
1746 cx: &mut App,
1747) -> AnyElement {
1748 let current_value = SettingsStore::global(cx)
1749 .get_value_from_file(file.to_settings(), field.pick)
1750 .1
1751 .cloned()
1752 .unwrap_or_else(|| SharedString::default().into());
1753
1754 let font_picker = cx.new(|cx| {
1755 ui_input::font_picker(
1756 current_value.clone().into(),
1757 move |font_name, cx| {
1758 update_settings_file(file.clone(), cx, move |settings, _cx| {
1759 *(field.pick_mut)(settings) = Some(font_name.into());
1760 })
1761 .log_err(); // todo(settings_ui) don't log err
1762 },
1763 window,
1764 cx,
1765 )
1766 });
1767
1768 PopoverMenu::new("font-picker")
1769 .menu(move |_window, _cx| Some(font_picker.clone()))
1770 .trigger(
1771 Button::new("font-family-button", current_value)
1772 .tab_index(0_isize)
1773 .style(ButtonStyle::Outlined)
1774 .size(ButtonSize::Medium)
1775 .icon(IconName::ChevronUpDown)
1776 .icon_color(Color::Muted)
1777 .icon_size(IconSize::Small)
1778 .icon_position(IconPosition::End),
1779 )
1780 .anchor(gpui::Corner::TopLeft)
1781 .offset(gpui::Point {
1782 x: px(0.0),
1783 y: px(2.0),
1784 })
1785 .with_handle(ui::PopoverMenuHandle::default())
1786 .into_any_element()
1787}
1788
1789fn render_number_field<T: NumberFieldType + Send + Sync>(
1790 field: SettingField<T>,
1791 file: SettingsUiFile,
1792 window: &mut Window,
1793 cx: &mut App,
1794) -> AnyElement {
1795 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1796 let value = value.copied().unwrap_or_else(T::min_value);
1797 NumberField::new("numeric_stepper", value, window, cx)
1798 .on_change({
1799 move |value, _window, cx| {
1800 let value = *value;
1801 update_settings_file(file.clone(), cx, move |settings, _cx| {
1802 *(field.pick_mut)(settings) = Some(value);
1803 })
1804 .log_err(); // todo(settings_ui) don't log err
1805 }
1806 })
1807 .tab_index(0)
1808 .into_any_element()
1809}
1810
1811fn render_dropdown<T>(
1812 field: SettingField<T>,
1813 file: SettingsUiFile,
1814 window: &mut Window,
1815 cx: &mut App,
1816) -> AnyElement
1817where
1818 T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
1819{
1820 let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
1821 let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
1822
1823 let (_, current_value) =
1824 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
1825 let current_value = current_value.copied().unwrap_or(variants()[0]);
1826
1827 let current_value_label =
1828 labels()[variants().iter().position(|v| *v == current_value).unwrap()];
1829
1830 DropdownMenu::new(
1831 "dropdown",
1832 current_value_label.to_title_case(),
1833 ContextMenu::build(window, cx, move |mut menu, _, _| {
1834 for (&value, &label) in std::iter::zip(variants(), labels()) {
1835 let file = file.clone();
1836 menu = menu.toggleable_entry(
1837 label.to_title_case(),
1838 value == current_value,
1839 IconPosition::Start,
1840 None,
1841 move |_, cx| {
1842 if value == current_value {
1843 return;
1844 }
1845 update_settings_file(file.clone(), cx, move |settings, _cx| {
1846 *(field.pick_mut)(settings) = Some(value);
1847 })
1848 .log_err(); // todo(settings_ui) don't log err
1849 },
1850 );
1851 }
1852 menu
1853 }),
1854 )
1855 .trigger_size(ButtonSize::Medium)
1856 .style(DropdownStyle::Outlined)
1857 .offset(gpui::Point {
1858 x: px(0.0),
1859 y: px(2.0),
1860 })
1861 .tab_index(0)
1862 .into_any_element()
1863}
1864
1865#[cfg(test)]
1866mod test {
1867
1868 use super::*;
1869
1870 impl SettingsWindow {
1871 fn navbar_entry(&self) -> usize {
1872 self.navbar_entry
1873 }
1874
1875 fn new_builder(window: &mut Window, cx: &mut Context<Self>) -> Self {
1876 let mut this = Self::new(window, cx);
1877 this.navbar_entries.clear();
1878 this.pages.clear();
1879 this
1880 }
1881
1882 fn build(mut self) -> Self {
1883 self.build_search_matches();
1884 self.build_navbar();
1885 self
1886 }
1887
1888 fn add_page(
1889 mut self,
1890 title: &'static str,
1891 build_page: impl Fn(SettingsPage) -> SettingsPage,
1892 ) -> Self {
1893 let page = SettingsPage {
1894 title,
1895 items: Vec::default(),
1896 };
1897
1898 self.pages.push(build_page(page));
1899 self
1900 }
1901
1902 fn search(&mut self, search_query: &str, window: &mut Window, cx: &mut Context<Self>) {
1903 self.search_task.take();
1904 self.search_bar.update(cx, |editor, cx| {
1905 editor.set_text(search_query, window, cx);
1906 });
1907 self.update_matches(cx);
1908 }
1909
1910 fn assert_search_results(&self, other: &Self) {
1911 // page index could be different because of filtered out pages
1912 #[derive(Debug, PartialEq)]
1913 struct EntryMinimal {
1914 is_root: bool,
1915 title: &'static str,
1916 }
1917 pretty_assertions::assert_eq!(
1918 other
1919 .visible_navbar_entries()
1920 .map(|(_, entry)| EntryMinimal {
1921 is_root: entry.is_root,
1922 title: entry.title,
1923 })
1924 .collect::<Vec<_>>(),
1925 self.visible_navbar_entries()
1926 .map(|(_, entry)| EntryMinimal {
1927 is_root: entry.is_root,
1928 title: entry.title,
1929 })
1930 .collect::<Vec<_>>(),
1931 );
1932 assert_eq!(
1933 self.current_page().items.iter().collect::<Vec<_>>(),
1934 other.page_items().collect::<Vec<_>>()
1935 );
1936 }
1937 }
1938
1939 impl SettingsPage {
1940 fn item(mut self, item: SettingsPageItem) -> Self {
1941 self.items.push(item);
1942 self
1943 }
1944 }
1945
1946 impl SettingsPageItem {
1947 fn basic_item(title: &'static str, description: &'static str) -> Self {
1948 SettingsPageItem::SettingItem(SettingItem {
1949 files: USER,
1950 title,
1951 description,
1952 field: Box::new(SettingField {
1953 pick: |settings_content| &settings_content.auto_update,
1954 pick_mut: |settings_content| &mut settings_content.auto_update,
1955 }),
1956 metadata: None,
1957 })
1958 }
1959 }
1960
1961 fn register_settings(cx: &mut App) {
1962 settings::init(cx);
1963 theme::init(theme::LoadThemes::JustBase, cx);
1964 workspace::init_settings(cx);
1965 project::Project::init_settings(cx);
1966 language::init(cx);
1967 editor::init(cx);
1968 menu::init();
1969 }
1970
1971 fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
1972 let mut pages: Vec<SettingsPage> = Vec::new();
1973 let mut expanded_pages = Vec::new();
1974 let mut selected_idx = None;
1975 let mut index = 0;
1976 let mut in_expanded_section = false;
1977
1978 for mut line in input
1979 .lines()
1980 .map(|line| line.trim())
1981 .filter(|line| !line.is_empty())
1982 {
1983 if let Some(pre) = line.strip_suffix('*') {
1984 assert!(selected_idx.is_none(), "Only one selected entry allowed");
1985 selected_idx = Some(index);
1986 line = pre;
1987 }
1988 let (kind, title) = line.split_once(" ").unwrap();
1989 assert_eq!(kind.len(), 1);
1990 let kind = kind.chars().next().unwrap();
1991 if kind == 'v' {
1992 let page_idx = pages.len();
1993 expanded_pages.push(page_idx);
1994 pages.push(SettingsPage {
1995 title,
1996 items: vec![],
1997 });
1998 index += 1;
1999 in_expanded_section = true;
2000 } else if kind == '>' {
2001 pages.push(SettingsPage {
2002 title,
2003 items: vec![],
2004 });
2005 index += 1;
2006 in_expanded_section = false;
2007 } else if kind == '-' {
2008 pages
2009 .last_mut()
2010 .unwrap()
2011 .items
2012 .push(SettingsPageItem::SectionHeader(title));
2013 if selected_idx == Some(index) && !in_expanded_section {
2014 panic!("Items in unexpanded sections cannot be selected");
2015 }
2016 index += 1;
2017 } else {
2018 panic!(
2019 "Entries must start with one of 'v', '>', or '-'\n line: {}",
2020 line
2021 );
2022 }
2023 }
2024
2025 let mut settings_window = SettingsWindow {
2026 files: Vec::default(),
2027 current_file: crate::SettingsUiFile::User,
2028 pages,
2029 search_bar: cx.new(|cx| Editor::single_line(window, cx)),
2030 navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
2031 navbar_entries: Vec::default(),
2032 list_handle: UniformListScrollHandle::default(),
2033 search_matches: vec![],
2034 search_task: None,
2035 scroll_handle: ScrollHandle::new(),
2036 focus_handle: cx.focus_handle(),
2037 navbar_focus_handle: cx.focus_handle(),
2038 content_focus_handle: cx.focus_handle(),
2039 files_focus_handle: cx.focus_handle(),
2040 };
2041
2042 settings_window.build_search_matches();
2043 settings_window.build_navbar();
2044 for expanded_page_index in expanded_pages {
2045 for entry in &mut settings_window.navbar_entries {
2046 if entry.page_index == expanded_page_index && entry.is_root {
2047 entry.expanded = true;
2048 }
2049 }
2050 }
2051 settings_window
2052 }
2053
2054 #[track_caller]
2055 fn check_navbar_toggle(
2056 before: &'static str,
2057 toggle_page: &'static str,
2058 after: &'static str,
2059 window: &mut Window,
2060 cx: &mut App,
2061 ) {
2062 let mut settings_window = parse(before, window, cx);
2063 let toggle_page_idx = settings_window
2064 .pages
2065 .iter()
2066 .position(|page| page.title == toggle_page)
2067 .expect("page not found");
2068 let toggle_idx = settings_window
2069 .navbar_entries
2070 .iter()
2071 .position(|entry| entry.page_index == toggle_page_idx)
2072 .expect("page not found");
2073 settings_window.toggle_navbar_entry(toggle_idx);
2074
2075 let expected_settings_window = parse(after, window, cx);
2076
2077 pretty_assertions::assert_eq!(
2078 settings_window
2079 .visible_navbar_entries()
2080 .map(|(_, entry)| entry)
2081 .collect::<Vec<_>>(),
2082 expected_settings_window
2083 .visible_navbar_entries()
2084 .map(|(_, entry)| entry)
2085 .collect::<Vec<_>>(),
2086 );
2087 pretty_assertions::assert_eq!(
2088 settings_window.navbar_entries[settings_window.navbar_entry()],
2089 expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
2090 );
2091 }
2092
2093 macro_rules! check_navbar_toggle {
2094 ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
2095 #[gpui::test]
2096 fn $name(cx: &mut gpui::TestAppContext) {
2097 let window = cx.add_empty_window();
2098 window.update(|window, cx| {
2099 register_settings(cx);
2100 check_navbar_toggle($before, $toggle_page, $after, window, cx);
2101 });
2102 }
2103 };
2104 }
2105
2106 check_navbar_toggle!(
2107 navbar_basic_open,
2108 before: r"
2109 v General
2110 - General
2111 - Privacy*
2112 v Project
2113 - Project Settings
2114 ",
2115 toggle_page: "General",
2116 after: r"
2117 > General*
2118 v Project
2119 - Project Settings
2120 "
2121 );
2122
2123 check_navbar_toggle!(
2124 navbar_basic_close,
2125 before: r"
2126 > General*
2127 - General
2128 - Privacy
2129 v Project
2130 - Project Settings
2131 ",
2132 toggle_page: "General",
2133 after: r"
2134 v General*
2135 - General
2136 - Privacy
2137 v Project
2138 - Project Settings
2139 "
2140 );
2141
2142 check_navbar_toggle!(
2143 navbar_basic_second_root_entry_close,
2144 before: r"
2145 > General
2146 - General
2147 - Privacy
2148 v Project
2149 - Project Settings*
2150 ",
2151 toggle_page: "Project",
2152 after: r"
2153 > General
2154 > Project*
2155 "
2156 );
2157
2158 check_navbar_toggle!(
2159 navbar_toggle_subroot,
2160 before: r"
2161 v General Page
2162 - General
2163 - Privacy
2164 v Project
2165 - Worktree Settings Content*
2166 v AI
2167 - General
2168 > Appearance & Behavior
2169 ",
2170 toggle_page: "Project",
2171 after: r"
2172 v General Page
2173 - General
2174 - Privacy
2175 > Project*
2176 v AI
2177 - General
2178 > Appearance & Behavior
2179 "
2180 );
2181
2182 check_navbar_toggle!(
2183 navbar_toggle_close_propagates_selected_index,
2184 before: r"
2185 v General Page
2186 - General
2187 - Privacy
2188 v Project
2189 - Worktree Settings Content
2190 v AI
2191 - General*
2192 > Appearance & Behavior
2193 ",
2194 toggle_page: "General Page",
2195 after: r"
2196 > General Page
2197 v Project
2198 - Worktree Settings Content
2199 v AI
2200 - General*
2201 > Appearance & Behavior
2202 "
2203 );
2204
2205 check_navbar_toggle!(
2206 navbar_toggle_expand_propagates_selected_index,
2207 before: r"
2208 > General Page
2209 - General
2210 - Privacy
2211 v Project
2212 - Worktree Settings Content
2213 v AI
2214 - General*
2215 > Appearance & Behavior
2216 ",
2217 toggle_page: "General Page",
2218 after: r"
2219 v General Page
2220 - General
2221 - Privacy
2222 v Project
2223 - Worktree Settings Content
2224 v AI
2225 - General*
2226 > Appearance & Behavior
2227 "
2228 );
2229
2230 #[gpui::test]
2231 fn test_basic_search(cx: &mut gpui::TestAppContext) {
2232 let cx = cx.add_empty_window();
2233 let (actual, expected) = cx.update(|window, cx| {
2234 register_settings(cx);
2235
2236 let expected = cx.new(|cx| {
2237 SettingsWindow::new_builder(window, cx)
2238 .add_page("General", |page| {
2239 page.item(SettingsPageItem::SectionHeader("General settings"))
2240 .item(SettingsPageItem::basic_item("test title", "General test"))
2241 })
2242 .build()
2243 });
2244
2245 let actual = cx.new(|cx| {
2246 SettingsWindow::new_builder(window, cx)
2247 .add_page("General", |page| {
2248 page.item(SettingsPageItem::SectionHeader("General settings"))
2249 .item(SettingsPageItem::basic_item("test title", "General test"))
2250 })
2251 .add_page("Theme", |page| {
2252 page.item(SettingsPageItem::SectionHeader("Theme settings"))
2253 })
2254 .build()
2255 });
2256
2257 actual.update(cx, |settings, cx| settings.search("gen", window, cx));
2258
2259 (actual, expected)
2260 });
2261
2262 cx.cx.run_until_parked();
2263
2264 cx.update(|_window, cx| {
2265 let expected = expected.read(cx);
2266 let actual = actual.read(cx);
2267 expected.assert_search_results(&actual);
2268 })
2269 }
2270
2271 #[gpui::test]
2272 fn test_search_render_page_with_filtered_out_navbar_entries(cx: &mut gpui::TestAppContext) {
2273 let cx = cx.add_empty_window();
2274 let (actual, expected) = cx.update(|window, cx| {
2275 register_settings(cx);
2276
2277 let actual = cx.new(|cx| {
2278 SettingsWindow::new_builder(window, cx)
2279 .add_page("General", |page| {
2280 page.item(SettingsPageItem::SectionHeader("General settings"))
2281 .item(SettingsPageItem::basic_item(
2282 "Confirm Quit",
2283 "Whether to confirm before quitting Zed",
2284 ))
2285 .item(SettingsPageItem::basic_item(
2286 "Auto Update",
2287 "Automatically update Zed",
2288 ))
2289 })
2290 .add_page("AI", |page| {
2291 page.item(SettingsPageItem::basic_item(
2292 "Disable AI",
2293 "Whether to disable all AI features in Zed",
2294 ))
2295 })
2296 .add_page("Appearance & Behavior", |page| {
2297 page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2298 SettingsPageItem::basic_item(
2299 "Cursor Shape",
2300 "Cursor shape for the editor",
2301 ),
2302 )
2303 })
2304 .build()
2305 });
2306
2307 let expected = cx.new(|cx| {
2308 SettingsWindow::new_builder(window, cx)
2309 .add_page("Appearance & Behavior", |page| {
2310 page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2311 SettingsPageItem::basic_item(
2312 "Cursor Shape",
2313 "Cursor shape for the editor",
2314 ),
2315 )
2316 })
2317 .build()
2318 });
2319
2320 actual.update(cx, |settings, cx| settings.search("cursor", window, cx));
2321
2322 (actual, expected)
2323 });
2324
2325 cx.cx.run_until_parked();
2326
2327 cx.update(|_window, cx| {
2328 let expected = expected.read(cx);
2329 let actual = actual.read(cx);
2330 expected.assert_search_results(&actual);
2331 })
2332 }
2333}