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