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