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