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