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