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