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