1mod components;
2mod page_data;
3
4use anyhow::Result;
5use editor::{Editor, EditorEvent};
6use feature_flags::FeatureFlag;
7use fuzzy::StringMatchCandidate;
8use gpui::{
9 Action, App, Div, Entity, FocusHandle, Focusable, FontWeight, Global, ListState,
10 ReadGlobal as _, ScrollHandle, Stateful, Subscription, Task, TitlebarOptions,
11 UniformListScrollHandle, Window, WindowBounds, WindowHandle, WindowOptions, actions, div, list,
12 point, prelude::*, px, size, uniform_list,
13};
14use heck::ToTitleCase as _;
15use project::WorktreeId;
16use schemars::JsonSchema;
17use serde::Deserialize;
18use settings::{Settings, SettingsContent, SettingsStore};
19use std::{
20 any::{Any, TypeId, type_name},
21 cell::RefCell,
22 collections::HashMap,
23 num::{NonZero, NonZeroU32},
24 ops::Range,
25 rc::Rc,
26 sync::{Arc, LazyLock, RwLock},
27};
28use title_bar::platform_title_bar::PlatformTitleBar;
29use ui::{
30 ContextMenu, Divider, DividerColor, DropdownMenu, DropdownStyle, IconButtonShape, KeyBinding,
31 KeybindingHint, PopoverMenu, Switch, SwitchColor, Tooltip, TreeViewItem, WithScrollbar,
32 prelude::*,
33};
34use ui_input::{NumberField, NumberFieldType};
35use util::{ResultExt as _, paths::PathStyle, rel_path::RelPath};
36use workspace::{OpenOptions, OpenVisible, Workspace, client_side_decorations};
37use zed_actions::OpenSettings;
38
39use crate::components::SettingsEditor;
40
41const NAVBAR_CONTAINER_TAB_INDEX: isize = 0;
42const NAVBAR_GROUP_TAB_INDEX: isize = 1;
43
44const HEADER_CONTAINER_TAB_INDEX: isize = 2;
45const HEADER_GROUP_TAB_INDEX: isize = 3;
46
47const CONTENT_CONTAINER_TAB_INDEX: isize = 4;
48const CONTENT_GROUP_TAB_INDEX: isize = 5;
49
50actions!(
51 settings_editor,
52 [
53 /// Minimizes the settings UI window.
54 Minimize,
55 /// Toggles focus between the navbar and the main content.
56 ToggleFocusNav,
57 /// Expands the navigation entry.
58 ExpandNavEntry,
59 /// Collapses the navigation entry.
60 CollapseNavEntry,
61 /// Focuses the next file in the file list.
62 FocusNextFile,
63 /// Focuses the previous file in the file list.
64 FocusPreviousFile,
65 /// Opens an editor for the current file
66 OpenCurrentFile,
67 /// Focuses the previous root navigation entry.
68 FocusPreviousRootNavEntry,
69 /// Focuses the next root navigation entry.
70 FocusNextRootNavEntry,
71 /// Focuses the first navigation entry.
72 FocusFirstNavEntry,
73 /// Focuses the last navigation entry.
74 FocusLastNavEntry,
75 /// Focuses and opens the next navigation entry without moving focus to content.
76 FocusNextNavEntry,
77 /// Focuses and opens the previous navigation entry without moving focus to content.
78 FocusPreviousNavEntry
79 ]
80);
81
82#[derive(Action, PartialEq, Eq, Clone, Copy, Debug, JsonSchema, Deserialize)]
83#[action(namespace = settings_editor)]
84struct FocusFile(pub u32);
85
86struct SettingField<T: 'static> {
87 pick: fn(&SettingsContent) -> &Option<T>,
88 pick_mut: fn(&mut SettingsContent) -> &mut Option<T>,
89}
90
91impl<T: 'static> Clone for SettingField<T> {
92 fn clone(&self) -> Self {
93 *self
94 }
95}
96
97// manual impl because derive puts a Copy bound on T, which is inaccurate in our case
98impl<T: 'static> Copy for SettingField<T> {}
99
100/// Helper for unimplemented settings, used in combination with `SettingField::unimplemented`
101/// to keep the setting around in the UI with valid pick and pick_mut implementations, but don't actually try to render it.
102/// TODO(settings_ui): In non-dev builds (`#[cfg(not(debug_assertions))]`) make this render as edit-in-json
103#[derive(Clone, Copy)]
104struct UnimplementedSettingField;
105
106impl PartialEq for UnimplementedSettingField {
107 fn eq(&self, _other: &Self) -> bool {
108 true
109 }
110}
111
112impl<T: 'static> SettingField<T> {
113 /// Helper for settings with types that are not yet implemented.
114 #[allow(unused)]
115 fn unimplemented(self) -> SettingField<UnimplementedSettingField> {
116 SettingField {
117 pick: |_| &Some(UnimplementedSettingField),
118 pick_mut: |_| unreachable!(),
119 }
120 }
121}
122
123trait AnySettingField {
124 fn as_any(&self) -> &dyn Any;
125 fn type_name(&self) -> &'static str;
126 fn type_id(&self) -> TypeId;
127 // 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)
128 fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool);
129 fn reset_to_default_fn(
130 &self,
131 current_file: &SettingsUiFile,
132 file_set_in: &settings::SettingsFile,
133 cx: &App,
134 ) -> Option<Box<dyn Fn(&mut App)>>;
135}
136
137impl<T: PartialEq + Clone + Send + Sync + 'static> AnySettingField for SettingField<T> {
138 fn as_any(&self) -> &dyn Any {
139 self
140 }
141
142 fn type_name(&self) -> &'static str {
143 type_name::<T>()
144 }
145
146 fn type_id(&self) -> TypeId {
147 TypeId::of::<T>()
148 }
149
150 fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool) {
151 let (file, value) = cx
152 .global::<SettingsStore>()
153 .get_value_from_file(file.to_settings(), self.pick);
154 return (file, value.is_some());
155 }
156
157 fn reset_to_default_fn(
158 &self,
159 current_file: &SettingsUiFile,
160 file_set_in: &settings::SettingsFile,
161 cx: &App,
162 ) -> Option<Box<dyn Fn(&mut App)>> {
163 if file_set_in == &settings::SettingsFile::Default {
164 return None;
165 }
166 let this = *self;
167 let store = SettingsStore::global(cx);
168 let default_value = (this.pick)(store.raw_default_settings());
169 let is_default = store
170 .get_content_for_file(file_set_in.clone())
171 .map_or(&None, this.pick)
172 == default_value;
173 if is_default {
174 return None;
175 }
176 let current_file = current_file.clone();
177
178 return Some(Box::new(move |cx| {
179 let store = SettingsStore::global(cx);
180 let default_value = (this.pick)(store.raw_default_settings());
181 let is_set_somewhere_other_than_default = store
182 .get_value_up_to_file(current_file.to_settings(), this.pick)
183 .0
184 != settings::SettingsFile::Default;
185 let value_to_set = if is_set_somewhere_other_than_default {
186 default_value.clone()
187 } else {
188 None
189 };
190 update_settings_file(current_file.clone(), cx, move |settings, _| {
191 *(this.pick_mut)(settings) = value_to_set;
192 })
193 // todo(settings_ui): Don't log err
194 .log_err();
195 }));
196 }
197}
198
199#[derive(Default, Clone)]
200struct SettingFieldRenderer {
201 renderers: Rc<
202 RefCell<
203 HashMap<
204 TypeId,
205 Box<
206 dyn Fn(
207 &SettingsWindow,
208 &SettingItem,
209 SettingsUiFile,
210 Option<&SettingsFieldMetadata>,
211 &mut Window,
212 &mut Context<SettingsWindow>,
213 ) -> Stateful<Div>,
214 >,
215 >,
216 >,
217 >,
218}
219
220impl Global for SettingFieldRenderer {}
221
222impl SettingFieldRenderer {
223 fn add_basic_renderer<T: 'static>(
224 &mut self,
225 render_control: impl Fn(
226 SettingField<T>,
227 SettingsUiFile,
228 Option<&SettingsFieldMetadata>,
229 &mut Window,
230 &mut App,
231 ) -> AnyElement
232 + 'static,
233 ) -> &mut Self {
234 self.add_renderer(
235 move |settings_window: &SettingsWindow,
236 item: &SettingItem,
237 field: SettingField<T>,
238 settings_file: SettingsUiFile,
239 metadata: Option<&SettingsFieldMetadata>,
240 window: &mut Window,
241 cx: &mut Context<SettingsWindow>| {
242 render_settings_item(
243 settings_window,
244 item,
245 settings_file.clone(),
246 render_control(field, settings_file, metadata, window, cx),
247 window,
248 cx,
249 )
250 },
251 )
252 }
253
254 fn add_renderer<T: 'static>(
255 &mut self,
256 renderer: impl Fn(
257 &SettingsWindow,
258 &SettingItem,
259 SettingField<T>,
260 SettingsUiFile,
261 Option<&SettingsFieldMetadata>,
262 &mut Window,
263 &mut Context<SettingsWindow>,
264 ) -> Stateful<Div>
265 + 'static,
266 ) -> &mut Self {
267 let key = TypeId::of::<T>();
268 let renderer = Box::new(
269 move |settings_window: &SettingsWindow,
270 item: &SettingItem,
271 settings_file: SettingsUiFile,
272 metadata: Option<&SettingsFieldMetadata>,
273 window: &mut Window,
274 cx: &mut Context<SettingsWindow>| {
275 let field = *item
276 .field
277 .as_ref()
278 .as_any()
279 .downcast_ref::<SettingField<T>>()
280 .unwrap();
281 renderer(
282 settings_window,
283 item,
284 field,
285 settings_file,
286 metadata,
287 window,
288 cx,
289 )
290 },
291 );
292 self.renderers.borrow_mut().insert(key, renderer);
293 self
294 }
295}
296
297struct NonFocusableHandle {
298 handle: FocusHandle,
299 _subscription: Subscription,
300}
301
302impl NonFocusableHandle {
303 fn new(tab_index: isize, tab_stop: bool, window: &mut Window, cx: &mut App) -> Entity<Self> {
304 let handle = cx.focus_handle().tab_index(tab_index).tab_stop(tab_stop);
305 Self::from_handle(handle, window, cx)
306 }
307
308 fn from_handle(handle: FocusHandle, window: &mut Window, cx: &mut App) -> Entity<Self> {
309 cx.new(|cx| {
310 let _subscription = cx.on_focus(&handle, window, {
311 move |_, window, _| {
312 window.focus_next();
313 }
314 });
315 Self {
316 handle,
317 _subscription,
318 }
319 })
320 }
321}
322
323impl Focusable for NonFocusableHandle {
324 fn focus_handle(&self, _: &App) -> FocusHandle {
325 self.handle.clone()
326 }
327}
328
329#[derive(Default)]
330struct SettingsFieldMetadata {
331 placeholder: Option<&'static str>,
332 should_do_titlecase: Option<bool>,
333}
334
335pub struct SettingsUiFeatureFlag;
336
337impl FeatureFlag for SettingsUiFeatureFlag {
338 const NAME: &'static str = "settings-ui";
339}
340
341pub fn init(cx: &mut App) {
342 init_renderers(cx);
343
344 cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
345 workspace.register_action(|workspace, _: &OpenSettings, window, cx| {
346 let window_handle = window
347 .window_handle()
348 .downcast::<Workspace>()
349 .expect("Workspaces are root Windows");
350 open_settings_editor(workspace, window_handle, cx);
351 });
352 })
353 .detach();
354}
355
356fn init_renderers(cx: &mut App) {
357 cx.default_global::<SettingFieldRenderer>()
358 .add_basic_renderer::<UnimplementedSettingField>(|_, _, _, _, _| {
359 Button::new("open-in-settings-file", "Edit in settings.json")
360 .style(ButtonStyle::Outlined)
361 .size(ButtonSize::Medium)
362 .tab_index(0_isize)
363 .on_click(|_, window, cx| {
364 window.dispatch_action(Box::new(OpenCurrentFile), cx);
365 })
366 .into_any_element()
367 })
368 .add_basic_renderer::<bool>(render_toggle_button)
369 .add_basic_renderer::<String>(render_text_field)
370 .add_basic_renderer::<settings::SaturatingBool>(render_toggle_button)
371 .add_basic_renderer::<settings::CursorShape>(render_dropdown)
372 .add_basic_renderer::<settings::RestoreOnStartupBehavior>(render_dropdown)
373 .add_basic_renderer::<settings::BottomDockLayout>(render_dropdown)
374 .add_basic_renderer::<settings::OnLastWindowClosed>(render_dropdown)
375 .add_basic_renderer::<settings::CloseWindowWhenNoItems>(render_dropdown)
376 .add_basic_renderer::<settings::FontFamilyName>(render_font_picker)
377 // todo(settings_ui): This needs custom ui
378 // .add_renderer::<settings::BufferLineHeight>(|settings_field, file, _, window, cx| {
379 // // todo(settings_ui): Do we want to expose the custom variant of buffer line height?
380 // // right now there's a manual impl of strum::VariantArray
381 // render_dropdown(*settings_field, file, window, cx)
382 // })
383 .add_basic_renderer::<settings::BaseKeymapContent>(render_dropdown)
384 .add_basic_renderer::<settings::MultiCursorModifier>(render_dropdown)
385 .add_basic_renderer::<settings::HideMouseMode>(render_dropdown)
386 .add_basic_renderer::<settings::CurrentLineHighlight>(render_dropdown)
387 .add_basic_renderer::<settings::ShowWhitespaceSetting>(render_dropdown)
388 .add_basic_renderer::<settings::SoftWrap>(render_dropdown)
389 .add_basic_renderer::<settings::ScrollBeyondLastLine>(render_dropdown)
390 .add_basic_renderer::<settings::SnippetSortOrder>(render_dropdown)
391 .add_basic_renderer::<settings::ClosePosition>(render_dropdown)
392 .add_basic_renderer::<settings::DockSide>(render_dropdown)
393 .add_basic_renderer::<settings::TerminalDockPosition>(render_dropdown)
394 .add_basic_renderer::<settings::DockPosition>(render_dropdown)
395 .add_basic_renderer::<settings::GitGutterSetting>(render_dropdown)
396 .add_basic_renderer::<settings::GitHunkStyleSetting>(render_dropdown)
397 .add_basic_renderer::<settings::DiagnosticSeverityContent>(render_dropdown)
398 .add_basic_renderer::<settings::SeedQuerySetting>(render_dropdown)
399 .add_basic_renderer::<settings::DoubleClickInMultibuffer>(render_dropdown)
400 .add_basic_renderer::<settings::GoToDefinitionFallback>(render_dropdown)
401 .add_basic_renderer::<settings::ActivateOnClose>(render_dropdown)
402 .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
403 .add_basic_renderer::<settings::ShowCloseButton>(render_dropdown)
404 .add_basic_renderer::<settings::ProjectPanelEntrySpacing>(render_dropdown)
405 .add_basic_renderer::<settings::RewrapBehavior>(render_dropdown)
406 .add_basic_renderer::<settings::FormatOnSave>(render_dropdown)
407 .add_basic_renderer::<settings::IndentGuideColoring>(render_dropdown)
408 .add_basic_renderer::<settings::IndentGuideBackgroundColoring>(render_dropdown)
409 .add_basic_renderer::<settings::FileFinderWidthContent>(render_dropdown)
410 .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
411 .add_basic_renderer::<settings::WordsCompletionMode>(render_dropdown)
412 .add_basic_renderer::<settings::LspInsertMode>(render_dropdown)
413 .add_basic_renderer::<settings::AlternateScroll>(render_dropdown)
414 .add_basic_renderer::<settings::TerminalBlink>(render_dropdown)
415 .add_basic_renderer::<settings::CursorShapeContent>(render_dropdown)
416 .add_basic_renderer::<f32>(render_number_field)
417 .add_basic_renderer::<u32>(render_number_field)
418 .add_basic_renderer::<u64>(render_number_field)
419 .add_basic_renderer::<usize>(render_number_field)
420 .add_basic_renderer::<NonZero<usize>>(render_number_field)
421 .add_basic_renderer::<NonZeroU32>(render_number_field)
422 .add_basic_renderer::<settings::CodeFade>(render_number_field)
423 .add_basic_renderer::<FontWeight>(render_number_field)
424 .add_basic_renderer::<settings::MinimumContrast>(render_number_field)
425 .add_basic_renderer::<settings::ShowScrollbar>(render_dropdown)
426 .add_basic_renderer::<settings::ScrollbarDiagnostics>(render_dropdown)
427 .add_basic_renderer::<settings::ShowMinimap>(render_dropdown)
428 .add_basic_renderer::<settings::DisplayIn>(render_dropdown)
429 .add_basic_renderer::<settings::MinimapThumb>(render_dropdown)
430 .add_basic_renderer::<settings::MinimapThumbBorder>(render_dropdown)
431 .add_basic_renderer::<settings::SteppingGranularity>(render_dropdown)
432 .add_basic_renderer::<settings::NotifyWhenAgentWaiting>(render_dropdown)
433 .add_basic_renderer::<settings::ImageFileSizeUnit>(render_dropdown)
434 .add_basic_renderer::<settings::StatusStyle>(render_dropdown)
435 .add_basic_renderer::<settings::PaneSplitDirectionHorizontal>(render_dropdown)
436 .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
437 .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
438 .add_basic_renderer::<settings::DocumentColorsRenderMode>(render_dropdown)
439 // please semicolon stay on next line
440 ;
441 // .add_renderer::<ThemeSelection>(|settings_field, file, _, window, cx| {
442 // render_dropdown(*settings_field, file, window, cx)
443 // });
444}
445
446pub fn open_settings_editor(
447 _workspace: &mut Workspace,
448 workspace_handle: WindowHandle<Workspace>,
449 cx: &mut App,
450) {
451 let existing_window = cx
452 .windows()
453 .into_iter()
454 .find_map(|window| window.downcast::<SettingsWindow>());
455
456 if let Some(existing_window) = existing_window {
457 existing_window
458 .update(cx, |settings_window, window, _| {
459 settings_window.original_window = Some(workspace_handle);
460 window.activate_window();
461 })
462 .ok();
463 return;
464 }
465
466 // We have to defer this to get the workspace off the stack.
467
468 cx.defer(move |cx| {
469 let current_rem_size: f32 = theme::ThemeSettings::get_global(cx).ui_font_size(cx).into();
470
471 let default_bounds = size(px(900.), px(750.)); // 4:3 Aspect Ratio
472 let default_rem_size = 16.0;
473 let scale_factor = current_rem_size / default_rem_size;
474 let scaled_bounds: gpui::Size<Pixels> = default_bounds.map(|axis| axis * scale_factor);
475
476 cx.open_window(
477 WindowOptions {
478 titlebar: Some(TitlebarOptions {
479 title: Some("Settings Window".into()),
480 appears_transparent: true,
481 traffic_light_position: Some(point(px(12.0), px(12.0))),
482 }),
483 focus: true,
484 show: true,
485 is_movable: true,
486 kind: gpui::WindowKind::Floating,
487 window_background: cx.theme().window_background_appearance(),
488 window_min_size: Some(scaled_bounds),
489 window_bounds: Some(WindowBounds::centered(scaled_bounds, cx)),
490 ..Default::default()
491 },
492 |window, cx| cx.new(|cx| SettingsWindow::new(Some(workspace_handle), window, cx)),
493 )
494 .log_err();
495 });
496}
497
498/// The current sub page path that is selected.
499/// If this is empty the selected page is rendered,
500/// otherwise the last sub page gets rendered.
501///
502/// Global so that `pick` and `pick_mut` callbacks can access it
503/// and use it to dynamically render sub pages (e.g. for language settings)
504static SUB_PAGE_STACK: LazyLock<RwLock<Vec<SubPage>>> = LazyLock::new(|| RwLock::new(Vec::new()));
505
506fn sub_page_stack() -> std::sync::RwLockReadGuard<'static, Vec<SubPage>> {
507 SUB_PAGE_STACK
508 .read()
509 .expect("SUB_PAGE_STACK is never poisoned")
510}
511
512fn sub_page_stack_mut() -> std::sync::RwLockWriteGuard<'static, Vec<SubPage>> {
513 SUB_PAGE_STACK
514 .write()
515 .expect("SUB_PAGE_STACK is never poisoned")
516}
517
518pub struct SettingsWindow {
519 title_bar: Option<Entity<PlatformTitleBar>>,
520 original_window: Option<WindowHandle<Workspace>>,
521 files: Vec<(SettingsUiFile, FocusHandle)>,
522 drop_down_file: Option<usize>,
523 worktree_root_dirs: HashMap<WorktreeId, String>,
524 current_file: SettingsUiFile,
525 pages: Vec<SettingsPage>,
526 search_bar: Entity<Editor>,
527 search_task: Option<Task<()>>,
528 /// Index into navbar_entries
529 navbar_entry: usize,
530 navbar_entries: Vec<NavBarEntry>,
531 navbar_scroll_handle: UniformListScrollHandle,
532 /// [page_index][page_item_index] will be false
533 /// when the item is filtered out either by searches
534 /// or by the current file
535 navbar_focus_subscriptions: Vec<gpui::Subscription>,
536 filter_table: Vec<Vec<bool>>,
537 has_query: bool,
538 content_handles: Vec<Vec<Entity<NonFocusableHandle>>>,
539 sub_page_scroll_handle: ScrollHandle,
540 focus_handle: FocusHandle,
541 navbar_focus_handle: Entity<NonFocusableHandle>,
542 content_focus_handle: Entity<NonFocusableHandle>,
543 files_focus_handle: FocusHandle,
544 search_index: Option<Arc<SearchIndex>>,
545 visible_items: Vec<usize>,
546 list_state: ListState,
547}
548
549struct SearchIndex {
550 bm25_engine: bm25::SearchEngine<usize>,
551 fuzzy_match_candidates: Vec<StringMatchCandidate>,
552 key_lut: Vec<SearchItemKey>,
553}
554
555struct SearchItemKey {
556 page_index: usize,
557 header_index: usize,
558 item_index: usize,
559}
560
561struct SubPage {
562 link: SubPageLink,
563 section_header: &'static str,
564}
565
566#[derive(Debug)]
567struct NavBarEntry {
568 title: &'static str,
569 is_root: bool,
570 expanded: bool,
571 page_index: usize,
572 item_index: Option<usize>,
573 focus_handle: FocusHandle,
574}
575
576struct SettingsPage {
577 title: &'static str,
578 items: Vec<SettingsPageItem>,
579}
580
581#[derive(PartialEq)]
582enum SettingsPageItem {
583 SectionHeader(&'static str),
584 SettingItem(SettingItem),
585 SubPageLink(SubPageLink),
586}
587
588impl std::fmt::Debug for SettingsPageItem {
589 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
590 match self {
591 SettingsPageItem::SectionHeader(header) => write!(f, "SectionHeader({})", header),
592 SettingsPageItem::SettingItem(setting_item) => {
593 write!(f, "SettingItem({})", setting_item.title)
594 }
595 SettingsPageItem::SubPageLink(sub_page_link) => {
596 write!(f, "SubPageLink({})", sub_page_link.title)
597 }
598 }
599 }
600}
601
602impl SettingsPageItem {
603 fn render(
604 &self,
605 settings_window: &SettingsWindow,
606 item_index: usize,
607 is_last: bool,
608 window: &mut Window,
609 cx: &mut Context<SettingsWindow>,
610 ) -> AnyElement {
611 let file = settings_window.current_file.clone();
612 match self {
613 SettingsPageItem::SectionHeader(header) => v_flex()
614 .w_full()
615 .gap_1p5()
616 .child(
617 Label::new(SharedString::new_static(header))
618 .size(LabelSize::Small)
619 .color(Color::Muted)
620 .buffer_font(cx),
621 )
622 .child(Divider::horizontal().color(DividerColor::BorderFaded))
623 .into_any_element(),
624 SettingsPageItem::SettingItem(setting_item) => {
625 let renderer = cx.default_global::<SettingFieldRenderer>().clone();
626 let (_, found) = setting_item.field.file_set_in(file.clone(), cx);
627
628 let renderers = renderer.renderers.borrow();
629 let field_renderer =
630 renderers.get(&AnySettingField::type_id(setting_item.field.as_ref()));
631 let field_renderer_or_warning =
632 field_renderer.ok_or("NO RENDERER").and_then(|renderer| {
633 if cfg!(debug_assertions) && !found {
634 Err("NO DEFAULT")
635 } else {
636 Ok(renderer)
637 }
638 });
639
640 let field = match field_renderer_or_warning {
641 Ok(field_renderer) => field_renderer(
642 settings_window,
643 setting_item,
644 file,
645 setting_item.metadata.as_deref(),
646 window,
647 cx,
648 ),
649 Err(warning) => render_settings_item(
650 settings_window,
651 setting_item,
652 file,
653 Button::new("error-warning", warning)
654 .style(ButtonStyle::Outlined)
655 .size(ButtonSize::Medium)
656 .icon(Some(IconName::Debug))
657 .icon_position(IconPosition::Start)
658 .icon_color(Color::Error)
659 .tab_index(0_isize)
660 .tooltip(Tooltip::text(setting_item.field.type_name()))
661 .into_any_element(),
662 window,
663 cx,
664 ),
665 };
666
667 field
668 .pt_4()
669 .map(|this| {
670 if is_last {
671 this.pb_10()
672 } else {
673 this.pb_4()
674 .border_b_1()
675 .border_color(cx.theme().colors().border_variant)
676 }
677 })
678 .into_any_element()
679 }
680 SettingsPageItem::SubPageLink(sub_page_link) => h_flex()
681 .id(sub_page_link.title.clone())
682 .w_full()
683 .min_w_0()
684 .gap_2()
685 .justify_between()
686 .pt_4()
687 .map(|this| {
688 if is_last {
689 this.pb_10()
690 } else {
691 this.pb_4()
692 .border_b_1()
693 .border_color(cx.theme().colors().border_variant)
694 }
695 })
696 .child(
697 v_flex()
698 .w_full()
699 .max_w_1_2()
700 .child(Label::new(sub_page_link.title.clone())),
701 )
702 .child(
703 Button::new(
704 ("sub-page".into(), sub_page_link.title.clone()),
705 "Configure",
706 )
707 .icon(IconName::ChevronRight)
708 .tab_index(0_isize)
709 .icon_position(IconPosition::End)
710 .icon_color(Color::Muted)
711 .icon_size(IconSize::Small)
712 .style(ButtonStyle::Outlined)
713 .size(ButtonSize::Medium)
714 .on_click({
715 let sub_page_link = sub_page_link.clone();
716 cx.listener(move |this, _, _, cx| {
717 let mut section_index = item_index;
718 let current_page = this.current_page();
719
720 while !matches!(
721 current_page.items[section_index],
722 SettingsPageItem::SectionHeader(_)
723 ) {
724 section_index -= 1;
725 }
726
727 let SettingsPageItem::SectionHeader(header) =
728 current_page.items[section_index]
729 else {
730 unreachable!("All items always have a section header above them")
731 };
732
733 this.push_sub_page(sub_page_link.clone(), header, cx)
734 })
735 }),
736 )
737 .into_any_element(),
738 }
739 }
740}
741
742fn render_settings_item(
743 settings_window: &SettingsWindow,
744 setting_item: &SettingItem,
745 file: SettingsUiFile,
746 control: AnyElement,
747 _window: &mut Window,
748 cx: &mut Context<'_, SettingsWindow>,
749) -> Stateful<Div> {
750 let (found_in_file, _) = setting_item.field.file_set_in(file.clone(), cx);
751 let file_set_in = SettingsUiFile::from_settings(found_in_file.clone());
752
753 h_flex()
754 .id(setting_item.title)
755 .min_w_0()
756 .gap_2()
757 .justify_between()
758 .child(
759 v_flex()
760 .w_1_2()
761 .child(
762 h_flex()
763 .w_full()
764 .gap_1()
765 .child(Label::new(SharedString::new_static(setting_item.title)))
766 .when_some(
767 setting_item
768 .field
769 .reset_to_default_fn(&file, &found_in_file, cx)
770 .filter(|_| file_set_in.as_ref() == Some(&file)),
771 |this, reset_to_default| {
772 this.child(
773 IconButton::new("reset-to-default-btn", IconName::Undo)
774 .icon_color(Color::Muted)
775 .icon_size(IconSize::Small)
776 .tooltip(Tooltip::text("Reset to Default"))
777 .on_click({
778 move |_, _, cx| {
779 reset_to_default(cx);
780 }
781 }),
782 )
783 },
784 )
785 .when_some(
786 file_set_in.filter(|file_set_in| file_set_in != &file),
787 |this, file_set_in| {
788 this.child(
789 Label::new(format!(
790 "— Modified in {}",
791 settings_window
792 .display_name(&file_set_in)
793 .expect("File name should exist")
794 ))
795 .color(Color::Muted)
796 .size(LabelSize::Small),
797 )
798 },
799 ),
800 )
801 .child(
802 Label::new(SharedString::new_static(setting_item.description))
803 .size(LabelSize::Small)
804 .color(Color::Muted),
805 ),
806 )
807 .child(control)
808}
809
810struct SettingItem {
811 title: &'static str,
812 description: &'static str,
813 field: Box<dyn AnySettingField>,
814 metadata: Option<Box<SettingsFieldMetadata>>,
815 files: FileMask,
816}
817
818#[derive(PartialEq, Eq, Clone, Copy)]
819struct FileMask(u8);
820
821impl std::fmt::Debug for FileMask {
822 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
823 write!(f, "FileMask(")?;
824 let mut items = vec![];
825
826 if self.contains(USER) {
827 items.push("USER");
828 }
829 if self.contains(LOCAL) {
830 items.push("LOCAL");
831 }
832 if self.contains(SERVER) {
833 items.push("SERVER");
834 }
835
836 write!(f, "{})", items.join(" | "))
837 }
838}
839
840const USER: FileMask = FileMask(1 << 0);
841const LOCAL: FileMask = FileMask(1 << 2);
842const SERVER: FileMask = FileMask(1 << 3);
843
844impl std::ops::BitAnd for FileMask {
845 type Output = Self;
846
847 fn bitand(self, other: Self) -> Self {
848 Self(self.0 & other.0)
849 }
850}
851
852impl std::ops::BitOr for FileMask {
853 type Output = Self;
854
855 fn bitor(self, other: Self) -> Self {
856 Self(self.0 | other.0)
857 }
858}
859
860impl FileMask {
861 fn contains(&self, other: FileMask) -> bool {
862 self.0 & other.0 != 0
863 }
864}
865
866impl PartialEq for SettingItem {
867 fn eq(&self, other: &Self) -> bool {
868 self.title == other.title
869 && self.description == other.description
870 && (match (&self.metadata, &other.metadata) {
871 (None, None) => true,
872 (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
873 _ => false,
874 })
875 }
876}
877
878#[derive(Clone)]
879struct SubPageLink {
880 title: SharedString,
881 files: FileMask,
882 render: Arc<
883 dyn Fn(&mut SettingsWindow, &mut Window, &mut Context<SettingsWindow>) -> AnyElement
884 + 'static
885 + Send
886 + Sync,
887 >,
888}
889
890impl PartialEq for SubPageLink {
891 fn eq(&self, other: &Self) -> bool {
892 self.title == other.title
893 }
894}
895
896fn all_language_names(cx: &App) -> Vec<SharedString> {
897 workspace::AppState::global(cx)
898 .upgrade()
899 .map_or(vec![], |state| {
900 state
901 .languages
902 .language_names()
903 .into_iter()
904 .filter(|name| name.as_ref() != "Zed Keybind Context")
905 .map(Into::into)
906 .collect()
907 })
908}
909
910#[allow(unused)]
911#[derive(Clone, PartialEq)]
912enum SettingsUiFile {
913 User, // Uses all settings.
914 Project((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
915 Server(&'static str), // Uses a special name, and the user settings
916}
917
918impl SettingsUiFile {
919 fn is_server(&self) -> bool {
920 matches!(self, SettingsUiFile::Server(_))
921 }
922
923 fn worktree_id(&self) -> Option<WorktreeId> {
924 match self {
925 SettingsUiFile::User => None,
926 SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
927 SettingsUiFile::Server(_) => None,
928 }
929 }
930
931 fn from_settings(file: settings::SettingsFile) -> Option<Self> {
932 Some(match file {
933 settings::SettingsFile::User => SettingsUiFile::User,
934 settings::SettingsFile::Project(location) => SettingsUiFile::Project(location),
935 settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
936 settings::SettingsFile::Default => return None,
937 })
938 }
939
940 fn to_settings(&self) -> settings::SettingsFile {
941 match self {
942 SettingsUiFile::User => settings::SettingsFile::User,
943 SettingsUiFile::Project(location) => settings::SettingsFile::Project(location.clone()),
944 SettingsUiFile::Server(_) => settings::SettingsFile::Server,
945 }
946 }
947
948 fn mask(&self) -> FileMask {
949 match self {
950 SettingsUiFile::User => USER,
951 SettingsUiFile::Project(_) => LOCAL,
952 SettingsUiFile::Server(_) => SERVER,
953 }
954 }
955}
956
957impl SettingsWindow {
958 pub fn new(
959 original_window: Option<WindowHandle<Workspace>>,
960 window: &mut Window,
961 cx: &mut Context<Self>,
962 ) -> Self {
963 let font_family_cache = theme::FontFamilyCache::global(cx);
964
965 cx.spawn(async move |this, cx| {
966 font_family_cache.prefetch(cx).await;
967 this.update(cx, |_, cx| {
968 cx.notify();
969 })
970 })
971 .detach();
972
973 let current_file = SettingsUiFile::User;
974 let search_bar = cx.new(|cx| {
975 let mut editor = Editor::single_line(window, cx);
976 editor.set_placeholder_text("Search settings…", window, cx);
977 editor
978 });
979
980 cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
981 let EditorEvent::Edited { transaction_id: _ } = event else {
982 return;
983 };
984
985 this.update_matches(cx);
986 })
987 .detach();
988
989 cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
990 this.fetch_files(window, cx);
991 cx.notify();
992 })
993 .detach();
994
995 let title_bar = if !cfg!(target_os = "macos") {
996 Some(cx.new(|cx| PlatformTitleBar::new("settings-title-bar", cx)))
997 } else {
998 None
999 };
1000
1001 // high overdraw value so the list scrollbar len doesn't change too much
1002 let list_state = gpui::ListState::new(0, gpui::ListAlignment::Top, px(100.0)).measure_all();
1003 list_state.set_scroll_handler(|_, _, _| {});
1004
1005 let mut this = Self {
1006 title_bar,
1007 original_window,
1008 worktree_root_dirs: HashMap::default(),
1009 files: vec![],
1010 drop_down_file: None,
1011 current_file: current_file,
1012 pages: vec![],
1013 navbar_entries: vec![],
1014 navbar_entry: 0,
1015 navbar_scroll_handle: UniformListScrollHandle::default(),
1016 search_bar,
1017 search_task: None,
1018 filter_table: vec![],
1019 has_query: false,
1020 content_handles: vec![],
1021 sub_page_scroll_handle: ScrollHandle::new(),
1022 focus_handle: cx.focus_handle(),
1023 navbar_focus_handle: NonFocusableHandle::new(
1024 NAVBAR_CONTAINER_TAB_INDEX,
1025 false,
1026 window,
1027 cx,
1028 ),
1029 navbar_focus_subscriptions: vec![],
1030 content_focus_handle: NonFocusableHandle::new(
1031 CONTENT_CONTAINER_TAB_INDEX,
1032 false,
1033 window,
1034 cx,
1035 ),
1036 files_focus_handle: cx
1037 .focus_handle()
1038 .tab_index(HEADER_CONTAINER_TAB_INDEX)
1039 .tab_stop(false),
1040 search_index: None,
1041 visible_items: Vec::default(),
1042 list_state,
1043 };
1044
1045 this.fetch_files(window, cx);
1046 this.build_ui(window, cx);
1047 this.build_search_index();
1048
1049 this.search_bar.update(cx, |editor, cx| {
1050 editor.focus_handle(cx).focus(window);
1051 });
1052
1053 this
1054 }
1055
1056 fn toggle_navbar_entry(&mut self, nav_entry_index: usize) {
1057 // We can only toggle root entries
1058 if !self.navbar_entries[nav_entry_index].is_root {
1059 return;
1060 }
1061
1062 let expanded = &mut self.navbar_entries[nav_entry_index].expanded;
1063 *expanded = !*expanded;
1064 let expanded = *expanded;
1065
1066 let toggle_page_index = self.page_index_from_navbar_index(nav_entry_index);
1067 let selected_page_index = self.page_index_from_navbar_index(self.navbar_entry);
1068 // if currently selected page is a child of the parent page we are folding,
1069 // set the current page to the parent page
1070 if !expanded && selected_page_index == toggle_page_index {
1071 self.navbar_entry = nav_entry_index;
1072 // note: not opening page. Toggling does not change content just selected page
1073 }
1074 }
1075
1076 fn build_navbar(&mut self, cx: &App) {
1077 let mut navbar_entries = Vec::new();
1078
1079 for (page_index, page) in self.pages.iter().enumerate() {
1080 navbar_entries.push(NavBarEntry {
1081 title: page.title,
1082 is_root: true,
1083 expanded: false,
1084 page_index,
1085 item_index: None,
1086 focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1087 });
1088
1089 for (item_index, item) in page.items.iter().enumerate() {
1090 let SettingsPageItem::SectionHeader(title) = item else {
1091 continue;
1092 };
1093 navbar_entries.push(NavBarEntry {
1094 title,
1095 is_root: false,
1096 expanded: false,
1097 page_index,
1098 item_index: Some(item_index),
1099 focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1100 });
1101 }
1102 }
1103
1104 self.navbar_entries = navbar_entries;
1105 }
1106
1107 fn setup_navbar_focus_subscriptions(
1108 &mut self,
1109 window: &mut Window,
1110 cx: &mut Context<SettingsWindow>,
1111 ) {
1112 let mut focus_subscriptions = Vec::new();
1113
1114 for entry_index in 0..self.navbar_entries.len() {
1115 let focus_handle = self.navbar_entries[entry_index].focus_handle.clone();
1116
1117 let subscription = cx.on_focus(
1118 &focus_handle,
1119 window,
1120 move |this: &mut SettingsWindow,
1121 window: &mut Window,
1122 cx: &mut Context<SettingsWindow>| {
1123 this.open_and_scroll_to_navbar_entry(entry_index, window, cx, false);
1124 },
1125 );
1126 focus_subscriptions.push(subscription);
1127 }
1128 self.navbar_focus_subscriptions = focus_subscriptions;
1129 }
1130
1131 fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
1132 let mut index = 0;
1133 let entries = &self.navbar_entries;
1134 let search_matches = &self.filter_table;
1135 let has_query = self.has_query;
1136 std::iter::from_fn(move || {
1137 while index < entries.len() {
1138 let entry = &entries[index];
1139 let included_in_search = if let Some(item_index) = entry.item_index {
1140 search_matches[entry.page_index][item_index]
1141 } else {
1142 search_matches[entry.page_index].iter().any(|b| *b)
1143 || search_matches[entry.page_index].is_empty()
1144 };
1145 if included_in_search {
1146 break;
1147 }
1148 index += 1;
1149 }
1150 if index >= self.navbar_entries.len() {
1151 return None;
1152 }
1153 let entry = &entries[index];
1154 let entry_index = index;
1155
1156 index += 1;
1157 if entry.is_root && !entry.expanded && !has_query {
1158 while index < entries.len() {
1159 if entries[index].is_root {
1160 break;
1161 }
1162 index += 1;
1163 }
1164 }
1165
1166 return Some((entry_index, entry));
1167 })
1168 }
1169
1170 fn filter_matches_to_file(&mut self) {
1171 let current_file = self.current_file.mask();
1172 for (page, page_filter) in std::iter::zip(&self.pages, &mut self.filter_table) {
1173 let mut header_index = 0;
1174 let mut any_found_since_last_header = true;
1175
1176 for (index, item) in page.items.iter().enumerate() {
1177 match item {
1178 SettingsPageItem::SectionHeader(_) => {
1179 if !any_found_since_last_header {
1180 page_filter[header_index] = false;
1181 }
1182 header_index = index;
1183 any_found_since_last_header = false;
1184 }
1185 SettingsPageItem::SettingItem(SettingItem { files, .. })
1186 | SettingsPageItem::SubPageLink(SubPageLink { files, .. }) => {
1187 if !files.contains(current_file) {
1188 page_filter[index] = false;
1189 } else {
1190 any_found_since_last_header = true;
1191 }
1192 }
1193 }
1194 }
1195 if let Some(last_header) = page_filter.get_mut(header_index)
1196 && !any_found_since_last_header
1197 {
1198 *last_header = false;
1199 }
1200 }
1201 }
1202
1203 fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
1204 self.search_task.take();
1205 let query = self.search_bar.read(cx).text(cx);
1206 if query.is_empty() || self.search_index.is_none() {
1207 for page in &mut self.filter_table {
1208 page.fill(true);
1209 }
1210 self.has_query = false;
1211 self.filter_matches_to_file();
1212 self.reset_list_state();
1213 cx.notify();
1214 return;
1215 }
1216
1217 let search_index = self.search_index.as_ref().unwrap().clone();
1218
1219 fn update_matches_inner(
1220 this: &mut SettingsWindow,
1221 search_index: &SearchIndex,
1222 match_indices: impl Iterator<Item = usize>,
1223 cx: &mut Context<SettingsWindow>,
1224 ) {
1225 for page in &mut this.filter_table {
1226 page.fill(false);
1227 }
1228
1229 for match_index in match_indices {
1230 let SearchItemKey {
1231 page_index,
1232 header_index,
1233 item_index,
1234 } = search_index.key_lut[match_index];
1235 let page = &mut this.filter_table[page_index];
1236 page[header_index] = true;
1237 page[item_index] = true;
1238 }
1239 this.has_query = true;
1240 this.filter_matches_to_file();
1241 this.open_first_nav_page();
1242 this.reset_list_state();
1243 cx.notify();
1244 }
1245
1246 self.search_task = Some(cx.spawn(async move |this, cx| {
1247 let bm25_task = cx.background_spawn({
1248 let search_index = search_index.clone();
1249 let max_results = search_index.key_lut.len();
1250 let query = query.clone();
1251 async move { search_index.bm25_engine.search(&query, max_results) }
1252 });
1253 let cancel_flag = std::sync::atomic::AtomicBool::new(false);
1254 let fuzzy_search_task = fuzzy::match_strings(
1255 search_index.fuzzy_match_candidates.as_slice(),
1256 &query,
1257 false,
1258 true,
1259 search_index.fuzzy_match_candidates.len(),
1260 &cancel_flag,
1261 cx.background_executor().clone(),
1262 );
1263
1264 let fuzzy_matches = fuzzy_search_task.await;
1265
1266 _ = this
1267 .update(cx, |this, cx| {
1268 // For tuning the score threshold
1269 // for fuzzy_match in &fuzzy_matches {
1270 // let SearchItemKey {
1271 // page_index,
1272 // header_index,
1273 // item_index,
1274 // } = search_index.key_lut[fuzzy_match.candidate_id];
1275 // let SettingsPageItem::SectionHeader(header) =
1276 // this.pages[page_index].items[header_index]
1277 // else {
1278 // continue;
1279 // };
1280 // let SettingsPageItem::SettingItem(SettingItem {
1281 // title, description, ..
1282 // }) = this.pages[page_index].items[item_index]
1283 // else {
1284 // continue;
1285 // };
1286 // let score = fuzzy_match.score;
1287 // eprint!("# {header} :: QUERY = {query} :: SCORE = {score}\n{title}\n{description}\n\n");
1288 // }
1289 update_matches_inner(
1290 this,
1291 search_index.as_ref(),
1292 fuzzy_matches
1293 .into_iter()
1294 // MAGIC NUMBER: Was found to have right balance between not too many weird matches, but also
1295 // flexible enough to catch misspellings and <4 letter queries
1296 // More flexible is good for us here because fuzzy matches will only be used for things that don't
1297 // match using bm25
1298 .take_while(|fuzzy_match| fuzzy_match.score >= 0.3)
1299 .map(|fuzzy_match| fuzzy_match.candidate_id),
1300 cx,
1301 );
1302 })
1303 .ok();
1304
1305 let bm25_matches = bm25_task.await;
1306
1307 _ = this
1308 .update(cx, |this, cx| {
1309 if bm25_matches.is_empty() {
1310 return;
1311 }
1312 update_matches_inner(
1313 this,
1314 search_index.as_ref(),
1315 bm25_matches
1316 .into_iter()
1317 .map(|bm25_match| bm25_match.document.id),
1318 cx,
1319 );
1320 })
1321 .ok();
1322 }));
1323 }
1324
1325 fn build_filter_table(&mut self) {
1326 self.filter_table = self
1327 .pages
1328 .iter()
1329 .map(|page| vec![true; page.items.len()])
1330 .collect::<Vec<_>>();
1331 }
1332
1333 fn build_search_index(&mut self) {
1334 let mut key_lut: Vec<SearchItemKey> = vec![];
1335 let mut documents = Vec::default();
1336 let mut fuzzy_match_candidates = Vec::default();
1337
1338 fn push_candidates(
1339 fuzzy_match_candidates: &mut Vec<StringMatchCandidate>,
1340 key_index: usize,
1341 input: &str,
1342 ) {
1343 for word in input.split_ascii_whitespace() {
1344 fuzzy_match_candidates.push(StringMatchCandidate::new(key_index, word));
1345 }
1346 }
1347
1348 // PERF: We are currently searching all items even in project files
1349 // where many settings are filtered out, using the logic in filter_matches_to_file
1350 // we could only search relevant items based on the current file
1351 for (page_index, page) in self.pages.iter().enumerate() {
1352 let mut header_index = 0;
1353 let mut header_str = "";
1354 for (item_index, item) in page.items.iter().enumerate() {
1355 let key_index = key_lut.len();
1356 match item {
1357 SettingsPageItem::SettingItem(item) => {
1358 documents.push(bm25::Document {
1359 id: key_index,
1360 contents: [page.title, header_str, item.title, item.description]
1361 .join("\n"),
1362 });
1363 push_candidates(&mut fuzzy_match_candidates, key_index, item.title);
1364 push_candidates(&mut fuzzy_match_candidates, key_index, item.description);
1365 }
1366 SettingsPageItem::SectionHeader(header) => {
1367 documents.push(bm25::Document {
1368 id: key_index,
1369 contents: header.to_string(),
1370 });
1371 push_candidates(&mut fuzzy_match_candidates, key_index, header);
1372 header_index = item_index;
1373 header_str = *header;
1374 }
1375 SettingsPageItem::SubPageLink(sub_page_link) => {
1376 documents.push(bm25::Document {
1377 id: key_index,
1378 contents: [page.title, header_str, sub_page_link.title.as_ref()]
1379 .join("\n"),
1380 });
1381 push_candidates(
1382 &mut fuzzy_match_candidates,
1383 key_index,
1384 sub_page_link.title.as_ref(),
1385 );
1386 }
1387 }
1388 push_candidates(&mut fuzzy_match_candidates, key_index, page.title);
1389 push_candidates(&mut fuzzy_match_candidates, key_index, header_str);
1390
1391 key_lut.push(SearchItemKey {
1392 page_index,
1393 header_index,
1394 item_index,
1395 });
1396 }
1397 }
1398 let engine =
1399 bm25::SearchEngineBuilder::with_documents(bm25::Language::English, documents).build();
1400 self.search_index = Some(Arc::new(SearchIndex {
1401 bm25_engine: engine,
1402 key_lut,
1403 fuzzy_match_candidates,
1404 }));
1405 }
1406
1407 fn build_content_handles(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1408 self.content_handles = self
1409 .pages
1410 .iter()
1411 .map(|page| {
1412 std::iter::repeat_with(|| NonFocusableHandle::new(0, false, window, cx))
1413 .take(page.items.len())
1414 .collect()
1415 })
1416 .collect::<Vec<_>>();
1417 }
1418
1419 fn reset_list_state(&mut self) {
1420 // plus one for the title
1421 self.visible_items = self.visible_page_items().map(|(index, _)| index).collect();
1422
1423 if self.visible_items.is_empty() {
1424 self.list_state.reset(0);
1425 } else {
1426 // show page title if page is non empty
1427 self.list_state.reset(self.visible_items.len() + 1);
1428 }
1429 }
1430
1431 fn build_ui(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1432 if self.pages.is_empty() {
1433 self.pages = page_data::settings_data(cx);
1434 self.build_navbar(cx);
1435 self.setup_navbar_focus_subscriptions(window, cx);
1436 self.build_content_handles(window, cx);
1437 }
1438 sub_page_stack_mut().clear();
1439 // PERF: doesn't have to be rebuilt, can just be filled with true. pages is constant once it is built
1440 self.build_filter_table();
1441 self.reset_list_state();
1442 self.update_matches(cx);
1443
1444 cx.notify();
1445 }
1446
1447 fn fetch_files(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1448 self.worktree_root_dirs.clear();
1449 let prev_files = self.files.clone();
1450 let settings_store = cx.global::<SettingsStore>();
1451 let mut ui_files = vec![];
1452 let all_files = settings_store.get_all_files();
1453 for file in all_files {
1454 let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
1455 continue;
1456 };
1457 if settings_ui_file.is_server() {
1458 continue;
1459 }
1460
1461 if let Some(worktree_id) = settings_ui_file.worktree_id() {
1462 let directory_name = all_projects(cx)
1463 .find_map(|project| project.read(cx).worktree_for_id(worktree_id, cx))
1464 .and_then(|worktree| worktree.read(cx).root_dir())
1465 .and_then(|root_dir| {
1466 root_dir
1467 .file_name()
1468 .map(|os_string| os_string.to_string_lossy().to_string())
1469 });
1470
1471 let Some(directory_name) = directory_name else {
1472 log::error!(
1473 "No directory name found for settings file at worktree ID: {}",
1474 worktree_id
1475 );
1476 continue;
1477 };
1478
1479 self.worktree_root_dirs.insert(worktree_id, directory_name);
1480 }
1481
1482 let focus_handle = prev_files
1483 .iter()
1484 .find_map(|(prev_file, handle)| {
1485 (prev_file == &settings_ui_file).then(|| handle.clone())
1486 })
1487 .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
1488 ui_files.push((settings_ui_file, focus_handle));
1489 }
1490 ui_files.reverse();
1491 self.files = ui_files;
1492 let current_file_still_exists = self
1493 .files
1494 .iter()
1495 .any(|(file, _)| file == &self.current_file);
1496 if !current_file_still_exists {
1497 self.change_file(0, window, false, cx);
1498 }
1499 }
1500
1501 fn open_navbar_entry_page(&mut self, navbar_entry: usize) {
1502 if !self.is_nav_entry_visible(navbar_entry) {
1503 self.open_first_nav_page();
1504 }
1505
1506 let is_new_page = self.navbar_entries[self.navbar_entry].page_index
1507 != self.navbar_entries[navbar_entry].page_index;
1508 self.navbar_entry = navbar_entry;
1509
1510 // We only need to reset visible items when updating matches
1511 // and selecting a new page
1512 if is_new_page {
1513 self.reset_list_state();
1514 }
1515
1516 sub_page_stack_mut().clear();
1517 }
1518
1519 fn open_first_nav_page(&mut self) {
1520 let Some(first_navbar_entry_index) = self.visible_navbar_entries().next().map(|e| e.0)
1521 else {
1522 return;
1523 };
1524 self.open_navbar_entry_page(first_navbar_entry_index);
1525 }
1526
1527 fn change_file(
1528 &mut self,
1529 ix: usize,
1530 window: &mut Window,
1531 drop_down_file: bool,
1532 cx: &mut Context<SettingsWindow>,
1533 ) {
1534 if ix >= self.files.len() {
1535 self.current_file = SettingsUiFile::User;
1536 self.build_ui(window, cx);
1537 return;
1538 }
1539 if drop_down_file {
1540 self.drop_down_file = Some(ix);
1541 }
1542
1543 if self.files[ix].0 == self.current_file {
1544 return;
1545 }
1546 self.current_file = self.files[ix].0.clone();
1547
1548 self.build_ui(window, cx);
1549
1550 if self
1551 .visible_navbar_entries()
1552 .any(|(index, _)| index == self.navbar_entry)
1553 {
1554 self.open_and_scroll_to_navbar_entry(self.navbar_entry, window, cx, true);
1555 } else {
1556 self.open_first_nav_page();
1557 };
1558 }
1559
1560 fn render_files_header(
1561 &self,
1562 window: &mut Window,
1563 cx: &mut Context<SettingsWindow>,
1564 ) -> impl IntoElement {
1565 const OVERFLOW_LIMIT: usize = 1;
1566
1567 let file_button =
1568 |ix, file: &SettingsUiFile, focus_handle, cx: &mut Context<SettingsWindow>| {
1569 Button::new(
1570 ix,
1571 self.display_name(&file)
1572 .expect("Files should always have a name"),
1573 )
1574 .toggle_state(file == &self.current_file)
1575 .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
1576 .track_focus(focus_handle)
1577 .on_click(cx.listener({
1578 let focus_handle = focus_handle.clone();
1579 move |this, _: &gpui::ClickEvent, window, cx| {
1580 this.change_file(ix, window, false, cx);
1581 focus_handle.focus(window);
1582 }
1583 }))
1584 };
1585
1586 let this = cx.entity();
1587
1588 h_flex()
1589 .w_full()
1590 .pb_4()
1591 .gap_1()
1592 .justify_between()
1593 .track_focus(&self.files_focus_handle)
1594 .tab_group()
1595 .tab_index(HEADER_GROUP_TAB_INDEX)
1596 .child(
1597 h_flex()
1598 .gap_1()
1599 .children(
1600 self.files.iter().enumerate().take(OVERFLOW_LIMIT).map(
1601 |(ix, (file, focus_handle))| file_button(ix, file, focus_handle, cx),
1602 ),
1603 )
1604 .when(self.files.len() > OVERFLOW_LIMIT, |div| {
1605 div.children(
1606 self.files
1607 .iter()
1608 .enumerate()
1609 .skip(OVERFLOW_LIMIT)
1610 .find(|(_, (file, _))| file == &self.current_file)
1611 .map(|(ix, (file, focus_handle))| {
1612 file_button(ix, file, focus_handle, cx)
1613 })
1614 .or_else(|| {
1615 let ix = self.drop_down_file.unwrap_or(OVERFLOW_LIMIT);
1616 self.files.get(ix).map(|(file, focus_handle)| {
1617 file_button(ix, file, focus_handle, cx)
1618 })
1619 }),
1620 )
1621 .when(
1622 self.files.len() > OVERFLOW_LIMIT + 1,
1623 |div| {
1624 div.child(
1625 DropdownMenu::new(
1626 "more-files",
1627 format!("+{}", self.files.len() - (OVERFLOW_LIMIT + 1)),
1628 ContextMenu::build(window, cx, move |mut menu, _, _| {
1629 for (ix, (file, focus_handle)) in self
1630 .files
1631 .iter()
1632 .enumerate()
1633 .skip(OVERFLOW_LIMIT + 1)
1634 {
1635 menu = menu.entry(
1636 self.display_name(file)
1637 .expect("Files should always have a name"),
1638 None,
1639 {
1640 let this = this.clone();
1641 let focus_handle = focus_handle.clone();
1642 move |window, cx| {
1643 this.update(cx, |this, cx| {
1644 this.change_file(
1645 ix, window, true, cx,
1646 );
1647 });
1648 focus_handle.focus(window);
1649 }
1650 },
1651 );
1652 }
1653
1654 menu
1655 }),
1656 )
1657 .style(DropdownStyle::Subtle)
1658 .trigger_tooltip(Tooltip::text("View Other Projects"))
1659 .trigger_icon(IconName::ChevronDown)
1660 .attach(gpui::Corner::BottomLeft)
1661 .offset(gpui::Point {
1662 x: px(0.0),
1663 y: px(2.0),
1664 })
1665 .tab_index(0),
1666 )
1667 },
1668 )
1669 }),
1670 )
1671 .child(
1672 Button::new("edit-in-json", "Edit in settings.json")
1673 .tab_index(0_isize)
1674 .style(ButtonStyle::OutlinedGhost)
1675 .on_click(cx.listener(|this, _, _, cx| {
1676 this.open_current_settings_file(cx);
1677 })),
1678 )
1679 }
1680
1681 pub(crate) fn display_name(&self, file: &SettingsUiFile) -> Option<String> {
1682 match file {
1683 SettingsUiFile::User => Some("User".to_string()),
1684 SettingsUiFile::Project((worktree_id, path)) => self
1685 .worktree_root_dirs
1686 .get(&worktree_id)
1687 .map(|directory_name| {
1688 let path_style = PathStyle::local();
1689 if path.is_empty() {
1690 directory_name.clone()
1691 } else {
1692 format!(
1693 "{}{}{}",
1694 directory_name,
1695 path_style.separator(),
1696 path.display(path_style)
1697 )
1698 }
1699 }),
1700 SettingsUiFile::Server(file) => Some(file.to_string()),
1701 }
1702 }
1703
1704 // TODO:
1705 // Reconsider this after preview launch
1706 // fn file_location_str(&self) -> String {
1707 // match &self.current_file {
1708 // SettingsUiFile::User => "settings.json".to_string(),
1709 // SettingsUiFile::Project((worktree_id, path)) => self
1710 // .worktree_root_dirs
1711 // .get(&worktree_id)
1712 // .map(|directory_name| {
1713 // let path_style = PathStyle::local();
1714 // let file_path = path.join(paths::local_settings_file_relative_path());
1715 // format!(
1716 // "{}{}{}",
1717 // directory_name,
1718 // path_style.separator(),
1719 // file_path.display(path_style)
1720 // )
1721 // })
1722 // .expect("Current file should always be present in root dir map"),
1723 // SettingsUiFile::Server(file) => file.to_string(),
1724 // }
1725 // }
1726
1727 fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
1728 h_flex()
1729 .py_1()
1730 .px_1p5()
1731 .mb_3()
1732 .gap_1p5()
1733 .rounded_sm()
1734 .bg(cx.theme().colors().editor_background)
1735 .border_1()
1736 .border_color(cx.theme().colors().border)
1737 .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
1738 .child(self.search_bar.clone())
1739 }
1740
1741 fn render_nav(
1742 &self,
1743 window: &mut Window,
1744 cx: &mut Context<SettingsWindow>,
1745 ) -> impl IntoElement {
1746 let visible_count = self.visible_navbar_entries().count();
1747
1748 let focus_keybind_label = if self
1749 .navbar_focus_handle
1750 .read(cx)
1751 .handle
1752 .contains_focused(window, cx)
1753 {
1754 "Focus Content"
1755 } else {
1756 "Focus Navbar"
1757 };
1758
1759 v_flex()
1760 .w_56()
1761 .p_2p5()
1762 .when(cfg!(target_os = "macos"), |c| c.pt_10())
1763 .h_full()
1764 .flex_none()
1765 .border_r_1()
1766 .key_context("NavigationMenu")
1767 .on_action(cx.listener(|this, _: &CollapseNavEntry, window, cx| {
1768 let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1769 return;
1770 };
1771 let focused_entry_parent = this.root_entry_containing(focused_entry);
1772 if this.navbar_entries[focused_entry_parent].expanded {
1773 this.toggle_navbar_entry(focused_entry_parent);
1774 window.focus(&this.navbar_entries[focused_entry_parent].focus_handle);
1775 }
1776 cx.notify();
1777 }))
1778 .on_action(cx.listener(|this, _: &ExpandNavEntry, window, cx| {
1779 let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1780 return;
1781 };
1782 if !this.navbar_entries[focused_entry].is_root {
1783 return;
1784 }
1785 if !this.navbar_entries[focused_entry].expanded {
1786 this.toggle_navbar_entry(focused_entry);
1787 }
1788 cx.notify();
1789 }))
1790 .on_action(
1791 cx.listener(|this, _: &FocusPreviousRootNavEntry, window, cx| {
1792 let entry_index = this
1793 .focused_nav_entry(window, cx)
1794 .unwrap_or(this.navbar_entry);
1795 let mut root_index = None;
1796 for (index, entry) in this.visible_navbar_entries() {
1797 if index >= entry_index {
1798 break;
1799 }
1800 if entry.is_root {
1801 root_index = Some(index);
1802 }
1803 }
1804 let Some(previous_root_index) = root_index else {
1805 return;
1806 };
1807 this.focus_and_scroll_to_nav_entry(previous_root_index, window, cx);
1808 }),
1809 )
1810 .on_action(cx.listener(|this, _: &FocusNextRootNavEntry, window, cx| {
1811 let entry_index = this
1812 .focused_nav_entry(window, cx)
1813 .unwrap_or(this.navbar_entry);
1814 let mut root_index = None;
1815 for (index, entry) in this.visible_navbar_entries() {
1816 if index <= entry_index {
1817 continue;
1818 }
1819 if entry.is_root {
1820 root_index = Some(index);
1821 break;
1822 }
1823 }
1824 let Some(next_root_index) = root_index else {
1825 return;
1826 };
1827 this.focus_and_scroll_to_nav_entry(next_root_index, window, cx);
1828 }))
1829 .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, cx| {
1830 if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
1831 this.focus_and_scroll_to_nav_entry(first_entry_index, window, cx);
1832 }
1833 }))
1834 .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, cx| {
1835 if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
1836 this.focus_and_scroll_to_nav_entry(last_entry_index, window, cx);
1837 }
1838 }))
1839 .on_action(cx.listener(|this, _: &FocusNextNavEntry, window, cx| {
1840 let entry_index = this
1841 .focused_nav_entry(window, cx)
1842 .unwrap_or(this.navbar_entry);
1843 let mut next_index = None;
1844 for (index, _) in this.visible_navbar_entries() {
1845 if index > entry_index {
1846 next_index = Some(index);
1847 break;
1848 }
1849 }
1850 let Some(next_entry_index) = next_index else {
1851 return;
1852 };
1853 this.open_and_scroll_to_navbar_entry(next_entry_index, window, cx, false);
1854 }))
1855 .on_action(cx.listener(|this, _: &FocusPreviousNavEntry, window, cx| {
1856 let entry_index = this
1857 .focused_nav_entry(window, cx)
1858 .unwrap_or(this.navbar_entry);
1859 let mut prev_index = None;
1860 for (index, _) in this.visible_navbar_entries() {
1861 if index >= entry_index {
1862 break;
1863 }
1864 prev_index = Some(index);
1865 }
1866 let Some(prev_entry_index) = prev_index else {
1867 return;
1868 };
1869 this.open_and_scroll_to_navbar_entry(prev_entry_index, window, cx, false);
1870 }))
1871 .border_color(cx.theme().colors().border)
1872 .bg(cx.theme().colors().panel_background)
1873 .child(self.render_search(window, cx))
1874 .child(
1875 v_flex()
1876 .flex_1()
1877 .overflow_hidden()
1878 .track_focus(&self.navbar_focus_handle.focus_handle(cx))
1879 .tab_group()
1880 .tab_index(NAVBAR_GROUP_TAB_INDEX)
1881 .child(
1882 uniform_list(
1883 "settings-ui-nav-bar",
1884 visible_count + 1,
1885 cx.processor(move |this, range: Range<usize>, _, cx| {
1886 this.visible_navbar_entries()
1887 .skip(range.start.saturating_sub(1))
1888 .take(range.len())
1889 .map(|(ix, entry)| {
1890 TreeViewItem::new(
1891 ("settings-ui-navbar-entry", ix),
1892 entry.title,
1893 )
1894 .track_focus(&entry.focus_handle)
1895 .root_item(entry.is_root)
1896 .toggle_state(this.is_navbar_entry_selected(ix))
1897 .when(entry.is_root, |item| {
1898 item.expanded(entry.expanded || this.has_query)
1899 .on_toggle(cx.listener(
1900 move |this, _, window, cx| {
1901 this.toggle_navbar_entry(ix);
1902 // Update selection state immediately before cx.notify
1903 // to prevent double selection flash
1904 this.navbar_entry = ix;
1905 window.focus(
1906 &this.navbar_entries[ix].focus_handle,
1907 );
1908 cx.notify();
1909 },
1910 ))
1911 })
1912 .on_click(
1913 cx.listener(move |this, _, window, cx| {
1914 this.open_and_scroll_to_navbar_entry(
1915 ix, window, cx, true,
1916 );
1917 }),
1918 )
1919 })
1920 .collect()
1921 }),
1922 )
1923 .size_full()
1924 .track_scroll(self.navbar_scroll_handle.clone()),
1925 )
1926 .vertical_scrollbar_for(self.navbar_scroll_handle.clone(), window, cx),
1927 )
1928 .child(
1929 h_flex()
1930 .w_full()
1931 .h_8()
1932 .p_2()
1933 .pb_0p5()
1934 .flex_shrink_0()
1935 .border_t_1()
1936 .border_color(cx.theme().colors().border_variant)
1937 .children(
1938 KeyBinding::for_action(&ToggleFocusNav, window, cx).map(|this| {
1939 KeybindingHint::new(
1940 this,
1941 cx.theme().colors().surface_background.opacity(0.5),
1942 )
1943 .suffix(focus_keybind_label)
1944 }),
1945 ),
1946 )
1947 }
1948
1949 fn open_and_scroll_to_navbar_entry(
1950 &mut self,
1951 navbar_entry_index: usize,
1952 window: &mut Window,
1953 cx: &mut Context<Self>,
1954 focus_content: bool,
1955 ) {
1956 self.open_navbar_entry_page(navbar_entry_index);
1957 cx.notify();
1958
1959 if self.navbar_entries[navbar_entry_index].is_root
1960 || !self.is_nav_entry_visible(navbar_entry_index)
1961 {
1962 self.sub_page_scroll_handle
1963 .set_offset(point(px(0.), px(0.)));
1964 if focus_content {
1965 let Some(first_item_index) =
1966 self.visible_page_items().next().map(|(index, _)| index)
1967 else {
1968 return;
1969 };
1970 self.focus_content_element(first_item_index, window, cx);
1971 } else {
1972 window.focus(&self.navbar_entries[navbar_entry_index].focus_handle);
1973 }
1974 } else {
1975 let entry_item_index = self.navbar_entries[navbar_entry_index]
1976 .item_index
1977 .expect("Non-root items should have an item index");
1978 let Some(selected_item_index) = self
1979 .visible_page_items()
1980 .position(|(index, _)| index == entry_item_index)
1981 else {
1982 return;
1983 };
1984
1985 self.list_state.scroll_to(gpui::ListOffset {
1986 item_ix: selected_item_index + 1,
1987 offset_in_item: px(0.),
1988 });
1989 if focus_content {
1990 self.focus_content_element(entry_item_index, window, cx);
1991 } else {
1992 window.focus(&self.navbar_entries[navbar_entry_index].focus_handle);
1993 }
1994 }
1995
1996 // Page scroll handle updates the active item index
1997 // in it's next paint call after using scroll_handle.scroll_to_top_of_item
1998 // The call after that updates the offset of the scroll handle. So to
1999 // ensure the scroll handle doesn't lag behind we need to render three frames
2000 // back to back.
2001 cx.on_next_frame(window, |_, window, cx| {
2002 cx.on_next_frame(window, |_, _, cx| {
2003 cx.notify();
2004 });
2005 cx.notify();
2006 });
2007 cx.notify();
2008 }
2009
2010 fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
2011 self.visible_navbar_entries()
2012 .any(|(index, _)| index == nav_entry_index)
2013 }
2014
2015 fn focus_and_scroll_to_nav_entry(
2016 &self,
2017 nav_entry_index: usize,
2018 window: &mut Window,
2019 cx: &mut Context<Self>,
2020 ) {
2021 let Some(position) = self
2022 .visible_navbar_entries()
2023 .position(|(index, _)| index == nav_entry_index)
2024 else {
2025 return;
2026 };
2027 self.navbar_scroll_handle
2028 .scroll_to_item(position, gpui::ScrollStrategy::Top);
2029 window.focus(&self.navbar_entries[nav_entry_index].focus_handle);
2030 cx.notify();
2031 }
2032
2033 fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
2034 let page_idx = self.current_page_index();
2035
2036 self.current_page()
2037 .items
2038 .iter()
2039 .enumerate()
2040 .filter_map(move |(item_index, item)| {
2041 self.filter_table[page_idx][item_index].then_some((item_index, item))
2042 })
2043 }
2044
2045 fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
2046 let mut items = vec![];
2047 items.push(self.current_page().title.into());
2048 items.extend(
2049 sub_page_stack()
2050 .iter()
2051 .flat_map(|page| [page.section_header.into(), page.link.title.clone()]),
2052 );
2053
2054 let last = items.pop().unwrap();
2055 h_flex()
2056 .gap_1()
2057 .children(
2058 items
2059 .into_iter()
2060 .flat_map(|item| [item, "/".into()])
2061 .map(|item| Label::new(item).color(Color::Muted)),
2062 )
2063 .child(Label::new(last))
2064 }
2065
2066 fn render_page_items(
2067 &mut self,
2068 page_index: Option<usize>,
2069 _window: &mut Window,
2070 cx: &mut Context<SettingsWindow>,
2071 ) -> impl IntoElement {
2072 let mut page_content = v_flex().id("settings-ui-page").size_full();
2073
2074 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2075 let has_no_results = self.visible_items.len() == 0 && has_active_search;
2076
2077 if has_no_results {
2078 let search_query = self.search_bar.read(cx).text(cx);
2079 page_content = page_content.child(
2080 v_flex()
2081 .size_full()
2082 .items_center()
2083 .justify_center()
2084 .gap_1()
2085 .child(div().child("No Results"))
2086 .child(
2087 div()
2088 .text_sm()
2089 .text_color(cx.theme().colors().text_muted)
2090 .child(format!("No settings match \"{}\"", search_query)),
2091 ),
2092 )
2093 } else {
2094 let items = &self.current_page().items;
2095
2096 let last_non_header_index = self
2097 .visible_items
2098 .iter()
2099 .map(|index| &items[*index])
2100 .enumerate()
2101 .rev()
2102 .find(|(_, item)| !matches!(item, SettingsPageItem::SectionHeader(_)))
2103 .map(|(index, _)| index);
2104
2105 let root_nav_label = self
2106 .navbar_entries
2107 .iter()
2108 .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2109 .map(|entry| entry.title);
2110
2111 let list_content = list(
2112 self.list_state.clone(),
2113 cx.processor(move |this, index, window, cx| {
2114 if index == 0 {
2115 return div()
2116 .when(sub_page_stack().is_empty(), |this| {
2117 this.when_some(root_nav_label, |this, title| {
2118 this.child(
2119 Label::new(title).size(LabelSize::Large).mt_2().mb_3(),
2120 )
2121 })
2122 })
2123 .into_any_element();
2124 }
2125
2126 let index = index - 1;
2127 let actual_item_index = this.visible_items[index];
2128 let item: &SettingsPageItem = &this.current_page().items[actual_item_index];
2129
2130 let no_bottom_border = this
2131 .visible_items
2132 .get(index + 1)
2133 .map(|item_index| {
2134 let item = &this.current_page().items[*item_index];
2135 matches!(item, SettingsPageItem::SectionHeader(_))
2136 })
2137 .unwrap_or(false);
2138 let is_last = Some(index) == last_non_header_index;
2139
2140 v_flex()
2141 .id(("settings-page-item", actual_item_index))
2142 .w_full()
2143 .min_w_0()
2144 .when_some(page_index, |element, page_index| {
2145 element.track_focus(
2146 &this.content_handles[page_index][actual_item_index]
2147 .focus_handle(cx),
2148 )
2149 })
2150 .child(item.render(
2151 this,
2152 actual_item_index,
2153 no_bottom_border || is_last,
2154 window,
2155 cx,
2156 ))
2157 .into_any_element()
2158 }),
2159 );
2160
2161 page_content = page_content.child(list_content.size_full())
2162 }
2163 page_content
2164 }
2165
2166 fn render_sub_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
2167 &self,
2168 items: Items,
2169 page_index: Option<usize>,
2170 window: &mut Window,
2171 cx: &mut Context<SettingsWindow>,
2172 ) -> impl IntoElement {
2173 let mut page_content = v_flex()
2174 .id("settings-ui-page")
2175 .size_full()
2176 .overflow_y_scroll()
2177 .track_scroll(&self.sub_page_scroll_handle);
2178
2179 let items: Vec<_> = items.collect();
2180 let items_len = items.len();
2181 let mut section_header = None;
2182
2183 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2184 let has_no_results = items_len == 0 && has_active_search;
2185
2186 if has_no_results {
2187 let search_query = self.search_bar.read(cx).text(cx);
2188 page_content = page_content.child(
2189 v_flex()
2190 .size_full()
2191 .items_center()
2192 .justify_center()
2193 .gap_1()
2194 .child(div().child("No Results"))
2195 .child(
2196 div()
2197 .text_sm()
2198 .text_color(cx.theme().colors().text_muted)
2199 .child(format!("No settings match \"{}\"", search_query)),
2200 ),
2201 )
2202 } else {
2203 let last_non_header_index = items
2204 .iter()
2205 .enumerate()
2206 .rev()
2207 .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
2208 .map(|(index, _)| index);
2209
2210 let root_nav_label = self
2211 .navbar_entries
2212 .iter()
2213 .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2214 .map(|entry| entry.title);
2215
2216 page_content = page_content
2217 .when(sub_page_stack().is_empty(), |this| {
2218 this.when_some(root_nav_label, |this, title| {
2219 this.child(Label::new(title).size(LabelSize::Large).mt_2().mb_3())
2220 })
2221 })
2222 .children(items.clone().into_iter().enumerate().map(
2223 |(index, (actual_item_index, item))| {
2224 let no_bottom_border = items
2225 .get(index + 1)
2226 .map(|(_, next_item)| {
2227 matches!(next_item, SettingsPageItem::SectionHeader(_))
2228 })
2229 .unwrap_or(false);
2230 let is_last = Some(index) == last_non_header_index;
2231
2232 if let SettingsPageItem::SectionHeader(header) = item {
2233 section_header = Some(*header);
2234 }
2235 v_flex()
2236 .w_full()
2237 .min_w_0()
2238 .id(("settings-page-item", actual_item_index))
2239 .when_some(page_index, |element, page_index| {
2240 element.track_focus(
2241 &self.content_handles[page_index][actual_item_index]
2242 .focus_handle(cx),
2243 )
2244 })
2245 .child(item.render(
2246 self,
2247 actual_item_index,
2248 no_bottom_border || is_last,
2249 window,
2250 cx,
2251 ))
2252 },
2253 ))
2254 }
2255 page_content
2256 }
2257
2258 fn render_page(
2259 &mut self,
2260 window: &mut Window,
2261 cx: &mut Context<SettingsWindow>,
2262 ) -> impl IntoElement {
2263 let page_header;
2264 let page_content;
2265
2266 if sub_page_stack().is_empty() {
2267 page_header = self.render_files_header(window, cx).into_any_element();
2268
2269 page_content = self
2270 .render_page_items(Some(self.current_page_index()), window, cx)
2271 .into_any_element();
2272 } else {
2273 page_header = h_flex()
2274 .ml_neg_1p5()
2275 .pb_4()
2276 .gap_1()
2277 .child(
2278 IconButton::new("back-btn", IconName::ArrowLeft)
2279 .icon_size(IconSize::Small)
2280 .shape(IconButtonShape::Square)
2281 .on_click(cx.listener(|this, _, _, cx| {
2282 this.pop_sub_page(cx);
2283 })),
2284 )
2285 .child(self.render_sub_page_breadcrumbs())
2286 .into_any_element();
2287
2288 let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
2289 page_content = (active_page_render_fn)(self, window, cx);
2290 }
2291
2292 return v_flex()
2293 .id("Settings-ui-page")
2294 .flex_1()
2295 .pt_6()
2296 .pb_8()
2297 .px_8()
2298 .bg(cx.theme().colors().editor_background)
2299 .child(page_header)
2300 .when(sub_page_stack().is_empty(), |this| {
2301 this.vertical_scrollbar_for(self.list_state.clone(), window, cx)
2302 })
2303 .when(!sub_page_stack().is_empty(), |this| {
2304 this.vertical_scrollbar_for(self.sub_page_scroll_handle.clone(), window, cx)
2305 })
2306 .track_focus(&self.content_focus_handle.focus_handle(cx))
2307 .child(
2308 div()
2309 .size_full()
2310 .tab_group()
2311 .tab_index(CONTENT_GROUP_TAB_INDEX)
2312 .child(page_content),
2313 );
2314 }
2315
2316 fn open_current_settings_file(&mut self, cx: &mut Context<Self>) {
2317 match &self.current_file {
2318 SettingsUiFile::User => {
2319 let Some(original_window) = self.original_window else {
2320 return;
2321 };
2322 original_window
2323 .update(cx, |workspace, window, cx| {
2324 workspace
2325 .with_local_workspace(window, cx, |workspace, window, cx| {
2326 let create_task = workspace.project().update(cx, |project, cx| {
2327 project.find_or_create_worktree(
2328 paths::config_dir().as_path(),
2329 false,
2330 cx,
2331 )
2332 });
2333 let open_task = workspace.open_paths(
2334 vec![paths::settings_file().to_path_buf()],
2335 OpenOptions {
2336 visible: Some(OpenVisible::None),
2337 ..Default::default()
2338 },
2339 None,
2340 window,
2341 cx,
2342 );
2343
2344 cx.spawn_in(window, async move |workspace, cx| {
2345 create_task.await.ok();
2346 open_task.await;
2347
2348 workspace.update_in(cx, |_, window, cx| {
2349 window.activate_window();
2350 cx.notify();
2351 })
2352 })
2353 .detach();
2354 })
2355 .detach();
2356 })
2357 .ok();
2358 }
2359 SettingsUiFile::Project((worktree_id, path)) => {
2360 let mut corresponding_workspace: Option<WindowHandle<Workspace>> = None;
2361 let settings_path = path.join(paths::local_settings_file_relative_path());
2362 let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
2363 return;
2364 };
2365 for workspace in app_state.workspace_store.read(cx).workspaces() {
2366 let contains_settings_file = workspace
2367 .read_with(cx, |workspace, cx| {
2368 workspace.project().read(cx).contains_local_settings_file(
2369 *worktree_id,
2370 settings_path.as_ref(),
2371 cx,
2372 )
2373 })
2374 .ok();
2375 if Some(true) == contains_settings_file {
2376 corresponding_workspace = Some(*workspace);
2377
2378 break;
2379 }
2380 }
2381
2382 let Some(corresponding_workspace) = corresponding_workspace else {
2383 log::error!(
2384 "No corresponding workspace found for settings file {}",
2385 settings_path.as_std_path().display()
2386 );
2387
2388 return;
2389 };
2390
2391 // TODO: move zed::open_local_file() APIs to this crate, and
2392 // re-implement the "initial_contents" behavior
2393 corresponding_workspace
2394 .update(cx, |workspace, window, cx| {
2395 let open_task = workspace.open_path(
2396 (*worktree_id, settings_path.clone()),
2397 None,
2398 true,
2399 window,
2400 cx,
2401 );
2402
2403 cx.spawn_in(window, async move |workspace, cx| {
2404 if open_task.await.log_err().is_some() {
2405 workspace
2406 .update_in(cx, |_, window, cx| {
2407 window.activate_window();
2408 cx.notify();
2409 })
2410 .ok();
2411 }
2412 })
2413 .detach();
2414 })
2415 .ok();
2416 }
2417 SettingsUiFile::Server(_) => {
2418 return;
2419 }
2420 };
2421 }
2422
2423 fn current_page_index(&self) -> usize {
2424 self.page_index_from_navbar_index(self.navbar_entry)
2425 }
2426
2427 fn current_page(&self) -> &SettingsPage {
2428 &self.pages[self.current_page_index()]
2429 }
2430
2431 fn page_index_from_navbar_index(&self, index: usize) -> usize {
2432 if self.navbar_entries.is_empty() {
2433 return 0;
2434 }
2435
2436 self.navbar_entries[index].page_index
2437 }
2438
2439 fn is_navbar_entry_selected(&self, ix: usize) -> bool {
2440 ix == self.navbar_entry
2441 }
2442
2443 fn push_sub_page(
2444 &mut self,
2445 sub_page_link: SubPageLink,
2446 section_header: &'static str,
2447 cx: &mut Context<SettingsWindow>,
2448 ) {
2449 sub_page_stack_mut().push(SubPage {
2450 link: sub_page_link,
2451 section_header,
2452 });
2453 cx.notify();
2454 }
2455
2456 fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
2457 sub_page_stack_mut().pop();
2458 cx.notify();
2459 }
2460
2461 fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
2462 if let Some((_, handle)) = self.files.get(index) {
2463 handle.focus(window);
2464 }
2465 }
2466
2467 fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
2468 if self.files_focus_handle.contains_focused(window, cx)
2469 && let Some(index) = self
2470 .files
2471 .iter()
2472 .position(|(_, handle)| handle.is_focused(window))
2473 {
2474 return index;
2475 }
2476 if let Some(current_file_index) = self
2477 .files
2478 .iter()
2479 .position(|(file, _)| file == &self.current_file)
2480 {
2481 return current_file_index;
2482 }
2483 0
2484 }
2485
2486 fn focus_content_element(&self, item_index: usize, window: &mut Window, cx: &mut App) {
2487 if !sub_page_stack().is_empty() {
2488 return;
2489 }
2490 let page_index = self.current_page_index();
2491 window.focus(&self.content_handles[page_index][item_index].focus_handle(cx));
2492 }
2493
2494 fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
2495 if !self
2496 .navbar_focus_handle
2497 .focus_handle(cx)
2498 .contains_focused(window, cx)
2499 {
2500 return None;
2501 }
2502 for (index, entry) in self.navbar_entries.iter().enumerate() {
2503 if entry.focus_handle.is_focused(window) {
2504 return Some(index);
2505 }
2506 }
2507 None
2508 }
2509
2510 fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
2511 let mut index = Some(nav_entry_index);
2512 while let Some(prev_index) = index
2513 && !self.navbar_entries[prev_index].is_root
2514 {
2515 index = prev_index.checked_sub(1);
2516 }
2517 return index.expect("No root entry found");
2518 }
2519}
2520
2521impl Render for SettingsWindow {
2522 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2523 let ui_font = theme::setup_ui_font(window, cx);
2524
2525 client_side_decorations(
2526 v_flex()
2527 .text_color(cx.theme().colors().text)
2528 .size_full()
2529 .children(self.title_bar.clone())
2530 .child(
2531 div()
2532 .id("settings-window")
2533 .key_context("SettingsWindow")
2534 .track_focus(&self.focus_handle)
2535 .on_action(cx.listener(|this, _: &OpenCurrentFile, _, cx| {
2536 this.open_current_settings_file(cx);
2537 }))
2538 .on_action(|_: &Minimize, window, _cx| {
2539 window.minimize_window();
2540 })
2541 .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
2542 this.search_bar.focus_handle(cx).focus(window);
2543 }))
2544 .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
2545 if this
2546 .navbar_focus_handle
2547 .focus_handle(cx)
2548 .contains_focused(window, cx)
2549 {
2550 this.open_and_scroll_to_navbar_entry(
2551 this.navbar_entry,
2552 window,
2553 cx,
2554 true,
2555 );
2556 } else {
2557 this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
2558 }
2559 }))
2560 .on_action(cx.listener(
2561 |this, FocusFile(file_index): &FocusFile, window, _| {
2562 this.focus_file_at_index(*file_index as usize, window);
2563 },
2564 ))
2565 .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
2566 let next_index = usize::min(
2567 this.focused_file_index(window, cx) + 1,
2568 this.files.len().saturating_sub(1),
2569 );
2570 this.focus_file_at_index(next_index, window);
2571 }))
2572 .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
2573 let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
2574 this.focus_file_at_index(prev_index, window);
2575 }))
2576 .on_action(|_: &menu::SelectNext, window, _| {
2577 window.focus_next();
2578 })
2579 .on_action(|_: &menu::SelectPrevious, window, _| {
2580 window.focus_prev();
2581 })
2582 .flex()
2583 .flex_row()
2584 .flex_1()
2585 .min_h_0()
2586 .font(ui_font)
2587 .bg(cx.theme().colors().background)
2588 .text_color(cx.theme().colors().text)
2589 .child(self.render_nav(window, cx))
2590 .child(self.render_page(window, cx)),
2591 ),
2592 window,
2593 cx,
2594 )
2595 }
2596}
2597
2598fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
2599 workspace::AppState::global(cx)
2600 .upgrade()
2601 .map(|app_state| {
2602 app_state
2603 .workspace_store
2604 .read(cx)
2605 .workspaces()
2606 .iter()
2607 .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
2608 })
2609 .into_iter()
2610 .flatten()
2611}
2612
2613fn update_settings_file(
2614 file: SettingsUiFile,
2615 cx: &mut App,
2616 update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
2617) -> Result<()> {
2618 match file {
2619 SettingsUiFile::Project((worktree_id, rel_path)) => {
2620 let rel_path = rel_path.join(paths::local_settings_file_relative_path());
2621 let project = all_projects(cx).find(|project| {
2622 project.read_with(cx, |project, cx| {
2623 project.contains_local_settings_file(worktree_id, &rel_path, cx)
2624 })
2625 });
2626 let Some(project) = project else {
2627 anyhow::bail!(
2628 "Could not find worktree containing settings file: {}",
2629 &rel_path.display(PathStyle::local())
2630 );
2631 };
2632 project.update(cx, |project, cx| {
2633 project.update_local_settings_file(worktree_id, rel_path, cx, update);
2634 });
2635 return Ok(());
2636 }
2637 SettingsUiFile::User => {
2638 // todo(settings_ui) error?
2639 SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
2640 Ok(())
2641 }
2642 SettingsUiFile::Server(_) => unimplemented!(),
2643 }
2644}
2645
2646fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
2647 field: SettingField<T>,
2648 file: SettingsUiFile,
2649 metadata: Option<&SettingsFieldMetadata>,
2650 _window: &mut Window,
2651 cx: &mut App,
2652) -> AnyElement {
2653 let (_, initial_text) =
2654 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2655 let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
2656
2657 SettingsEditor::new()
2658 .tab_index(0)
2659 .when_some(initial_text, |editor, text| {
2660 editor.with_initial_text(text.as_ref().to_string())
2661 })
2662 .when_some(
2663 metadata.and_then(|metadata| metadata.placeholder),
2664 |editor, placeholder| editor.with_placeholder(placeholder),
2665 )
2666 .on_confirm({
2667 move |new_text, cx| {
2668 update_settings_file(file.clone(), cx, move |settings, _cx| {
2669 *(field.pick_mut)(settings) = new_text.map(Into::into);
2670 })
2671 .log_err(); // todo(settings_ui) don't log err
2672 }
2673 })
2674 .into_any_element()
2675}
2676
2677fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
2678 field: SettingField<B>,
2679 file: SettingsUiFile,
2680 _metadata: Option<&SettingsFieldMetadata>,
2681 _window: &mut Window,
2682 cx: &mut App,
2683) -> AnyElement {
2684 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2685
2686 let toggle_state = if value.copied().map_or(false, Into::into) {
2687 ToggleState::Selected
2688 } else {
2689 ToggleState::Unselected
2690 };
2691
2692 Switch::new("toggle_button", toggle_state)
2693 .color(ui::SwitchColor::Accent)
2694 .on_click({
2695 move |state, _window, cx| {
2696 let state = *state == ui::ToggleState::Selected;
2697 update_settings_file(file.clone(), cx, move |settings, _cx| {
2698 *(field.pick_mut)(settings) = Some(state.into());
2699 })
2700 .log_err(); // todo(settings_ui) don't log err
2701 }
2702 })
2703 .tab_index(0_isize)
2704 .color(SwitchColor::Accent)
2705 .into_any_element()
2706}
2707
2708fn render_font_picker(
2709 field: SettingField<settings::FontFamilyName>,
2710 file: SettingsUiFile,
2711 _metadata: Option<&SettingsFieldMetadata>,
2712 window: &mut Window,
2713 cx: &mut App,
2714) -> AnyElement {
2715 let current_value = SettingsStore::global(cx)
2716 .get_value_from_file(file.to_settings(), field.pick)
2717 .1
2718 .cloned()
2719 .unwrap_or_else(|| SharedString::default().into());
2720
2721 let font_picker = cx.new(|cx| {
2722 ui_input::font_picker(
2723 current_value.clone().into(),
2724 move |font_name, cx| {
2725 update_settings_file(file.clone(), cx, move |settings, _cx| {
2726 *(field.pick_mut)(settings) = Some(font_name.into());
2727 })
2728 .log_err(); // todo(settings_ui) don't log err
2729 },
2730 window,
2731 cx,
2732 )
2733 });
2734
2735 PopoverMenu::new("font-picker")
2736 .menu(move |_window, _cx| Some(font_picker.clone()))
2737 .trigger(
2738 Button::new("font-family-button", current_value)
2739 .tab_index(0_isize)
2740 .style(ButtonStyle::Outlined)
2741 .size(ButtonSize::Medium)
2742 .icon(IconName::ChevronUpDown)
2743 .icon_color(Color::Muted)
2744 .icon_size(IconSize::Small)
2745 .icon_position(IconPosition::End),
2746 )
2747 .anchor(gpui::Corner::TopLeft)
2748 .offset(gpui::Point {
2749 x: px(0.0),
2750 y: px(2.0),
2751 })
2752 .with_handle(ui::PopoverMenuHandle::default())
2753 .into_any_element()
2754}
2755
2756fn render_number_field<T: NumberFieldType + Send + Sync>(
2757 field: SettingField<T>,
2758 file: SettingsUiFile,
2759 _metadata: Option<&SettingsFieldMetadata>,
2760 window: &mut Window,
2761 cx: &mut App,
2762) -> AnyElement {
2763 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2764 let value = value.copied().unwrap_or_else(T::min_value);
2765 NumberField::new("numeric_stepper", value, window, cx)
2766 .on_change({
2767 move |value, _window, cx| {
2768 let value = *value;
2769 update_settings_file(file.clone(), cx, move |settings, _cx| {
2770 *(field.pick_mut)(settings) = Some(value);
2771 })
2772 .log_err(); // todo(settings_ui) don't log err
2773 }
2774 })
2775 .into_any_element()
2776}
2777
2778fn render_dropdown<T>(
2779 field: SettingField<T>,
2780 file: SettingsUiFile,
2781 metadata: Option<&SettingsFieldMetadata>,
2782 window: &mut Window,
2783 cx: &mut App,
2784) -> AnyElement
2785where
2786 T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
2787{
2788 let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
2789 let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
2790 let should_do_titlecase = metadata
2791 .and_then(|metadata| metadata.should_do_titlecase)
2792 .unwrap_or(true);
2793
2794 let (_, current_value) =
2795 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2796 let current_value = current_value.copied().unwrap_or(variants()[0]);
2797
2798 let current_value_label =
2799 labels()[variants().iter().position(|v| *v == current_value).unwrap()];
2800
2801 DropdownMenu::new(
2802 "dropdown",
2803 if should_do_titlecase {
2804 current_value_label.to_title_case()
2805 } else {
2806 current_value_label.to_string()
2807 },
2808 ContextMenu::build(window, cx, move |mut menu, _, _| {
2809 for (&value, &label) in std::iter::zip(variants(), labels()) {
2810 let file = file.clone();
2811 menu = menu.toggleable_entry(
2812 if should_do_titlecase {
2813 label.to_title_case()
2814 } else {
2815 label.to_string()
2816 },
2817 value == current_value,
2818 IconPosition::End,
2819 None,
2820 move |_, cx| {
2821 if value == current_value {
2822 return;
2823 }
2824 update_settings_file(file.clone(), cx, move |settings, _cx| {
2825 *(field.pick_mut)(settings) = Some(value);
2826 })
2827 .log_err(); // todo(settings_ui) don't log err
2828 },
2829 );
2830 }
2831 menu
2832 }),
2833 )
2834 .trigger_size(ButtonSize::Medium)
2835 .style(DropdownStyle::Outlined)
2836 .offset(gpui::Point {
2837 x: px(0.0),
2838 y: px(2.0),
2839 })
2840 .tab_index(0)
2841 .into_any_element()
2842}
2843
2844#[cfg(test)]
2845mod test {
2846
2847 use super::*;
2848
2849 impl SettingsWindow {
2850 fn navbar_entry(&self) -> usize {
2851 self.navbar_entry
2852 }
2853 }
2854
2855 impl PartialEq for NavBarEntry {
2856 fn eq(&self, other: &Self) -> bool {
2857 self.title == other.title
2858 && self.is_root == other.is_root
2859 && self.expanded == other.expanded
2860 && self.page_index == other.page_index
2861 && self.item_index == other.item_index
2862 // ignoring focus_handle
2863 }
2864 }
2865
2866 fn register_settings(cx: &mut App) {
2867 settings::init(cx);
2868 theme::init(theme::LoadThemes::JustBase, cx);
2869 workspace::init_settings(cx);
2870 project::Project::init_settings(cx);
2871 language::init(cx);
2872 editor::init(cx);
2873 menu::init();
2874 }
2875
2876 fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
2877 let mut pages: Vec<SettingsPage> = Vec::new();
2878 let mut expanded_pages = Vec::new();
2879 let mut selected_idx = None;
2880 let mut index = 0;
2881 let mut in_expanded_section = false;
2882
2883 for mut line in input
2884 .lines()
2885 .map(|line| line.trim())
2886 .filter(|line| !line.is_empty())
2887 {
2888 if let Some(pre) = line.strip_suffix('*') {
2889 assert!(selected_idx.is_none(), "Only one selected entry allowed");
2890 selected_idx = Some(index);
2891 line = pre;
2892 }
2893 let (kind, title) = line.split_once(" ").unwrap();
2894 assert_eq!(kind.len(), 1);
2895 let kind = kind.chars().next().unwrap();
2896 if kind == 'v' {
2897 let page_idx = pages.len();
2898 expanded_pages.push(page_idx);
2899 pages.push(SettingsPage {
2900 title,
2901 items: vec![],
2902 });
2903 index += 1;
2904 in_expanded_section = true;
2905 } else if kind == '>' {
2906 pages.push(SettingsPage {
2907 title,
2908 items: vec![],
2909 });
2910 index += 1;
2911 in_expanded_section = false;
2912 } else if kind == '-' {
2913 pages
2914 .last_mut()
2915 .unwrap()
2916 .items
2917 .push(SettingsPageItem::SectionHeader(title));
2918 if selected_idx == Some(index) && !in_expanded_section {
2919 panic!("Items in unexpanded sections cannot be selected");
2920 }
2921 index += 1;
2922 } else {
2923 panic!(
2924 "Entries must start with one of 'v', '>', or '-'\n line: {}",
2925 line
2926 );
2927 }
2928 }
2929
2930 let mut settings_window = SettingsWindow {
2931 title_bar: None,
2932 original_window: None,
2933 worktree_root_dirs: HashMap::default(),
2934 files: Vec::default(),
2935 current_file: crate::SettingsUiFile::User,
2936 drop_down_file: None,
2937 pages,
2938 search_bar: cx.new(|cx| Editor::single_line(window, cx)),
2939 navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
2940 navbar_entries: Vec::default(),
2941 navbar_scroll_handle: UniformListScrollHandle::default(),
2942 navbar_focus_subscriptions: vec![],
2943 filter_table: vec![],
2944 has_query: false,
2945 content_handles: vec![],
2946 search_task: None,
2947 sub_page_scroll_handle: ScrollHandle::new(),
2948 focus_handle: cx.focus_handle(),
2949 navbar_focus_handle: NonFocusableHandle::new(
2950 NAVBAR_CONTAINER_TAB_INDEX,
2951 false,
2952 window,
2953 cx,
2954 ),
2955 content_focus_handle: NonFocusableHandle::new(
2956 CONTENT_CONTAINER_TAB_INDEX,
2957 false,
2958 window,
2959 cx,
2960 ),
2961 files_focus_handle: cx.focus_handle(),
2962 search_index: None,
2963 visible_items: Vec::default(),
2964 list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
2965 };
2966
2967 settings_window.build_filter_table();
2968 settings_window.build_navbar(cx);
2969 for expanded_page_index in expanded_pages {
2970 for entry in &mut settings_window.navbar_entries {
2971 if entry.page_index == expanded_page_index && entry.is_root {
2972 entry.expanded = true;
2973 }
2974 }
2975 }
2976 settings_window
2977 }
2978
2979 #[track_caller]
2980 fn check_navbar_toggle(
2981 before: &'static str,
2982 toggle_page: &'static str,
2983 after: &'static str,
2984 window: &mut Window,
2985 cx: &mut App,
2986 ) {
2987 let mut settings_window = parse(before, window, cx);
2988 let toggle_page_idx = settings_window
2989 .pages
2990 .iter()
2991 .position(|page| page.title == toggle_page)
2992 .expect("page not found");
2993 let toggle_idx = settings_window
2994 .navbar_entries
2995 .iter()
2996 .position(|entry| entry.page_index == toggle_page_idx)
2997 .expect("page not found");
2998 settings_window.toggle_navbar_entry(toggle_idx);
2999
3000 let expected_settings_window = parse(after, window, cx);
3001
3002 pretty_assertions::assert_eq!(
3003 settings_window
3004 .visible_navbar_entries()
3005 .map(|(_, entry)| entry)
3006 .collect::<Vec<_>>(),
3007 expected_settings_window
3008 .visible_navbar_entries()
3009 .map(|(_, entry)| entry)
3010 .collect::<Vec<_>>(),
3011 );
3012 pretty_assertions::assert_eq!(
3013 settings_window.navbar_entries[settings_window.navbar_entry()],
3014 expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
3015 );
3016 }
3017
3018 macro_rules! check_navbar_toggle {
3019 ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
3020 #[gpui::test]
3021 fn $name(cx: &mut gpui::TestAppContext) {
3022 let window = cx.add_empty_window();
3023 window.update(|window, cx| {
3024 register_settings(cx);
3025 check_navbar_toggle($before, $toggle_page, $after, window, cx);
3026 });
3027 }
3028 };
3029 }
3030
3031 check_navbar_toggle!(
3032 navbar_basic_open,
3033 before: r"
3034 v General
3035 - General
3036 - Privacy*
3037 v Project
3038 - Project Settings
3039 ",
3040 toggle_page: "General",
3041 after: r"
3042 > General*
3043 v Project
3044 - Project Settings
3045 "
3046 );
3047
3048 check_navbar_toggle!(
3049 navbar_basic_close,
3050 before: r"
3051 > General*
3052 - General
3053 - Privacy
3054 v Project
3055 - Project Settings
3056 ",
3057 toggle_page: "General",
3058 after: r"
3059 v General*
3060 - General
3061 - Privacy
3062 v Project
3063 - Project Settings
3064 "
3065 );
3066
3067 check_navbar_toggle!(
3068 navbar_basic_second_root_entry_close,
3069 before: r"
3070 > General
3071 - General
3072 - Privacy
3073 v Project
3074 - Project Settings*
3075 ",
3076 toggle_page: "Project",
3077 after: r"
3078 > General
3079 > Project*
3080 "
3081 );
3082
3083 check_navbar_toggle!(
3084 navbar_toggle_subroot,
3085 before: r"
3086 v General Page
3087 - General
3088 - Privacy
3089 v Project
3090 - Worktree Settings Content*
3091 v AI
3092 - General
3093 > Appearance & Behavior
3094 ",
3095 toggle_page: "Project",
3096 after: r"
3097 v General Page
3098 - General
3099 - Privacy
3100 > Project*
3101 v AI
3102 - General
3103 > Appearance & Behavior
3104 "
3105 );
3106
3107 check_navbar_toggle!(
3108 navbar_toggle_close_propagates_selected_index,
3109 before: r"
3110 v General Page
3111 - General
3112 - Privacy
3113 v Project
3114 - Worktree Settings Content
3115 v AI
3116 - General*
3117 > Appearance & Behavior
3118 ",
3119 toggle_page: "General Page",
3120 after: r"
3121 > General Page
3122 v Project
3123 - Worktree Settings Content
3124 v AI
3125 - General*
3126 > Appearance & Behavior
3127 "
3128 );
3129
3130 check_navbar_toggle!(
3131 navbar_toggle_expand_propagates_selected_index,
3132 before: r"
3133 > General Page
3134 - General
3135 - Privacy
3136 v Project
3137 - Worktree Settings Content
3138 v AI
3139 - General*
3140 > Appearance & Behavior
3141 ",
3142 toggle_page: "General Page",
3143 after: r"
3144 v General Page
3145 - General
3146 - Privacy
3147 v Project
3148 - Worktree Settings Content
3149 v AI
3150 - General*
3151 > Appearance & Behavior
3152 "
3153 );
3154}