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