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 .style(ButtonStyle::Outlined)
261 .size(ButtonSize::Medium)
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 .min_w_0()
610 .gap_2()
611 .justify_between()
612 .pt_4()
613 .map(|this| {
614 if is_last {
615 this.pb_10()
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 .min_w_0()
680 .gap_2()
681 .justify_between()
682 .pt_4()
683 .when(!is_last, |this| {
684 this.pb_4()
685 .border_b_1()
686 .border_color(cx.theme().colors().border_variant)
687 })
688 .child(
689 v_flex()
690 .w_full()
691 .max_w_1_2()
692 .child(Label::new(SharedString::new_static(sub_page_link.title))),
693 )
694 .child(
695 Button::new(("sub-page".into(), sub_page_link.title), "Configure")
696 .icon(IconName::ChevronRight)
697 .icon_position(IconPosition::End)
698 .icon_color(Color::Muted)
699 .icon_size(IconSize::Small)
700 .style(ButtonStyle::Outlined)
701 .size(ButtonSize::Medium),
702 )
703 .on_click({
704 let sub_page_link = sub_page_link.clone();
705 cx.listener(move |this, _, _, cx| {
706 this.push_sub_page(sub_page_link.clone(), section_header, cx)
707 })
708 })
709 .into_any_element(),
710 }
711 }
712}
713
714struct SettingItem {
715 title: &'static str,
716 description: &'static str,
717 field: Box<dyn AnySettingField>,
718 metadata: Option<Box<SettingsFieldMetadata>>,
719 files: FileMask,
720}
721
722#[derive(PartialEq, Eq, Clone, Copy)]
723struct FileMask(u8);
724
725impl std::fmt::Debug for FileMask {
726 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
727 write!(f, "FileMask(")?;
728 let mut items = vec![];
729
730 if self.contains(USER) {
731 items.push("USER");
732 }
733 if self.contains(LOCAL) {
734 items.push("LOCAL");
735 }
736 if self.contains(SERVER) {
737 items.push("SERVER");
738 }
739
740 write!(f, "{})", items.join(" | "))
741 }
742}
743
744const USER: FileMask = FileMask(1 << 0);
745const LOCAL: FileMask = FileMask(1 << 2);
746const SERVER: FileMask = FileMask(1 << 3);
747
748impl std::ops::BitAnd for FileMask {
749 type Output = Self;
750
751 fn bitand(self, other: Self) -> Self {
752 Self(self.0 & other.0)
753 }
754}
755
756impl std::ops::BitOr for FileMask {
757 type Output = Self;
758
759 fn bitor(self, other: Self) -> Self {
760 Self(self.0 | other.0)
761 }
762}
763
764impl FileMask {
765 fn contains(&self, other: FileMask) -> bool {
766 self.0 & other.0 != 0
767 }
768}
769
770impl PartialEq for SettingItem {
771 fn eq(&self, other: &Self) -> bool {
772 self.title == other.title
773 && self.description == other.description
774 && (match (&self.metadata, &other.metadata) {
775 (None, None) => true,
776 (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
777 _ => false,
778 })
779 }
780}
781
782#[derive(Clone)]
783struct SubPageLink {
784 title: &'static str,
785 files: FileMask,
786 render: Arc<
787 dyn Fn(&mut SettingsWindow, &mut Window, &mut Context<SettingsWindow>) -> AnyElement
788 + 'static
789 + Send
790 + Sync,
791 >,
792}
793
794impl PartialEq for SubPageLink {
795 fn eq(&self, other: &Self) -> bool {
796 self.title == other.title
797 }
798}
799
800#[allow(unused)]
801#[derive(Clone, PartialEq)]
802enum SettingsUiFile {
803 User, // Uses all settings.
804 Project((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
805 Server(&'static str), // Uses a special name, and the user settings
806}
807
808impl SettingsUiFile {
809 fn is_server(&self) -> bool {
810 matches!(self, SettingsUiFile::Server(_))
811 }
812
813 fn worktree_id(&self) -> Option<WorktreeId> {
814 match self {
815 SettingsUiFile::User => None,
816 SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
817 SettingsUiFile::Server(_) => None,
818 }
819 }
820
821 fn from_settings(file: settings::SettingsFile) -> Option<Self> {
822 Some(match file {
823 settings::SettingsFile::User => SettingsUiFile::User,
824 settings::SettingsFile::Project(location) => SettingsUiFile::Project(location),
825 settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
826 settings::SettingsFile::Default => return None,
827 })
828 }
829
830 fn to_settings(&self) -> settings::SettingsFile {
831 match self {
832 SettingsUiFile::User => settings::SettingsFile::User,
833 SettingsUiFile::Project(location) => settings::SettingsFile::Project(location.clone()),
834 SettingsUiFile::Server(_) => settings::SettingsFile::Server,
835 }
836 }
837
838 fn mask(&self) -> FileMask {
839 match self {
840 SettingsUiFile::User => USER,
841 SettingsUiFile::Project(_) => LOCAL,
842 SettingsUiFile::Server(_) => SERVER,
843 }
844 }
845}
846
847impl SettingsWindow {
848 pub fn new(
849 original_window: Option<WindowHandle<Workspace>>,
850 window: &mut Window,
851 cx: &mut Context<Self>,
852 ) -> Self {
853 let font_family_cache = theme::FontFamilyCache::global(cx);
854
855 cx.spawn(async move |this, cx| {
856 font_family_cache.prefetch(cx).await;
857 this.update(cx, |_, cx| {
858 cx.notify();
859 })
860 })
861 .detach();
862
863 let current_file = SettingsUiFile::User;
864 let search_bar = cx.new(|cx| {
865 let mut editor = Editor::single_line(window, cx);
866 editor.set_placeholder_text("Search settings…", window, cx);
867 editor
868 });
869
870 cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
871 let EditorEvent::Edited { transaction_id: _ } = event else {
872 return;
873 };
874
875 this.update_matches(cx);
876 })
877 .detach();
878
879 cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
880 this.fetch_files(window, cx);
881 cx.notify();
882 })
883 .detach();
884
885 let mut this = Self {
886 original_window,
887 worktree_root_dirs: HashMap::default(),
888 files: vec![],
889 current_file: current_file,
890 pages: vec![],
891 navbar_entries: vec![],
892 navbar_entry: 0,
893 list_handle: UniformListScrollHandle::default(),
894 search_bar,
895 search_task: None,
896 search_matches: vec![],
897 content_handles: vec![],
898 scroll_handle: ScrollHandle::new(),
899 focus_handle: cx.focus_handle(),
900 navbar_focus_handle: NonFocusableHandle::new(
901 NAVBAR_CONTAINER_TAB_INDEX,
902 false,
903 window,
904 cx,
905 ),
906 content_focus_handle: NonFocusableHandle::new(
907 CONTENT_CONTAINER_TAB_INDEX,
908 false,
909 window,
910 cx,
911 ),
912 files_focus_handle: cx
913 .focus_handle()
914 .tab_index(HEADER_CONTAINER_TAB_INDEX)
915 .tab_stop(false),
916 };
917
918 this.fetch_files(window, cx);
919 this.build_ui(window, cx);
920
921 this.search_bar.update(cx, |editor, cx| {
922 editor.focus_handle(cx).focus(window);
923 });
924
925 this
926 }
927
928 fn toggle_navbar_entry(&mut self, ix: usize) {
929 // We can only toggle root entries
930 if !self.navbar_entries[ix].is_root {
931 return;
932 }
933
934 let toggle_page_index = self.page_index_from_navbar_index(ix);
935 let selected_page_index = self.page_index_from_navbar_index(self.navbar_entry);
936
937 let expanded = &mut self.navbar_entries[ix].expanded;
938 *expanded = !*expanded;
939 // if currently selected page is a child of the parent page we are folding,
940 // set the current page to the parent page
941 if !*expanded && selected_page_index == toggle_page_index {
942 self.navbar_entry = ix;
943 // note: not opening page. Toggling does not change content just selected page
944 }
945 }
946
947 fn build_navbar(&mut self) {
948 let mut prev_navbar_state = HashMap::new();
949 let mut root_entry = "";
950 let mut prev_selected_entry = None;
951 for (index, entry) in self.navbar_entries.iter().enumerate() {
952 let sub_entry_title;
953 if entry.is_root {
954 sub_entry_title = None;
955 root_entry = entry.title;
956 } else {
957 sub_entry_title = Some(entry.title);
958 }
959 let key = (root_entry, sub_entry_title);
960 if index == self.navbar_entry {
961 prev_selected_entry = Some(key);
962 }
963 prev_navbar_state.insert(key, entry.expanded);
964 }
965
966 let mut navbar_entries = Vec::with_capacity(self.navbar_entries.len());
967 for (page_index, page) in self.pages.iter().enumerate() {
968 navbar_entries.push(NavBarEntry {
969 title: page.title,
970 is_root: true,
971 expanded: false,
972 page_index,
973 item_index: None,
974 });
975
976 for (item_index, item) in page.items.iter().enumerate() {
977 let SettingsPageItem::SectionHeader(title) = item else {
978 continue;
979 };
980 navbar_entries.push(NavBarEntry {
981 title,
982 is_root: false,
983 expanded: false,
984 page_index,
985 item_index: Some(item_index),
986 });
987 }
988 }
989
990 let mut root_entry = "";
991 let mut found_nav_entry = false;
992 for (index, entry) in navbar_entries.iter_mut().enumerate() {
993 let sub_entry_title;
994 if entry.is_root {
995 root_entry = entry.title;
996 sub_entry_title = None;
997 } else {
998 sub_entry_title = Some(entry.title);
999 };
1000 let key = (root_entry, sub_entry_title);
1001 if Some(key) == prev_selected_entry {
1002 self.open_nav_page(index);
1003 found_nav_entry = true;
1004 }
1005 entry.expanded = *prev_navbar_state.get(&key).unwrap_or(&false);
1006 }
1007 if !found_nav_entry {
1008 self.open_first_nav_page();
1009 }
1010 self.navbar_entries = navbar_entries;
1011 }
1012
1013 fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
1014 let mut index = 0;
1015 let entries = &self.navbar_entries;
1016 let search_matches = &self.search_matches;
1017 std::iter::from_fn(move || {
1018 while index < entries.len() {
1019 let entry = &entries[index];
1020 let included_in_search = if let Some(item_index) = entry.item_index {
1021 search_matches[entry.page_index][item_index]
1022 } else {
1023 search_matches[entry.page_index].iter().any(|b| *b)
1024 || search_matches[entry.page_index].is_empty()
1025 };
1026 if included_in_search {
1027 break;
1028 }
1029 index += 1;
1030 }
1031 if index >= self.navbar_entries.len() {
1032 return None;
1033 }
1034 let entry = &entries[index];
1035 let entry_index = index;
1036
1037 index += 1;
1038 if entry.is_root && !entry.expanded {
1039 while index < entries.len() {
1040 if entries[index].is_root {
1041 break;
1042 }
1043 index += 1;
1044 }
1045 }
1046
1047 return Some((entry_index, entry));
1048 })
1049 }
1050
1051 fn filter_matches_to_file(&mut self) {
1052 let current_file = self.current_file.mask();
1053 for (page, page_filter) in std::iter::zip(&self.pages, &mut self.search_matches) {
1054 let mut header_index = 0;
1055 let mut any_found_since_last_header = true;
1056
1057 for (index, item) in page.items.iter().enumerate() {
1058 match item {
1059 SettingsPageItem::SectionHeader(_) => {
1060 if !any_found_since_last_header {
1061 page_filter[header_index] = false;
1062 }
1063 header_index = index;
1064 any_found_since_last_header = false;
1065 }
1066 SettingsPageItem::SettingItem(setting_item) => {
1067 if !setting_item.files.contains(current_file) {
1068 page_filter[index] = false;
1069 } else {
1070 any_found_since_last_header = true;
1071 }
1072 }
1073 SettingsPageItem::SubPageLink(sub_page_link) => {
1074 if !sub_page_link.files.contains(current_file) {
1075 page_filter[index] = false;
1076 } else {
1077 any_found_since_last_header = true;
1078 }
1079 }
1080 }
1081 }
1082 if let Some(last_header) = page_filter.get_mut(header_index)
1083 && !any_found_since_last_header
1084 {
1085 *last_header = false;
1086 }
1087 }
1088 }
1089
1090 fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
1091 self.search_task.take();
1092 let query = self.search_bar.read(cx).text(cx);
1093 if query.is_empty() {
1094 for page in &mut self.search_matches {
1095 page.fill(true);
1096 }
1097 self.filter_matches_to_file();
1098 cx.notify();
1099 return;
1100 }
1101
1102 struct ItemKey {
1103 page_index: usize,
1104 header_index: usize,
1105 item_index: usize,
1106 }
1107 let mut key_lut: Vec<ItemKey> = vec![];
1108 let mut candidates = Vec::default();
1109
1110 for (page_index, page) in self.pages.iter().enumerate() {
1111 let mut header_index = 0;
1112 for (item_index, item) in page.items.iter().enumerate() {
1113 let key_index = key_lut.len();
1114 match item {
1115 SettingsPageItem::SettingItem(item) => {
1116 candidates.push(StringMatchCandidate::new(key_index, item.title));
1117 candidates.push(StringMatchCandidate::new(key_index, item.description));
1118 }
1119 SettingsPageItem::SectionHeader(header) => {
1120 candidates.push(StringMatchCandidate::new(key_index, header));
1121 header_index = item_index;
1122 }
1123 SettingsPageItem::SubPageLink(sub_page_link) => {
1124 candidates.push(StringMatchCandidate::new(key_index, sub_page_link.title));
1125 }
1126 }
1127 key_lut.push(ItemKey {
1128 page_index,
1129 header_index,
1130 item_index,
1131 });
1132 }
1133 }
1134 let atomic_bool = AtomicBool::new(false);
1135
1136 self.search_task = Some(cx.spawn(async move |this, cx| {
1137 let string_matches = fuzzy::match_strings(
1138 candidates.as_slice(),
1139 &query,
1140 false,
1141 true,
1142 candidates.len(),
1143 &atomic_bool,
1144 cx.background_executor().clone(),
1145 );
1146 let string_matches = string_matches.await;
1147
1148 this.update(cx, |this, cx| {
1149 for page in &mut this.search_matches {
1150 page.fill(false);
1151 }
1152
1153 for string_match in string_matches {
1154 let ItemKey {
1155 page_index,
1156 header_index,
1157 item_index,
1158 } = key_lut[string_match.candidate_id];
1159 let page = &mut this.search_matches[page_index];
1160 page[header_index] = true;
1161 page[item_index] = true;
1162 }
1163 this.filter_matches_to_file();
1164 this.open_first_nav_page();
1165 cx.notify();
1166 })
1167 .ok();
1168 }));
1169 }
1170
1171 fn build_search_matches(&mut self) {
1172 self.search_matches = self
1173 .pages
1174 .iter()
1175 .map(|page| vec![true; page.items.len()])
1176 .collect::<Vec<_>>();
1177 }
1178
1179 fn build_content_handles(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1180 self.content_handles = self
1181 .pages
1182 .iter()
1183 .map(|page| {
1184 std::iter::repeat_with(|| NonFocusableHandle::new(0, false, window, cx))
1185 .take(page.items.len())
1186 .collect()
1187 })
1188 .collect::<Vec<_>>();
1189 }
1190
1191 fn build_ui(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1192 if self.pages.is_empty() {
1193 self.pages = page_data::settings_data();
1194 }
1195 sub_page_stack_mut().clear();
1196 self.build_content_handles(window, cx);
1197 self.build_search_matches();
1198 self.build_navbar();
1199
1200 self.update_matches(cx);
1201
1202 cx.notify();
1203 }
1204
1205 fn fetch_files(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1206 self.worktree_root_dirs.clear();
1207 let prev_files = self.files.clone();
1208 let settings_store = cx.global::<SettingsStore>();
1209 let mut ui_files = vec![];
1210 let all_files = settings_store.get_all_files();
1211 for file in all_files {
1212 let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
1213 continue;
1214 };
1215 if settings_ui_file.is_server() {
1216 continue;
1217 }
1218
1219 if let Some(worktree_id) = settings_ui_file.worktree_id() {
1220 let directory_name = all_projects(cx)
1221 .find_map(|project| project.read(cx).worktree_for_id(worktree_id, cx))
1222 .and_then(|worktree| worktree.read(cx).root_dir())
1223 .and_then(|root_dir| {
1224 root_dir
1225 .file_name()
1226 .map(|os_string| os_string.to_string_lossy().to_string())
1227 });
1228
1229 let Some(directory_name) = directory_name else {
1230 log::error!(
1231 "No directory name found for settings file at worktree ID: {}",
1232 worktree_id
1233 );
1234 continue;
1235 };
1236
1237 self.worktree_root_dirs.insert(worktree_id, directory_name);
1238 }
1239
1240 let focus_handle = prev_files
1241 .iter()
1242 .find_map(|(prev_file, handle)| {
1243 (prev_file == &settings_ui_file).then(|| handle.clone())
1244 })
1245 .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
1246 ui_files.push((settings_ui_file, focus_handle));
1247 }
1248 ui_files.reverse();
1249 self.files = ui_files;
1250 let current_file_still_exists = self
1251 .files
1252 .iter()
1253 .any(|(file, _)| file == &self.current_file);
1254 if !current_file_still_exists {
1255 self.change_file(0, window, cx);
1256 }
1257 }
1258
1259 fn open_nav_page(&mut self, navbar_entry: usize) {
1260 self.navbar_entry = navbar_entry;
1261 sub_page_stack_mut().clear();
1262 }
1263
1264 fn open_first_nav_page(&mut self) {
1265 let first_navbar_entry_index = self
1266 .visible_navbar_entries()
1267 .next()
1268 .map(|e| e.0)
1269 .unwrap_or(0);
1270 self.open_nav_page(first_navbar_entry_index);
1271 }
1272
1273 fn change_file(&mut self, ix: usize, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1274 if ix >= self.files.len() {
1275 self.current_file = SettingsUiFile::User;
1276 self.build_ui(window, cx);
1277 return;
1278 }
1279 if self.files[ix].0 == self.current_file {
1280 return;
1281 }
1282 self.current_file = self.files[ix].0.clone();
1283 self.open_nav_page(0);
1284 self.build_ui(window, cx);
1285
1286 self.open_first_nav_page();
1287 }
1288
1289 fn render_files_header(
1290 &self,
1291 _window: &mut Window,
1292 cx: &mut Context<SettingsWindow>,
1293 ) -> impl IntoElement {
1294 h_flex()
1295 .w_full()
1296 .pb_4()
1297 .gap_1()
1298 .justify_between()
1299 .tab_group()
1300 .track_focus(&self.files_focus_handle)
1301 .tab_index(HEADER_GROUP_TAB_INDEX)
1302 .child(
1303 h_flex()
1304 .id("file_buttons_container")
1305 .w_64() // Temporary fix until long-term solution is a fixed set of buttons representing a file location (User, Project, and Remote)
1306 .gap_1()
1307 .overflow_x_scroll()
1308 .children(
1309 self.files
1310 .iter()
1311 .enumerate()
1312 .map(|(ix, (file, focus_handle))| {
1313 Button::new(
1314 ix,
1315 self.display_name(&file)
1316 .expect("Files should always have a name"),
1317 )
1318 .toggle_state(file == &self.current_file)
1319 .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
1320 .track_focus(focus_handle)
1321 .on_click(cx.listener({
1322 let focus_handle = focus_handle.clone();
1323 move |this, _: &gpui::ClickEvent, window, cx| {
1324 this.change_file(ix, window, cx);
1325 focus_handle.focus(window);
1326 }
1327 }))
1328 }),
1329 ),
1330 )
1331 .child(
1332 Button::new("edit-in-json", "Edit in settings.json")
1333 .tab_index(0_isize)
1334 .style(ButtonStyle::OutlinedGhost)
1335 .on_click(cx.listener(|this, _, _, cx| {
1336 this.open_current_settings_file(cx);
1337 })),
1338 )
1339 }
1340
1341 pub(crate) fn display_name(&self, file: &SettingsUiFile) -> Option<String> {
1342 match file {
1343 SettingsUiFile::User => Some("User".to_string()),
1344 SettingsUiFile::Project((worktree_id, path)) => self
1345 .worktree_root_dirs
1346 .get(&worktree_id)
1347 .map(|directory_name| {
1348 let path_style = PathStyle::local();
1349 if path.is_empty() {
1350 directory_name.clone()
1351 } else {
1352 format!(
1353 "{}{}{}",
1354 directory_name,
1355 path_style.separator(),
1356 path.display(path_style)
1357 )
1358 }
1359 }),
1360 SettingsUiFile::Server(file) => Some(file.to_string()),
1361 }
1362 }
1363
1364 // TODO:
1365 // Reconsider this after preview launch
1366 // fn file_location_str(&self) -> String {
1367 // match &self.current_file {
1368 // SettingsUiFile::User => "settings.json".to_string(),
1369 // SettingsUiFile::Project((worktree_id, path)) => self
1370 // .worktree_root_dirs
1371 // .get(&worktree_id)
1372 // .map(|directory_name| {
1373 // let path_style = PathStyle::local();
1374 // let file_path = path.join(paths::local_settings_file_relative_path());
1375 // format!(
1376 // "{}{}{}",
1377 // directory_name,
1378 // path_style.separator(),
1379 // file_path.display(path_style)
1380 // )
1381 // })
1382 // .expect("Current file should always be present in root dir map"),
1383 // SettingsUiFile::Server(file) => file.to_string(),
1384 // }
1385 // }
1386
1387 fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
1388 h_flex()
1389 .py_1()
1390 .px_1p5()
1391 .mb_3()
1392 .gap_1p5()
1393 .rounded_sm()
1394 .bg(cx.theme().colors().editor_background)
1395 .border_1()
1396 .border_color(cx.theme().colors().border)
1397 .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
1398 .child(self.search_bar.clone())
1399 }
1400
1401 fn render_nav(
1402 &self,
1403 window: &mut Window,
1404 cx: &mut Context<SettingsWindow>,
1405 ) -> impl IntoElement {
1406 let visible_count = self.visible_navbar_entries().count();
1407
1408 // let focus_keybind_label = if self.navbar_focus_handle.contains_focused(window, cx) {
1409 // "Focus Content"
1410 // } else {
1411 // "Focus Navbar"
1412 // };
1413
1414 v_flex()
1415 .w_64()
1416 .p_2p5()
1417 .pt_10()
1418 .flex_none()
1419 .border_r_1()
1420 .border_color(cx.theme().colors().border)
1421 .bg(cx.theme().colors().panel_background)
1422 .child(self.render_search(window, cx))
1423 .child(
1424 v_flex()
1425 .size_full()
1426 .track_focus(&self.navbar_focus_handle.focus_handle(cx))
1427 .tab_group()
1428 .tab_index(NAVBAR_GROUP_TAB_INDEX)
1429 .child(
1430 uniform_list(
1431 "settings-ui-nav-bar",
1432 visible_count,
1433 cx.processor(move |this, range: Range<usize>, _, cx| {
1434 this.visible_navbar_entries()
1435 .skip(range.start.saturating_sub(1))
1436 .take(range.len())
1437 .map(|(ix, entry)| {
1438 TreeViewItem::new(
1439 ("settings-ui-navbar-entry", ix),
1440 entry.title,
1441 )
1442 .tab_index(0)
1443 .root_item(entry.is_root)
1444 .toggle_state(this.is_navbar_entry_selected(ix))
1445 .when(entry.is_root, |item| {
1446 item.expanded(entry.expanded).on_toggle(cx.listener(
1447 move |this, _, _, cx| {
1448 this.toggle_navbar_entry(ix);
1449 cx.notify();
1450 },
1451 ))
1452 })
1453 .on_click(
1454 cx.listener(
1455 move |this, evt: &gpui::ClickEvent, window, cx| {
1456 if !this.navbar_entries[ix].is_root {
1457 this.open_nav_page(ix);
1458 let mut selected_page_ix = ix;
1459
1460 while !this.navbar_entries[selected_page_ix]
1461 .is_root
1462 {
1463 selected_page_ix -= 1;
1464 }
1465
1466 let section_header = ix - selected_page_ix;
1467
1468 if let Some(section_index) =
1469 this.page_items()
1470 .enumerate()
1471 .filter(|(_, (_, item))| {
1472 matches!(
1473 item,
1474 SettingsPageItem::SectionHeader(_)
1475 )
1476 })
1477 .take(section_header)
1478 .last()
1479 .map(|(index, _)| index)
1480 {
1481 this.scroll_handle
1482 .scroll_to_top_of_item(
1483 section_index,
1484 );
1485 this.focus_content_element(
1486 section_index,
1487 window,
1488 cx,
1489 );
1490 }
1491 } else if !evt.is_keyboard() {
1492 this.open_nav_page(ix);
1493 }
1494 cx.notify();
1495 },
1496 ),
1497 )
1498 })
1499 .collect()
1500 }),
1501 )
1502 .size_full()
1503 .track_scroll(self.list_handle.clone()),
1504 )
1505 .vertical_scrollbar_for(self.list_handle.clone(), window, cx),
1506 )
1507 // TODO: Restore this once we've fixed the ToggleFocusNav action
1508 // .child(
1509 // h_flex()
1510 // .w_full()
1511 // .p_2()
1512 // .pb_0p5()
1513 // .flex_none()
1514 // .border_t_1()
1515 // .border_color(cx.theme().colors().border_variant)
1516 // .children(
1517 // KeyBinding::for_action(&ToggleFocusNav, window, cx).map(|this| {
1518 // KeybindingHint::new(
1519 // this,
1520 // cx.theme().colors().surface_background.opacity(0.5),
1521 // )
1522 // .suffix(focus_keybind_label)
1523 // }),
1524 // ),
1525 // )
1526 }
1527
1528 fn focus_first_nav_item(&self, window: &mut Window, cx: &mut Context<Self>) {
1529 self.navbar_focus_handle.focus_handle(cx).focus(window);
1530 window.focus_next();
1531 cx.notify();
1532 }
1533
1534 fn focus_first_content_item(&self, window: &mut Window, cx: &mut Context<Self>) {
1535 self.content_focus_handle.focus_handle(cx).focus(window);
1536 window.focus_next();
1537 cx.notify();
1538 }
1539
1540 fn page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
1541 let page_idx = self.current_page_index();
1542
1543 self.current_page()
1544 .items
1545 .iter()
1546 .enumerate()
1547 .filter_map(move |(item_index, item)| {
1548 self.search_matches[page_idx][item_index].then_some((item_index, item))
1549 })
1550 }
1551
1552 fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
1553 let mut items = vec![];
1554 items.push(self.current_page().title);
1555 items.extend(
1556 sub_page_stack()
1557 .iter()
1558 .flat_map(|page| [page.section_header, page.link.title]),
1559 );
1560
1561 let last = items.pop().unwrap();
1562 h_flex()
1563 .gap_1()
1564 .children(
1565 items
1566 .into_iter()
1567 .flat_map(|item| [item, "/"])
1568 .map(|item| Label::new(item).color(Color::Muted)),
1569 )
1570 .child(Label::new(last))
1571 }
1572
1573 fn render_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
1574 &self,
1575 items: Items,
1576 page_index: Option<usize>,
1577 window: &mut Window,
1578 cx: &mut Context<SettingsWindow>,
1579 ) -> impl IntoElement {
1580 let mut page_content = v_flex()
1581 .id("settings-ui-page")
1582 .size_full()
1583 .overflow_y_scroll()
1584 .track_scroll(&self.scroll_handle);
1585
1586 let items: Vec<_> = items.collect();
1587 let items_len = items.len();
1588 let mut section_header = None;
1589
1590 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
1591 let has_no_results = items_len == 0 && has_active_search;
1592
1593 if has_no_results {
1594 let search_query = self.search_bar.read(cx).text(cx);
1595 page_content = page_content.child(
1596 v_flex()
1597 .size_full()
1598 .items_center()
1599 .justify_center()
1600 .gap_1()
1601 .child(div().child("No Results"))
1602 .child(
1603 div()
1604 .text_sm()
1605 .text_color(cx.theme().colors().text_muted)
1606 .child(format!("No settings match \"{}\"", search_query)),
1607 ),
1608 )
1609 } else {
1610 let last_non_header_index = items
1611 .iter()
1612 .enumerate()
1613 .rev()
1614 .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
1615 .map(|(index, _)| index);
1616
1617 page_content = page_content.children(items.clone().into_iter().enumerate().map(
1618 |(index, (actual_item_index, item))| {
1619 let no_bottom_border = items
1620 .get(index + 1)
1621 .map(|(_, next_item)| {
1622 matches!(next_item, SettingsPageItem::SectionHeader(_))
1623 })
1624 .unwrap_or(false);
1625 let is_last = Some(index) == last_non_header_index;
1626
1627 if let SettingsPageItem::SectionHeader(header) = item {
1628 section_header = Some(*header);
1629 }
1630 v_flex()
1631 .w_full()
1632 .min_w_0()
1633 .when_some(page_index, |element, page_index| {
1634 element.track_focus(
1635 &self.content_handles[page_index][actual_item_index]
1636 .focus_handle(cx),
1637 )
1638 })
1639 .child(item.render(
1640 self,
1641 section_header.expect("All items rendered after a section header"),
1642 no_bottom_border || is_last,
1643 window,
1644 cx,
1645 ))
1646 },
1647 ))
1648 }
1649 page_content
1650 }
1651
1652 fn render_page(
1653 &mut self,
1654 window: &mut Window,
1655 cx: &mut Context<SettingsWindow>,
1656 ) -> impl IntoElement {
1657 let page_header;
1658 let page_content;
1659
1660 if sub_page_stack().len() == 0 {
1661 page_header = self.render_files_header(window, cx).into_any_element();
1662
1663 page_content = self
1664 .render_page_items(
1665 self.page_items(),
1666 Some(self.current_page_index()),
1667 window,
1668 cx,
1669 )
1670 .into_any_element();
1671 } else {
1672 page_header = h_flex()
1673 .ml_neg_1p5()
1674 .pb_4()
1675 .gap_1()
1676 .child(
1677 IconButton::new("back-btn", IconName::ArrowLeft)
1678 .icon_size(IconSize::Small)
1679 .shape(IconButtonShape::Square)
1680 .on_click(cx.listener(|this, _, _, cx| {
1681 this.pop_sub_page(cx);
1682 })),
1683 )
1684 .child(self.render_sub_page_breadcrumbs())
1685 .into_any_element();
1686
1687 let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
1688 page_content = (active_page_render_fn)(self, window, cx);
1689 }
1690
1691 return v_flex()
1692 .size_full()
1693 .pt_6()
1694 .pb_8()
1695 .px_8()
1696 .track_focus(&self.content_focus_handle.focus_handle(cx))
1697 .bg(cx.theme().colors().editor_background)
1698 .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx)
1699 .child(page_header)
1700 .child(
1701 div()
1702 .size_full()
1703 .track_focus(&self.content_focus_handle.focus_handle(cx))
1704 .tab_group()
1705 .tab_index(CONTENT_GROUP_TAB_INDEX)
1706 .child(page_content),
1707 );
1708 }
1709
1710 fn open_current_settings_file(&mut self, cx: &mut Context<Self>) {
1711 match &self.current_file {
1712 SettingsUiFile::User => {
1713 let Some(original_window) = self.original_window else {
1714 return;
1715 };
1716 original_window
1717 .update(cx, |workspace, window, cx| {
1718 workspace
1719 .with_local_workspace(window, cx, |workspace, window, cx| {
1720 let create_task = workspace.project().update(cx, |project, cx| {
1721 project.find_or_create_worktree(
1722 paths::config_dir().as_path(),
1723 false,
1724 cx,
1725 )
1726 });
1727 let open_task = workspace.open_paths(
1728 vec![paths::settings_file().to_path_buf()],
1729 OpenOptions {
1730 visible: Some(OpenVisible::None),
1731 ..Default::default()
1732 },
1733 None,
1734 window,
1735 cx,
1736 );
1737
1738 cx.spawn_in(window, async move |workspace, cx| {
1739 create_task.await.ok();
1740 open_task.await;
1741
1742 workspace.update_in(cx, |_, window, cx| {
1743 window.activate_window();
1744 cx.notify();
1745 })
1746 })
1747 .detach();
1748 })
1749 .detach();
1750 })
1751 .ok();
1752 }
1753 SettingsUiFile::Project((worktree_id, path)) => {
1754 let mut corresponding_workspace: Option<WindowHandle<Workspace>> = None;
1755 let settings_path = path.join(paths::local_settings_file_relative_path());
1756 let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
1757 return;
1758 };
1759 for workspace in app_state.workspace_store.read(cx).workspaces() {
1760 let contains_settings_file = workspace
1761 .read_with(cx, |workspace, cx| {
1762 workspace.project().read(cx).contains_local_settings_file(
1763 *worktree_id,
1764 settings_path.as_ref(),
1765 cx,
1766 )
1767 })
1768 .ok();
1769 if Some(true) == contains_settings_file {
1770 corresponding_workspace = Some(*workspace);
1771
1772 break;
1773 }
1774 }
1775
1776 let Some(corresponding_workspace) = corresponding_workspace else {
1777 log::error!(
1778 "No corresponding workspace found for settings file {}",
1779 settings_path.as_std_path().display()
1780 );
1781
1782 return;
1783 };
1784
1785 // TODO: move zed::open_local_file() APIs to this crate, and
1786 // re-implement the "initial_contents" behavior
1787 corresponding_workspace
1788 .update(cx, |workspace, window, cx| {
1789 let open_task = workspace.open_path(
1790 (*worktree_id, settings_path.clone()),
1791 None,
1792 true,
1793 window,
1794 cx,
1795 );
1796
1797 cx.spawn_in(window, async move |workspace, cx| {
1798 if open_task.await.log_err().is_some() {
1799 workspace
1800 .update_in(cx, |_, window, cx| {
1801 window.activate_window();
1802 cx.notify();
1803 })
1804 .ok();
1805 }
1806 })
1807 .detach();
1808 })
1809 .ok();
1810 }
1811 SettingsUiFile::Server(_) => {
1812 return;
1813 }
1814 };
1815 }
1816
1817 fn current_page_index(&self) -> usize {
1818 self.page_index_from_navbar_index(self.navbar_entry)
1819 }
1820
1821 fn current_page(&self) -> &SettingsPage {
1822 &self.pages[self.current_page_index()]
1823 }
1824
1825 fn page_index_from_navbar_index(&self, index: usize) -> usize {
1826 if self.navbar_entries.is_empty() {
1827 return 0;
1828 }
1829
1830 self.navbar_entries[index].page_index
1831 }
1832
1833 fn is_navbar_entry_selected(&self, ix: usize) -> bool {
1834 ix == self.navbar_entry
1835 }
1836
1837 fn push_sub_page(
1838 &mut self,
1839 sub_page_link: SubPageLink,
1840 section_header: &'static str,
1841 cx: &mut Context<SettingsWindow>,
1842 ) {
1843 sub_page_stack_mut().push(SubPage {
1844 link: sub_page_link,
1845 section_header,
1846 });
1847 cx.notify();
1848 }
1849
1850 fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
1851 sub_page_stack_mut().pop();
1852 cx.notify();
1853 }
1854
1855 fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
1856 if let Some((_, handle)) = self.files.get(index) {
1857 handle.focus(window);
1858 }
1859 }
1860
1861 fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
1862 if self.files_focus_handle.contains_focused(window, cx)
1863 && let Some(index) = self
1864 .files
1865 .iter()
1866 .position(|(_, handle)| handle.is_focused(window))
1867 {
1868 return index;
1869 }
1870 if let Some(current_file_index) = self
1871 .files
1872 .iter()
1873 .position(|(file, _)| file == &self.current_file)
1874 {
1875 return current_file_index;
1876 }
1877 0
1878 }
1879
1880 fn focus_content_element(&self, item_index: usize, window: &mut Window, cx: &mut App) {
1881 if !sub_page_stack().is_empty() {
1882 return;
1883 }
1884 let page_index = self.current_page_index();
1885 window.focus(&self.content_handles[page_index][item_index].focus_handle(cx));
1886 }
1887}
1888
1889impl Render for SettingsWindow {
1890 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1891 let ui_font = theme::setup_ui_font(window, cx);
1892
1893 div()
1894 .id("settings-window")
1895 .key_context("SettingsWindow")
1896 .track_focus(&self.focus_handle)
1897 .on_action(cx.listener(|this, _: &OpenCurrentFile, _, cx| {
1898 this.open_current_settings_file(cx);
1899 }))
1900 .on_action(|_: &Minimize, window, _cx| {
1901 window.minimize_window();
1902 })
1903 .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
1904 this.search_bar.focus_handle(cx).focus(window);
1905 }))
1906 .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
1907 if this
1908 .navbar_focus_handle
1909 .focus_handle(cx)
1910 .contains_focused(window, cx)
1911 {
1912 this.focus_first_content_item(window, cx);
1913 } else {
1914 this.focus_first_nav_item(window, cx);
1915 }
1916 }))
1917 .on_action(
1918 cx.listener(|this, FocusFile(file_index): &FocusFile, window, _| {
1919 this.focus_file_at_index(*file_index as usize, window);
1920 }),
1921 )
1922 .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
1923 let next_index = usize::min(
1924 this.focused_file_index(window, cx) + 1,
1925 this.files.len().saturating_sub(1),
1926 );
1927 this.focus_file_at_index(next_index, window);
1928 }))
1929 .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
1930 let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
1931 this.focus_file_at_index(prev_index, window);
1932 }))
1933 .on_action(|_: &menu::SelectNext, window, _| {
1934 window.focus_next();
1935 })
1936 .on_action(|_: &menu::SelectPrevious, window, _| {
1937 window.focus_prev();
1938 })
1939 .flex()
1940 .flex_row()
1941 .size_full()
1942 .font(ui_font)
1943 .bg(cx.theme().colors().background)
1944 .text_color(cx.theme().colors().text)
1945 .child(self.render_nav(window, cx))
1946 .child(self.render_page(window, cx))
1947 }
1948}
1949
1950fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
1951 workspace::AppState::global(cx)
1952 .upgrade()
1953 .map(|app_state| {
1954 app_state
1955 .workspace_store
1956 .read(cx)
1957 .workspaces()
1958 .iter()
1959 .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
1960 })
1961 .into_iter()
1962 .flatten()
1963}
1964
1965fn update_settings_file(
1966 file: SettingsUiFile,
1967 cx: &mut App,
1968 update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
1969) -> Result<()> {
1970 match file {
1971 SettingsUiFile::Project((worktree_id, rel_path)) => {
1972 let rel_path = rel_path.join(paths::local_settings_file_relative_path());
1973 let project = all_projects(cx).find(|project| {
1974 project.read_with(cx, |project, cx| {
1975 project.contains_local_settings_file(worktree_id, &rel_path, cx)
1976 })
1977 });
1978 let Some(project) = project else {
1979 anyhow::bail!(
1980 "Could not find worktree containing settings file: {}",
1981 &rel_path.display(PathStyle::local())
1982 );
1983 };
1984 project.update(cx, |project, cx| {
1985 project.update_local_settings_file(worktree_id, rel_path, cx, update);
1986 });
1987 return Ok(());
1988 }
1989 SettingsUiFile::User => {
1990 // todo(settings_ui) error?
1991 SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
1992 Ok(())
1993 }
1994 SettingsUiFile::Server(_) => unimplemented!(),
1995 }
1996}
1997
1998fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
1999 field: SettingField<T>,
2000 file: SettingsUiFile,
2001 metadata: Option<&SettingsFieldMetadata>,
2002 cx: &mut App,
2003) -> AnyElement {
2004 let (_, initial_text) =
2005 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2006 let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
2007
2008 SettingsEditor::new()
2009 .tab_index(0)
2010 .when_some(initial_text, |editor, text| {
2011 editor.with_initial_text(text.as_ref().to_string())
2012 })
2013 .when_some(
2014 metadata.and_then(|metadata| metadata.placeholder),
2015 |editor, placeholder| editor.with_placeholder(placeholder),
2016 )
2017 .on_confirm({
2018 move |new_text, cx| {
2019 update_settings_file(file.clone(), cx, move |settings, _cx| {
2020 *(field.pick_mut)(settings) = new_text.map(Into::into);
2021 })
2022 .log_err(); // todo(settings_ui) don't log err
2023 }
2024 })
2025 .into_any_element()
2026}
2027
2028fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
2029 field: SettingField<B>,
2030 file: SettingsUiFile,
2031 cx: &mut App,
2032) -> AnyElement {
2033 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2034
2035 let toggle_state = if value.copied().map_or(false, Into::into) {
2036 ToggleState::Selected
2037 } else {
2038 ToggleState::Unselected
2039 };
2040
2041 Switch::new("toggle_button", toggle_state)
2042 .color(ui::SwitchColor::Accent)
2043 .on_click({
2044 move |state, _window, cx| {
2045 let state = *state == ui::ToggleState::Selected;
2046 update_settings_file(file.clone(), cx, move |settings, _cx| {
2047 *(field.pick_mut)(settings) = Some(state.into());
2048 })
2049 .log_err(); // todo(settings_ui) don't log err
2050 }
2051 })
2052 .tab_index(0_isize)
2053 .color(SwitchColor::Accent)
2054 .into_any_element()
2055}
2056
2057fn render_font_picker(
2058 field: SettingField<settings::FontFamilyName>,
2059 file: SettingsUiFile,
2060 window: &mut Window,
2061 cx: &mut App,
2062) -> AnyElement {
2063 let current_value = SettingsStore::global(cx)
2064 .get_value_from_file(file.to_settings(), field.pick)
2065 .1
2066 .cloned()
2067 .unwrap_or_else(|| SharedString::default().into());
2068
2069 let font_picker = cx.new(|cx| {
2070 ui_input::font_picker(
2071 current_value.clone().into(),
2072 move |font_name, cx| {
2073 update_settings_file(file.clone(), cx, move |settings, _cx| {
2074 *(field.pick_mut)(settings) = Some(font_name.into());
2075 })
2076 .log_err(); // todo(settings_ui) don't log err
2077 },
2078 window,
2079 cx,
2080 )
2081 });
2082
2083 PopoverMenu::new("font-picker")
2084 .menu(move |_window, _cx| Some(font_picker.clone()))
2085 .trigger(
2086 Button::new("font-family-button", current_value)
2087 .tab_index(0_isize)
2088 .style(ButtonStyle::Outlined)
2089 .size(ButtonSize::Medium)
2090 .icon(IconName::ChevronUpDown)
2091 .icon_color(Color::Muted)
2092 .icon_size(IconSize::Small)
2093 .icon_position(IconPosition::End),
2094 )
2095 .anchor(gpui::Corner::TopLeft)
2096 .offset(gpui::Point {
2097 x: px(0.0),
2098 y: px(2.0),
2099 })
2100 .with_handle(ui::PopoverMenuHandle::default())
2101 .into_any_element()
2102}
2103
2104fn render_number_field<T: NumberFieldType + Send + Sync>(
2105 field: SettingField<T>,
2106 file: SettingsUiFile,
2107 window: &mut Window,
2108 cx: &mut App,
2109) -> AnyElement {
2110 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2111 let value = value.copied().unwrap_or_else(T::min_value);
2112 NumberField::new("numeric_stepper", value, window, cx)
2113 .on_change({
2114 move |value, _window, cx| {
2115 let value = *value;
2116 update_settings_file(file.clone(), cx, move |settings, _cx| {
2117 *(field.pick_mut)(settings) = Some(value);
2118 })
2119 .log_err(); // todo(settings_ui) don't log err
2120 }
2121 })
2122 .into_any_element()
2123}
2124
2125fn render_dropdown<T>(
2126 field: SettingField<T>,
2127 file: SettingsUiFile,
2128 window: &mut Window,
2129 cx: &mut App,
2130) -> AnyElement
2131where
2132 T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
2133{
2134 let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
2135 let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
2136
2137 let (_, current_value) =
2138 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2139 let current_value = current_value.copied().unwrap_or(variants()[0]);
2140
2141 let current_value_label =
2142 labels()[variants().iter().position(|v| *v == current_value).unwrap()];
2143
2144 DropdownMenu::new(
2145 "dropdown",
2146 current_value_label.to_title_case(),
2147 ContextMenu::build(window, cx, move |mut menu, _, _| {
2148 for (&value, &label) in std::iter::zip(variants(), labels()) {
2149 let file = file.clone();
2150 menu = menu.toggleable_entry(
2151 label.to_title_case(),
2152 value == current_value,
2153 IconPosition::End,
2154 None,
2155 move |_, cx| {
2156 if value == current_value {
2157 return;
2158 }
2159 update_settings_file(file.clone(), cx, move |settings, _cx| {
2160 *(field.pick_mut)(settings) = Some(value);
2161 })
2162 .log_err(); // todo(settings_ui) don't log err
2163 },
2164 );
2165 }
2166 menu
2167 }),
2168 )
2169 .trigger_size(ButtonSize::Medium)
2170 .style(DropdownStyle::Outlined)
2171 .offset(gpui::Point {
2172 x: px(0.0),
2173 y: px(2.0),
2174 })
2175 .tab_index(0)
2176 .into_any_element()
2177}
2178
2179#[cfg(test)]
2180mod test {
2181
2182 use super::*;
2183
2184 impl SettingsWindow {
2185 fn navbar_entry(&self) -> usize {
2186 self.navbar_entry
2187 }
2188
2189 fn new_builder(window: &mut Window, cx: &mut Context<Self>) -> Self {
2190 let mut this = Self::new(None, window, cx);
2191 this.navbar_entries.clear();
2192 this.pages.clear();
2193 this
2194 }
2195
2196 fn build(mut self) -> Self {
2197 self.build_search_matches();
2198 self.build_navbar();
2199 self
2200 }
2201
2202 fn add_page(
2203 mut self,
2204 title: &'static str,
2205 build_page: impl Fn(SettingsPage) -> SettingsPage,
2206 ) -> Self {
2207 let page = SettingsPage {
2208 title,
2209 items: Vec::default(),
2210 };
2211
2212 self.pages.push(build_page(page));
2213 self
2214 }
2215
2216 fn search(&mut self, search_query: &str, window: &mut Window, cx: &mut Context<Self>) {
2217 self.search_task.take();
2218 self.search_bar.update(cx, |editor, cx| {
2219 editor.set_text(search_query, window, cx);
2220 });
2221 self.update_matches(cx);
2222 }
2223
2224 fn assert_search_results(&self, other: &Self) {
2225 // page index could be different because of filtered out pages
2226 #[derive(Debug, PartialEq)]
2227 struct EntryMinimal {
2228 is_root: bool,
2229 title: &'static str,
2230 }
2231 pretty_assertions::assert_eq!(
2232 other
2233 .visible_navbar_entries()
2234 .map(|(_, entry)| EntryMinimal {
2235 is_root: entry.is_root,
2236 title: entry.title,
2237 })
2238 .collect::<Vec<_>>(),
2239 self.visible_navbar_entries()
2240 .map(|(_, entry)| EntryMinimal {
2241 is_root: entry.is_root,
2242 title: entry.title,
2243 })
2244 .collect::<Vec<_>>(),
2245 );
2246 assert_eq!(
2247 self.current_page().items.iter().collect::<Vec<_>>(),
2248 other.page_items().map(|(_, item)| item).collect::<Vec<_>>()
2249 );
2250 }
2251 }
2252
2253 impl SettingsPage {
2254 fn item(mut self, item: SettingsPageItem) -> Self {
2255 self.items.push(item);
2256 self
2257 }
2258 }
2259
2260 impl SettingsPageItem {
2261 fn basic_item(title: &'static str, description: &'static str) -> Self {
2262 SettingsPageItem::SettingItem(SettingItem {
2263 files: USER,
2264 title,
2265 description,
2266 field: Box::new(SettingField {
2267 pick: |settings_content| &settings_content.auto_update,
2268 pick_mut: |settings_content| &mut settings_content.auto_update,
2269 }),
2270 metadata: None,
2271 })
2272 }
2273 }
2274
2275 fn register_settings(cx: &mut App) {
2276 settings::init(cx);
2277 theme::init(theme::LoadThemes::JustBase, cx);
2278 workspace::init_settings(cx);
2279 project::Project::init_settings(cx);
2280 language::init(cx);
2281 editor::init(cx);
2282 menu::init();
2283 }
2284
2285 fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
2286 let mut pages: Vec<SettingsPage> = Vec::new();
2287 let mut expanded_pages = Vec::new();
2288 let mut selected_idx = None;
2289 let mut index = 0;
2290 let mut in_expanded_section = false;
2291
2292 for mut line in input
2293 .lines()
2294 .map(|line| line.trim())
2295 .filter(|line| !line.is_empty())
2296 {
2297 if let Some(pre) = line.strip_suffix('*') {
2298 assert!(selected_idx.is_none(), "Only one selected entry allowed");
2299 selected_idx = Some(index);
2300 line = pre;
2301 }
2302 let (kind, title) = line.split_once(" ").unwrap();
2303 assert_eq!(kind.len(), 1);
2304 let kind = kind.chars().next().unwrap();
2305 if kind == 'v' {
2306 let page_idx = pages.len();
2307 expanded_pages.push(page_idx);
2308 pages.push(SettingsPage {
2309 title,
2310 items: vec![],
2311 });
2312 index += 1;
2313 in_expanded_section = true;
2314 } else if kind == '>' {
2315 pages.push(SettingsPage {
2316 title,
2317 items: vec![],
2318 });
2319 index += 1;
2320 in_expanded_section = false;
2321 } else if kind == '-' {
2322 pages
2323 .last_mut()
2324 .unwrap()
2325 .items
2326 .push(SettingsPageItem::SectionHeader(title));
2327 if selected_idx == Some(index) && !in_expanded_section {
2328 panic!("Items in unexpanded sections cannot be selected");
2329 }
2330 index += 1;
2331 } else {
2332 panic!(
2333 "Entries must start with one of 'v', '>', or '-'\n line: {}",
2334 line
2335 );
2336 }
2337 }
2338
2339 let mut settings_window = SettingsWindow {
2340 original_window: None,
2341 worktree_root_dirs: HashMap::default(),
2342 files: Vec::default(),
2343 current_file: crate::SettingsUiFile::User,
2344 pages,
2345 search_bar: cx.new(|cx| Editor::single_line(window, cx)),
2346 navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
2347 navbar_entries: Vec::default(),
2348 list_handle: UniformListScrollHandle::default(),
2349 search_matches: vec![],
2350 content_handles: vec![],
2351 search_task: None,
2352 scroll_handle: ScrollHandle::new(),
2353 focus_handle: cx.focus_handle(),
2354 navbar_focus_handle: NonFocusableHandle::new(
2355 NAVBAR_CONTAINER_TAB_INDEX,
2356 false,
2357 window,
2358 cx,
2359 ),
2360 content_focus_handle: NonFocusableHandle::new(
2361 CONTENT_CONTAINER_TAB_INDEX,
2362 false,
2363 window,
2364 cx,
2365 ),
2366 files_focus_handle: cx.focus_handle(),
2367 };
2368
2369 settings_window.build_search_matches();
2370 settings_window.build_navbar();
2371 for expanded_page_index in expanded_pages {
2372 for entry in &mut settings_window.navbar_entries {
2373 if entry.page_index == expanded_page_index && entry.is_root {
2374 entry.expanded = true;
2375 }
2376 }
2377 }
2378 settings_window
2379 }
2380
2381 #[track_caller]
2382 fn check_navbar_toggle(
2383 before: &'static str,
2384 toggle_page: &'static str,
2385 after: &'static str,
2386 window: &mut Window,
2387 cx: &mut App,
2388 ) {
2389 let mut settings_window = parse(before, window, cx);
2390 let toggle_page_idx = settings_window
2391 .pages
2392 .iter()
2393 .position(|page| page.title == toggle_page)
2394 .expect("page not found");
2395 let toggle_idx = settings_window
2396 .navbar_entries
2397 .iter()
2398 .position(|entry| entry.page_index == toggle_page_idx)
2399 .expect("page not found");
2400 settings_window.toggle_navbar_entry(toggle_idx);
2401
2402 let expected_settings_window = parse(after, window, cx);
2403
2404 pretty_assertions::assert_eq!(
2405 settings_window
2406 .visible_navbar_entries()
2407 .map(|(_, entry)| entry)
2408 .collect::<Vec<_>>(),
2409 expected_settings_window
2410 .visible_navbar_entries()
2411 .map(|(_, entry)| entry)
2412 .collect::<Vec<_>>(),
2413 );
2414 pretty_assertions::assert_eq!(
2415 settings_window.navbar_entries[settings_window.navbar_entry()],
2416 expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
2417 );
2418 }
2419
2420 macro_rules! check_navbar_toggle {
2421 ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
2422 #[gpui::test]
2423 fn $name(cx: &mut gpui::TestAppContext) {
2424 let window = cx.add_empty_window();
2425 window.update(|window, cx| {
2426 register_settings(cx);
2427 check_navbar_toggle($before, $toggle_page, $after, window, cx);
2428 });
2429 }
2430 };
2431 }
2432
2433 check_navbar_toggle!(
2434 navbar_basic_open,
2435 before: r"
2436 v General
2437 - General
2438 - Privacy*
2439 v Project
2440 - Project Settings
2441 ",
2442 toggle_page: "General",
2443 after: r"
2444 > General*
2445 v Project
2446 - Project Settings
2447 "
2448 );
2449
2450 check_navbar_toggle!(
2451 navbar_basic_close,
2452 before: r"
2453 > General*
2454 - General
2455 - Privacy
2456 v Project
2457 - Project Settings
2458 ",
2459 toggle_page: "General",
2460 after: r"
2461 v General*
2462 - General
2463 - Privacy
2464 v Project
2465 - Project Settings
2466 "
2467 );
2468
2469 check_navbar_toggle!(
2470 navbar_basic_second_root_entry_close,
2471 before: r"
2472 > General
2473 - General
2474 - Privacy
2475 v Project
2476 - Project Settings*
2477 ",
2478 toggle_page: "Project",
2479 after: r"
2480 > General
2481 > Project*
2482 "
2483 );
2484
2485 check_navbar_toggle!(
2486 navbar_toggle_subroot,
2487 before: r"
2488 v General Page
2489 - General
2490 - Privacy
2491 v Project
2492 - Worktree Settings Content*
2493 v AI
2494 - General
2495 > Appearance & Behavior
2496 ",
2497 toggle_page: "Project",
2498 after: r"
2499 v General Page
2500 - General
2501 - Privacy
2502 > Project*
2503 v AI
2504 - General
2505 > Appearance & Behavior
2506 "
2507 );
2508
2509 check_navbar_toggle!(
2510 navbar_toggle_close_propagates_selected_index,
2511 before: r"
2512 v General Page
2513 - General
2514 - Privacy
2515 v Project
2516 - Worktree Settings Content
2517 v AI
2518 - General*
2519 > Appearance & Behavior
2520 ",
2521 toggle_page: "General Page",
2522 after: r"
2523 > General Page
2524 v Project
2525 - Worktree Settings Content
2526 v AI
2527 - General*
2528 > Appearance & Behavior
2529 "
2530 );
2531
2532 check_navbar_toggle!(
2533 navbar_toggle_expand_propagates_selected_index,
2534 before: r"
2535 > General Page
2536 - General
2537 - Privacy
2538 v Project
2539 - Worktree Settings Content
2540 v AI
2541 - General*
2542 > Appearance & Behavior
2543 ",
2544 toggle_page: "General Page",
2545 after: r"
2546 v General Page
2547 - General
2548 - Privacy
2549 v Project
2550 - Worktree Settings Content
2551 v AI
2552 - General*
2553 > Appearance & Behavior
2554 "
2555 );
2556
2557 #[gpui::test]
2558 fn test_basic_search(cx: &mut gpui::TestAppContext) {
2559 let cx = cx.add_empty_window();
2560 let (actual, expected) = cx.update(|window, cx| {
2561 register_settings(cx);
2562
2563 let expected = cx.new(|cx| {
2564 SettingsWindow::new_builder(window, cx)
2565 .add_page("General", |page| {
2566 page.item(SettingsPageItem::SectionHeader("General settings"))
2567 .item(SettingsPageItem::basic_item("test title", "General test"))
2568 })
2569 .build()
2570 });
2571
2572 let actual = cx.new(|cx| {
2573 SettingsWindow::new_builder(window, cx)
2574 .add_page("General", |page| {
2575 page.item(SettingsPageItem::SectionHeader("General settings"))
2576 .item(SettingsPageItem::basic_item("test title", "General test"))
2577 })
2578 .add_page("Theme", |page| {
2579 page.item(SettingsPageItem::SectionHeader("Theme settings"))
2580 })
2581 .build()
2582 });
2583
2584 actual.update(cx, |settings, cx| settings.search("gen", window, cx));
2585
2586 (actual, expected)
2587 });
2588
2589 cx.cx.run_until_parked();
2590
2591 cx.update(|_window, cx| {
2592 let expected = expected.read(cx);
2593 let actual = actual.read(cx);
2594 expected.assert_search_results(&actual);
2595 })
2596 }
2597
2598 #[gpui::test]
2599 fn test_search_render_page_with_filtered_out_navbar_entries(cx: &mut gpui::TestAppContext) {
2600 let cx = cx.add_empty_window();
2601 let (actual, expected) = cx.update(|window, cx| {
2602 register_settings(cx);
2603
2604 let actual = cx.new(|cx| {
2605 SettingsWindow::new_builder(window, cx)
2606 .add_page("General", |page| {
2607 page.item(SettingsPageItem::SectionHeader("General settings"))
2608 .item(SettingsPageItem::basic_item(
2609 "Confirm Quit",
2610 "Whether to confirm before quitting Zed",
2611 ))
2612 .item(SettingsPageItem::basic_item(
2613 "Auto Update",
2614 "Automatically update Zed",
2615 ))
2616 })
2617 .add_page("AI", |page| {
2618 page.item(SettingsPageItem::basic_item(
2619 "Disable AI",
2620 "Whether to disable all AI features in Zed",
2621 ))
2622 })
2623 .add_page("Appearance & Behavior", |page| {
2624 page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2625 SettingsPageItem::basic_item(
2626 "Cursor Shape",
2627 "Cursor shape for the editor",
2628 ),
2629 )
2630 })
2631 .build()
2632 });
2633
2634 let expected = cx.new(|cx| {
2635 SettingsWindow::new_builder(window, cx)
2636 .add_page("Appearance & Behavior", |page| {
2637 page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2638 SettingsPageItem::basic_item(
2639 "Cursor Shape",
2640 "Cursor shape for the editor",
2641 ),
2642 )
2643 })
2644 .build()
2645 });
2646
2647 actual.update(cx, |settings, cx| settings.search("cursor", window, cx));
2648
2649 (actual, expected)
2650 });
2651
2652 cx.cx.run_until_parked();
2653
2654 cx.update(|_window, cx| {
2655 let expected = expected.read(cx);
2656 let actual = actual.read(cx);
2657 expected.assert_search_results(&actual);
2658 })
2659 }
2660}