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