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