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