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