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