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 list_handle: UniformListScrollHandle,
562 search_matches: Vec<Vec<bool>>,
563 content_handles: Vec<Vec<Entity<NonFocusableHandle>>>,
564 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 list_handle: UniformListScrollHandle::default(),
927 search_bar,
928 search_task: None,
929 search_matches: vec![],
930 content_handles: vec![],
931 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);
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);
1495 }))
1496 .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, _| {
1497 if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
1498 this.focus_and_scroll_to_nav_entry(first_entry_index, window);
1499 }
1500 }))
1501 .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, _| {
1502 if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
1503 this.focus_and_scroll_to_nav_entry(last_entry_index, window);
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.list_handle.clone()),
1555 )
1556 .vertical_scrollbar_for(self.list_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.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.scroll_handle
1607 .scroll_to_top_of_item(selected_item_index);
1608 self.focus_content_element(entry_item_index, window, cx);
1609 }
1610 }
1611
1612 fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
1613 self.visible_navbar_entries()
1614 .any(|(index, _)| index == nav_entry_index)
1615 }
1616
1617 fn focus_and_scroll_to_nav_entry(&self, nav_entry_index: usize, window: &mut Window) {
1618 let Some(position) = self
1619 .visible_navbar_entries()
1620 .position(|(index, _)| index == nav_entry_index)
1621 else {
1622 return;
1623 };
1624 self.list_handle
1625 .scroll_to_item(position, gpui::ScrollStrategy::Top);
1626 window.focus(&self.navbar_entries[nav_entry_index].focus_handle);
1627 }
1628
1629 fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
1630 let page_idx = self.current_page_index();
1631
1632 self.current_page()
1633 .items
1634 .iter()
1635 .enumerate()
1636 .filter_map(move |(item_index, item)| {
1637 self.search_matches[page_idx][item_index].then_some((item_index, item))
1638 })
1639 }
1640
1641 fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
1642 let mut items = vec![];
1643 items.push(self.current_page().title);
1644 items.extend(
1645 sub_page_stack()
1646 .iter()
1647 .flat_map(|page| [page.section_header, page.link.title]),
1648 );
1649
1650 let last = items.pop().unwrap();
1651 h_flex()
1652 .gap_1()
1653 .children(
1654 items
1655 .into_iter()
1656 .flat_map(|item| [item, "/"])
1657 .map(|item| Label::new(item).color(Color::Muted)),
1658 )
1659 .child(Label::new(last))
1660 }
1661
1662 fn render_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
1663 &self,
1664 items: Items,
1665 page_index: Option<usize>,
1666 window: &mut Window,
1667 cx: &mut Context<SettingsWindow>,
1668 ) -> impl IntoElement {
1669 let mut page_content = v_flex()
1670 .id("settings-ui-page")
1671 .size_full()
1672 .overflow_y_scroll()
1673 .track_scroll(&self.scroll_handle);
1674
1675 let items: Vec<_> = items.collect();
1676 let items_len = items.len();
1677 let mut section_header = None;
1678
1679 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
1680 let has_no_results = items_len == 0 && has_active_search;
1681
1682 if has_no_results {
1683 let search_query = self.search_bar.read(cx).text(cx);
1684 page_content = page_content.child(
1685 v_flex()
1686 .size_full()
1687 .items_center()
1688 .justify_center()
1689 .gap_1()
1690 .child(div().child("No Results"))
1691 .child(
1692 div()
1693 .text_sm()
1694 .text_color(cx.theme().colors().text_muted)
1695 .child(format!("No settings match \"{}\"", search_query)),
1696 ),
1697 )
1698 } else {
1699 let last_non_header_index = items
1700 .iter()
1701 .enumerate()
1702 .rev()
1703 .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
1704 .map(|(index, _)| index);
1705
1706 page_content = page_content.children(items.clone().into_iter().enumerate().map(
1707 |(index, (actual_item_index, item))| {
1708 let no_bottom_border = items
1709 .get(index + 1)
1710 .map(|(_, next_item)| {
1711 matches!(next_item, SettingsPageItem::SectionHeader(_))
1712 })
1713 .unwrap_or(false);
1714 let is_last = Some(index) == last_non_header_index;
1715
1716 if let SettingsPageItem::SectionHeader(header) = item {
1717 section_header = Some(*header);
1718 }
1719 v_flex()
1720 .w_full()
1721 .min_w_0()
1722 .id(("settings-page-item", actual_item_index))
1723 .when_some(page_index, |element, page_index| {
1724 element.track_focus(
1725 &self.content_handles[page_index][actual_item_index]
1726 .focus_handle(cx),
1727 )
1728 })
1729 .child(item.render(
1730 self,
1731 section_header.expect("All items rendered after a section header"),
1732 no_bottom_border || is_last,
1733 window,
1734 cx,
1735 ))
1736 },
1737 ))
1738 }
1739 page_content
1740 }
1741
1742 fn render_page(
1743 &mut self,
1744 window: &mut Window,
1745 cx: &mut Context<SettingsWindow>,
1746 ) -> impl IntoElement {
1747 let page_header;
1748 let page_content;
1749
1750 if sub_page_stack().is_empty() {
1751 page_header = self.render_files_header(window, cx).into_any_element();
1752
1753 page_content = self
1754 .render_page_items(
1755 self.visible_page_items(),
1756 Some(self.current_page_index()),
1757 window,
1758 cx,
1759 )
1760 .into_any_element();
1761 } else {
1762 page_header = h_flex()
1763 .ml_neg_1p5()
1764 .pb_4()
1765 .gap_1()
1766 .child(
1767 IconButton::new("back-btn", IconName::ArrowLeft)
1768 .icon_size(IconSize::Small)
1769 .shape(IconButtonShape::Square)
1770 .on_click(cx.listener(|this, _, _, cx| {
1771 this.pop_sub_page(cx);
1772 })),
1773 )
1774 .child(self.render_sub_page_breadcrumbs())
1775 .into_any_element();
1776
1777 let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
1778 page_content = (active_page_render_fn)(self, window, cx);
1779 }
1780
1781 return v_flex()
1782 .size_full()
1783 .pt_6()
1784 .pb_8()
1785 .px_8()
1786 .bg(cx.theme().colors().editor_background)
1787 .child(page_header)
1788 .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx)
1789 .track_focus(&self.content_focus_handle.focus_handle(cx))
1790 .child(
1791 div()
1792 .size_full()
1793 .tab_group()
1794 .tab_index(CONTENT_GROUP_TAB_INDEX)
1795 .child(page_content),
1796 );
1797 }
1798
1799 fn open_current_settings_file(&mut self, cx: &mut Context<Self>) {
1800 match &self.current_file {
1801 SettingsUiFile::User => {
1802 let Some(original_window) = self.original_window else {
1803 return;
1804 };
1805 original_window
1806 .update(cx, |workspace, window, cx| {
1807 workspace
1808 .with_local_workspace(window, cx, |workspace, window, cx| {
1809 let create_task = workspace.project().update(cx, |project, cx| {
1810 project.find_or_create_worktree(
1811 paths::config_dir().as_path(),
1812 false,
1813 cx,
1814 )
1815 });
1816 let open_task = workspace.open_paths(
1817 vec![paths::settings_file().to_path_buf()],
1818 OpenOptions {
1819 visible: Some(OpenVisible::None),
1820 ..Default::default()
1821 },
1822 None,
1823 window,
1824 cx,
1825 );
1826
1827 cx.spawn_in(window, async move |workspace, cx| {
1828 create_task.await.ok();
1829 open_task.await;
1830
1831 workspace.update_in(cx, |_, window, cx| {
1832 window.activate_window();
1833 cx.notify();
1834 })
1835 })
1836 .detach();
1837 })
1838 .detach();
1839 })
1840 .ok();
1841 }
1842 SettingsUiFile::Project((worktree_id, path)) => {
1843 let mut corresponding_workspace: Option<WindowHandle<Workspace>> = None;
1844 let settings_path = path.join(paths::local_settings_file_relative_path());
1845 let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
1846 return;
1847 };
1848 for workspace in app_state.workspace_store.read(cx).workspaces() {
1849 let contains_settings_file = workspace
1850 .read_with(cx, |workspace, cx| {
1851 workspace.project().read(cx).contains_local_settings_file(
1852 *worktree_id,
1853 settings_path.as_ref(),
1854 cx,
1855 )
1856 })
1857 .ok();
1858 if Some(true) == contains_settings_file {
1859 corresponding_workspace = Some(*workspace);
1860
1861 break;
1862 }
1863 }
1864
1865 let Some(corresponding_workspace) = corresponding_workspace else {
1866 log::error!(
1867 "No corresponding workspace found for settings file {}",
1868 settings_path.as_std_path().display()
1869 );
1870
1871 return;
1872 };
1873
1874 // TODO: move zed::open_local_file() APIs to this crate, and
1875 // re-implement the "initial_contents" behavior
1876 corresponding_workspace
1877 .update(cx, |workspace, window, cx| {
1878 let open_task = workspace.open_path(
1879 (*worktree_id, settings_path.clone()),
1880 None,
1881 true,
1882 window,
1883 cx,
1884 );
1885
1886 cx.spawn_in(window, async move |workspace, cx| {
1887 if open_task.await.log_err().is_some() {
1888 workspace
1889 .update_in(cx, |_, window, cx| {
1890 window.activate_window();
1891 cx.notify();
1892 })
1893 .ok();
1894 }
1895 })
1896 .detach();
1897 })
1898 .ok();
1899 }
1900 SettingsUiFile::Server(_) => {
1901 return;
1902 }
1903 };
1904 }
1905
1906 fn current_page_index(&self) -> usize {
1907 self.page_index_from_navbar_index(self.navbar_entry)
1908 }
1909
1910 fn current_page(&self) -> &SettingsPage {
1911 &self.pages[self.current_page_index()]
1912 }
1913
1914 fn page_index_from_navbar_index(&self, index: usize) -> usize {
1915 if self.navbar_entries.is_empty() {
1916 return 0;
1917 }
1918
1919 self.navbar_entries[index].page_index
1920 }
1921
1922 fn is_navbar_entry_selected(&self, ix: usize) -> bool {
1923 ix == self.navbar_entry
1924 }
1925
1926 fn push_sub_page(
1927 &mut self,
1928 sub_page_link: SubPageLink,
1929 section_header: &'static str,
1930 cx: &mut Context<SettingsWindow>,
1931 ) {
1932 sub_page_stack_mut().push(SubPage {
1933 link: sub_page_link,
1934 section_header,
1935 });
1936 cx.notify();
1937 }
1938
1939 fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
1940 sub_page_stack_mut().pop();
1941 cx.notify();
1942 }
1943
1944 fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
1945 if let Some((_, handle)) = self.files.get(index) {
1946 handle.focus(window);
1947 }
1948 }
1949
1950 fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
1951 if self.files_focus_handle.contains_focused(window, cx)
1952 && let Some(index) = self
1953 .files
1954 .iter()
1955 .position(|(_, handle)| handle.is_focused(window))
1956 {
1957 return index;
1958 }
1959 if let Some(current_file_index) = self
1960 .files
1961 .iter()
1962 .position(|(file, _)| file == &self.current_file)
1963 {
1964 return current_file_index;
1965 }
1966 0
1967 }
1968
1969 fn focus_content_element(&self, item_index: usize, window: &mut Window, cx: &mut App) {
1970 if !sub_page_stack().is_empty() {
1971 return;
1972 }
1973 let page_index = self.current_page_index();
1974 window.focus(&self.content_handles[page_index][item_index].focus_handle(cx));
1975 }
1976
1977 fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
1978 if !self
1979 .navbar_focus_handle
1980 .focus_handle(cx)
1981 .contains_focused(window, cx)
1982 {
1983 return None;
1984 }
1985 for (index, entry) in self.navbar_entries.iter().enumerate() {
1986 if entry.focus_handle.is_focused(window) {
1987 return Some(index);
1988 }
1989 }
1990 None
1991 }
1992
1993 fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
1994 let mut index = Some(nav_entry_index);
1995 while let Some(prev_index) = index
1996 && !self.navbar_entries[prev_index].is_root
1997 {
1998 index = prev_index.checked_sub(1);
1999 }
2000 return index.expect("No root entry found");
2001 }
2002}
2003
2004impl Render for SettingsWindow {
2005 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2006 let ui_font = theme::setup_ui_font(window, cx);
2007
2008 div()
2009 .id("settings-window")
2010 .key_context("SettingsWindow")
2011 .track_focus(&self.focus_handle)
2012 .on_action(cx.listener(|this, _: &OpenCurrentFile, _, cx| {
2013 this.open_current_settings_file(cx);
2014 }))
2015 .on_action(|_: &Minimize, window, _cx| {
2016 window.minimize_window();
2017 })
2018 .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
2019 this.search_bar.focus_handle(cx).focus(window);
2020 }))
2021 .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
2022 if this
2023 .navbar_focus_handle
2024 .focus_handle(cx)
2025 .contains_focused(window, cx)
2026 {
2027 this.open_and_scroll_to_navbar_entry(this.navbar_entry, window, cx);
2028 } else {
2029 this.focus_and_scroll_to_nav_entry(this.navbar_entry, window);
2030 }
2031 }))
2032 .on_action(
2033 cx.listener(|this, FocusFile(file_index): &FocusFile, window, _| {
2034 this.focus_file_at_index(*file_index as usize, window);
2035 }),
2036 )
2037 .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
2038 let next_index = usize::min(
2039 this.focused_file_index(window, cx) + 1,
2040 this.files.len().saturating_sub(1),
2041 );
2042 this.focus_file_at_index(next_index, window);
2043 }))
2044 .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
2045 let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
2046 this.focus_file_at_index(prev_index, window);
2047 }))
2048 .on_action(|_: &menu::SelectNext, window, _| {
2049 window.focus_next();
2050 })
2051 .on_action(|_: &menu::SelectPrevious, window, _| {
2052 window.focus_prev();
2053 })
2054 .flex()
2055 .flex_row()
2056 .size_full()
2057 .font(ui_font)
2058 .bg(cx.theme().colors().background)
2059 .text_color(cx.theme().colors().text)
2060 .child(self.render_nav(window, cx))
2061 .child(self.render_page(window, cx))
2062 }
2063}
2064
2065fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
2066 workspace::AppState::global(cx)
2067 .upgrade()
2068 .map(|app_state| {
2069 app_state
2070 .workspace_store
2071 .read(cx)
2072 .workspaces()
2073 .iter()
2074 .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
2075 })
2076 .into_iter()
2077 .flatten()
2078}
2079
2080fn update_settings_file(
2081 file: SettingsUiFile,
2082 cx: &mut App,
2083 update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
2084) -> Result<()> {
2085 match file {
2086 SettingsUiFile::Project((worktree_id, rel_path)) => {
2087 let rel_path = rel_path.join(paths::local_settings_file_relative_path());
2088 let project = all_projects(cx).find(|project| {
2089 project.read_with(cx, |project, cx| {
2090 project.contains_local_settings_file(worktree_id, &rel_path, cx)
2091 })
2092 });
2093 let Some(project) = project else {
2094 anyhow::bail!(
2095 "Could not find worktree containing settings file: {}",
2096 &rel_path.display(PathStyle::local())
2097 );
2098 };
2099 project.update(cx, |project, cx| {
2100 project.update_local_settings_file(worktree_id, rel_path, cx, update);
2101 });
2102 return Ok(());
2103 }
2104 SettingsUiFile::User => {
2105 // todo(settings_ui) error?
2106 SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
2107 Ok(())
2108 }
2109 SettingsUiFile::Server(_) => unimplemented!(),
2110 }
2111}
2112
2113fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
2114 field: SettingField<T>,
2115 file: SettingsUiFile,
2116 metadata: Option<&SettingsFieldMetadata>,
2117 cx: &mut App,
2118) -> AnyElement {
2119 let (_, initial_text) =
2120 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2121 let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
2122
2123 SettingsEditor::new()
2124 .tab_index(0)
2125 .when_some(initial_text, |editor, text| {
2126 editor.with_initial_text(text.as_ref().to_string())
2127 })
2128 .when_some(
2129 metadata.and_then(|metadata| metadata.placeholder),
2130 |editor, placeholder| editor.with_placeholder(placeholder),
2131 )
2132 .on_confirm({
2133 move |new_text, cx| {
2134 update_settings_file(file.clone(), cx, move |settings, _cx| {
2135 *(field.pick_mut)(settings) = new_text.map(Into::into);
2136 })
2137 .log_err(); // todo(settings_ui) don't log err
2138 }
2139 })
2140 .into_any_element()
2141}
2142
2143fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
2144 field: SettingField<B>,
2145 file: SettingsUiFile,
2146 cx: &mut App,
2147) -> AnyElement {
2148 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2149
2150 let toggle_state = if value.copied().map_or(false, Into::into) {
2151 ToggleState::Selected
2152 } else {
2153 ToggleState::Unselected
2154 };
2155
2156 Switch::new("toggle_button", toggle_state)
2157 .color(ui::SwitchColor::Accent)
2158 .on_click({
2159 move |state, _window, cx| {
2160 let state = *state == ui::ToggleState::Selected;
2161 update_settings_file(file.clone(), cx, move |settings, _cx| {
2162 *(field.pick_mut)(settings) = Some(state.into());
2163 })
2164 .log_err(); // todo(settings_ui) don't log err
2165 }
2166 })
2167 .tab_index(0_isize)
2168 .color(SwitchColor::Accent)
2169 .into_any_element()
2170}
2171
2172fn render_font_picker(
2173 field: SettingField<settings::FontFamilyName>,
2174 file: SettingsUiFile,
2175 window: &mut Window,
2176 cx: &mut App,
2177) -> AnyElement {
2178 let current_value = SettingsStore::global(cx)
2179 .get_value_from_file(file.to_settings(), field.pick)
2180 .1
2181 .cloned()
2182 .unwrap_or_else(|| SharedString::default().into());
2183
2184 let font_picker = cx.new(|cx| {
2185 ui_input::font_picker(
2186 current_value.clone().into(),
2187 move |font_name, cx| {
2188 update_settings_file(file.clone(), cx, move |settings, _cx| {
2189 *(field.pick_mut)(settings) = Some(font_name.into());
2190 })
2191 .log_err(); // todo(settings_ui) don't log err
2192 },
2193 window,
2194 cx,
2195 )
2196 });
2197
2198 PopoverMenu::new("font-picker")
2199 .menu(move |_window, _cx| Some(font_picker.clone()))
2200 .trigger(
2201 Button::new("font-family-button", current_value)
2202 .tab_index(0_isize)
2203 .style(ButtonStyle::Outlined)
2204 .size(ButtonSize::Medium)
2205 .icon(IconName::ChevronUpDown)
2206 .icon_color(Color::Muted)
2207 .icon_size(IconSize::Small)
2208 .icon_position(IconPosition::End),
2209 )
2210 .anchor(gpui::Corner::TopLeft)
2211 .offset(gpui::Point {
2212 x: px(0.0),
2213 y: px(2.0),
2214 })
2215 .with_handle(ui::PopoverMenuHandle::default())
2216 .into_any_element()
2217}
2218
2219fn render_number_field<T: NumberFieldType + Send + Sync>(
2220 field: SettingField<T>,
2221 file: SettingsUiFile,
2222 window: &mut Window,
2223 cx: &mut App,
2224) -> AnyElement {
2225 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2226 let value = value.copied().unwrap_or_else(T::min_value);
2227 NumberField::new("numeric_stepper", value, window, cx)
2228 .on_change({
2229 move |value, _window, cx| {
2230 let value = *value;
2231 update_settings_file(file.clone(), cx, move |settings, _cx| {
2232 *(field.pick_mut)(settings) = Some(value);
2233 })
2234 .log_err(); // todo(settings_ui) don't log err
2235 }
2236 })
2237 .into_any_element()
2238}
2239
2240fn render_dropdown<T>(
2241 field: SettingField<T>,
2242 file: SettingsUiFile,
2243 window: &mut Window,
2244 cx: &mut App,
2245) -> AnyElement
2246where
2247 T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
2248{
2249 let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
2250 let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
2251
2252 let (_, current_value) =
2253 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
2254 let current_value = current_value.copied().unwrap_or(variants()[0]);
2255
2256 let current_value_label =
2257 labels()[variants().iter().position(|v| *v == current_value).unwrap()];
2258
2259 DropdownMenu::new(
2260 "dropdown",
2261 current_value_label.to_title_case(),
2262 ContextMenu::build(window, cx, move |mut menu, _, _| {
2263 for (&value, &label) in std::iter::zip(variants(), labels()) {
2264 let file = file.clone();
2265 menu = menu.toggleable_entry(
2266 label.to_title_case(),
2267 value == current_value,
2268 IconPosition::End,
2269 None,
2270 move |_, cx| {
2271 if value == current_value {
2272 return;
2273 }
2274 update_settings_file(file.clone(), cx, move |settings, _cx| {
2275 *(field.pick_mut)(settings) = Some(value);
2276 })
2277 .log_err(); // todo(settings_ui) don't log err
2278 },
2279 );
2280 }
2281 menu
2282 }),
2283 )
2284 .trigger_size(ButtonSize::Medium)
2285 .style(DropdownStyle::Outlined)
2286 .offset(gpui::Point {
2287 x: px(0.0),
2288 y: px(2.0),
2289 })
2290 .tab_index(0)
2291 .into_any_element()
2292}
2293
2294#[cfg(test)]
2295mod test {
2296
2297 use super::*;
2298
2299 impl SettingsWindow {
2300 fn navbar_entry(&self) -> usize {
2301 self.navbar_entry
2302 }
2303
2304 fn new_builder(window: &mut Window, cx: &mut Context<Self>) -> Self {
2305 let mut this = Self::new(None, window, cx);
2306 this.navbar_entries.clear();
2307 this.pages.clear();
2308 this
2309 }
2310
2311 fn build(mut self, cx: &App) -> Self {
2312 self.build_search_matches();
2313 self.build_navbar(cx);
2314 self
2315 }
2316
2317 fn add_page(
2318 mut self,
2319 title: &'static str,
2320 build_page: impl Fn(SettingsPage) -> SettingsPage,
2321 ) -> Self {
2322 let page = SettingsPage {
2323 title,
2324 items: Vec::default(),
2325 };
2326
2327 self.pages.push(build_page(page));
2328 self
2329 }
2330
2331 fn search(&mut self, search_query: &str, window: &mut Window, cx: &mut Context<Self>) {
2332 self.search_task.take();
2333 self.search_bar.update(cx, |editor, cx| {
2334 editor.set_text(search_query, window, cx);
2335 });
2336 self.update_matches(cx);
2337 }
2338
2339 fn assert_search_results(&self, other: &Self) {
2340 // page index could be different because of filtered out pages
2341 #[derive(Debug, PartialEq)]
2342 struct EntryMinimal {
2343 is_root: bool,
2344 title: &'static str,
2345 }
2346 pretty_assertions::assert_eq!(
2347 other
2348 .visible_navbar_entries()
2349 .map(|(_, entry)| EntryMinimal {
2350 is_root: entry.is_root,
2351 title: entry.title,
2352 })
2353 .collect::<Vec<_>>(),
2354 self.visible_navbar_entries()
2355 .map(|(_, entry)| EntryMinimal {
2356 is_root: entry.is_root,
2357 title: entry.title,
2358 })
2359 .collect::<Vec<_>>(),
2360 );
2361 assert_eq!(
2362 self.current_page().items.iter().collect::<Vec<_>>(),
2363 other
2364 .visible_page_items()
2365 .map(|(_, item)| item)
2366 .collect::<Vec<_>>()
2367 );
2368 }
2369 }
2370
2371 impl SettingsPage {
2372 fn item(mut self, item: SettingsPageItem) -> Self {
2373 self.items.push(item);
2374 self
2375 }
2376 }
2377
2378 impl PartialEq for NavBarEntry {
2379 fn eq(&self, other: &Self) -> bool {
2380 self.title == other.title
2381 && self.is_root == other.is_root
2382 && self.expanded == other.expanded
2383 && self.page_index == other.page_index
2384 && self.item_index == other.item_index
2385 // ignoring focus_handle
2386 }
2387 }
2388
2389 impl SettingsPageItem {
2390 fn basic_item(title: &'static str, description: &'static str) -> Self {
2391 SettingsPageItem::SettingItem(SettingItem {
2392 files: USER,
2393 title,
2394 description,
2395 field: Box::new(SettingField {
2396 pick: |settings_content| &settings_content.auto_update,
2397 pick_mut: |settings_content| &mut settings_content.auto_update,
2398 }),
2399 metadata: None,
2400 })
2401 }
2402 }
2403
2404 fn register_settings(cx: &mut App) {
2405 settings::init(cx);
2406 theme::init(theme::LoadThemes::JustBase, cx);
2407 workspace::init_settings(cx);
2408 project::Project::init_settings(cx);
2409 language::init(cx);
2410 editor::init(cx);
2411 menu::init();
2412 }
2413
2414 fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
2415 let mut pages: Vec<SettingsPage> = Vec::new();
2416 let mut expanded_pages = Vec::new();
2417 let mut selected_idx = None;
2418 let mut index = 0;
2419 let mut in_expanded_section = false;
2420
2421 for mut line in input
2422 .lines()
2423 .map(|line| line.trim())
2424 .filter(|line| !line.is_empty())
2425 {
2426 if let Some(pre) = line.strip_suffix('*') {
2427 assert!(selected_idx.is_none(), "Only one selected entry allowed");
2428 selected_idx = Some(index);
2429 line = pre;
2430 }
2431 let (kind, title) = line.split_once(" ").unwrap();
2432 assert_eq!(kind.len(), 1);
2433 let kind = kind.chars().next().unwrap();
2434 if kind == 'v' {
2435 let page_idx = pages.len();
2436 expanded_pages.push(page_idx);
2437 pages.push(SettingsPage {
2438 title,
2439 items: vec![],
2440 });
2441 index += 1;
2442 in_expanded_section = true;
2443 } else if kind == '>' {
2444 pages.push(SettingsPage {
2445 title,
2446 items: vec![],
2447 });
2448 index += 1;
2449 in_expanded_section = false;
2450 } else if kind == '-' {
2451 pages
2452 .last_mut()
2453 .unwrap()
2454 .items
2455 .push(SettingsPageItem::SectionHeader(title));
2456 if selected_idx == Some(index) && !in_expanded_section {
2457 panic!("Items in unexpanded sections cannot be selected");
2458 }
2459 index += 1;
2460 } else {
2461 panic!(
2462 "Entries must start with one of 'v', '>', or '-'\n line: {}",
2463 line
2464 );
2465 }
2466 }
2467
2468 let mut settings_window = SettingsWindow {
2469 original_window: None,
2470 worktree_root_dirs: HashMap::default(),
2471 files: Vec::default(),
2472 current_file: crate::SettingsUiFile::User,
2473 pages,
2474 search_bar: cx.new(|cx| Editor::single_line(window, cx)),
2475 navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
2476 navbar_entries: Vec::default(),
2477 list_handle: UniformListScrollHandle::default(),
2478 search_matches: vec![],
2479 content_handles: vec![],
2480 search_task: None,
2481 scroll_handle: ScrollHandle::new(),
2482 focus_handle: cx.focus_handle(),
2483 navbar_focus_handle: NonFocusableHandle::new(
2484 NAVBAR_CONTAINER_TAB_INDEX,
2485 false,
2486 window,
2487 cx,
2488 ),
2489 content_focus_handle: NonFocusableHandle::new(
2490 CONTENT_CONTAINER_TAB_INDEX,
2491 false,
2492 window,
2493 cx,
2494 ),
2495 files_focus_handle: cx.focus_handle(),
2496 };
2497
2498 settings_window.build_search_matches();
2499 settings_window.build_navbar(cx);
2500 for expanded_page_index in expanded_pages {
2501 for entry in &mut settings_window.navbar_entries {
2502 if entry.page_index == expanded_page_index && entry.is_root {
2503 entry.expanded = true;
2504 }
2505 }
2506 }
2507 settings_window
2508 }
2509
2510 #[track_caller]
2511 fn check_navbar_toggle(
2512 before: &'static str,
2513 toggle_page: &'static str,
2514 after: &'static str,
2515 window: &mut Window,
2516 cx: &mut App,
2517 ) {
2518 let mut settings_window = parse(before, window, cx);
2519 let toggle_page_idx = settings_window
2520 .pages
2521 .iter()
2522 .position(|page| page.title == toggle_page)
2523 .expect("page not found");
2524 let toggle_idx = settings_window
2525 .navbar_entries
2526 .iter()
2527 .position(|entry| entry.page_index == toggle_page_idx)
2528 .expect("page not found");
2529 settings_window.toggle_navbar_entry(toggle_idx);
2530
2531 let expected_settings_window = parse(after, window, cx);
2532
2533 pretty_assertions::assert_eq!(
2534 settings_window
2535 .visible_navbar_entries()
2536 .map(|(_, entry)| entry)
2537 .collect::<Vec<_>>(),
2538 expected_settings_window
2539 .visible_navbar_entries()
2540 .map(|(_, entry)| entry)
2541 .collect::<Vec<_>>(),
2542 );
2543 pretty_assertions::assert_eq!(
2544 settings_window.navbar_entries[settings_window.navbar_entry()],
2545 expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
2546 );
2547 }
2548
2549 macro_rules! check_navbar_toggle {
2550 ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
2551 #[gpui::test]
2552 fn $name(cx: &mut gpui::TestAppContext) {
2553 let window = cx.add_empty_window();
2554 window.update(|window, cx| {
2555 register_settings(cx);
2556 check_navbar_toggle($before, $toggle_page, $after, window, cx);
2557 });
2558 }
2559 };
2560 }
2561
2562 check_navbar_toggle!(
2563 navbar_basic_open,
2564 before: r"
2565 v General
2566 - General
2567 - Privacy*
2568 v Project
2569 - Project Settings
2570 ",
2571 toggle_page: "General",
2572 after: r"
2573 > General*
2574 v Project
2575 - Project Settings
2576 "
2577 );
2578
2579 check_navbar_toggle!(
2580 navbar_basic_close,
2581 before: r"
2582 > General*
2583 - General
2584 - Privacy
2585 v Project
2586 - Project Settings
2587 ",
2588 toggle_page: "General",
2589 after: r"
2590 v General*
2591 - General
2592 - Privacy
2593 v Project
2594 - Project Settings
2595 "
2596 );
2597
2598 check_navbar_toggle!(
2599 navbar_basic_second_root_entry_close,
2600 before: r"
2601 > General
2602 - General
2603 - Privacy
2604 v Project
2605 - Project Settings*
2606 ",
2607 toggle_page: "Project",
2608 after: r"
2609 > General
2610 > Project*
2611 "
2612 );
2613
2614 check_navbar_toggle!(
2615 navbar_toggle_subroot,
2616 before: r"
2617 v General Page
2618 - General
2619 - Privacy
2620 v Project
2621 - Worktree Settings Content*
2622 v AI
2623 - General
2624 > Appearance & Behavior
2625 ",
2626 toggle_page: "Project",
2627 after: r"
2628 v General Page
2629 - General
2630 - Privacy
2631 > Project*
2632 v AI
2633 - General
2634 > Appearance & Behavior
2635 "
2636 );
2637
2638 check_navbar_toggle!(
2639 navbar_toggle_close_propagates_selected_index,
2640 before: r"
2641 v General Page
2642 - General
2643 - Privacy
2644 v Project
2645 - Worktree Settings Content
2646 v AI
2647 - General*
2648 > Appearance & Behavior
2649 ",
2650 toggle_page: "General Page",
2651 after: r"
2652 > General Page
2653 v Project
2654 - Worktree Settings Content
2655 v AI
2656 - General*
2657 > Appearance & Behavior
2658 "
2659 );
2660
2661 check_navbar_toggle!(
2662 navbar_toggle_expand_propagates_selected_index,
2663 before: r"
2664 > General Page
2665 - General
2666 - Privacy
2667 v Project
2668 - Worktree Settings Content
2669 v AI
2670 - General*
2671 > Appearance & Behavior
2672 ",
2673 toggle_page: "General Page",
2674 after: r"
2675 v General Page
2676 - General
2677 - Privacy
2678 v Project
2679 - Worktree Settings Content
2680 v AI
2681 - General*
2682 > Appearance & Behavior
2683 "
2684 );
2685
2686 #[gpui::test]
2687 fn test_basic_search(cx: &mut gpui::TestAppContext) {
2688 let cx = cx.add_empty_window();
2689 let (actual, expected) = cx.update(|window, cx| {
2690 register_settings(cx);
2691
2692 let expected = cx.new(|cx| {
2693 SettingsWindow::new_builder(window, cx)
2694 .add_page("General", |page| {
2695 page.item(SettingsPageItem::SectionHeader("General settings"))
2696 .item(SettingsPageItem::basic_item("test title", "General test"))
2697 })
2698 .build(cx)
2699 });
2700
2701 let actual = cx.new(|cx| {
2702 SettingsWindow::new_builder(window, cx)
2703 .add_page("General", |page| {
2704 page.item(SettingsPageItem::SectionHeader("General settings"))
2705 .item(SettingsPageItem::basic_item("test title", "General test"))
2706 })
2707 .add_page("Theme", |page| {
2708 page.item(SettingsPageItem::SectionHeader("Theme settings"))
2709 })
2710 .build(cx)
2711 });
2712
2713 actual.update(cx, |settings, cx| settings.search("gen", window, cx));
2714
2715 (actual, expected)
2716 });
2717
2718 cx.cx.run_until_parked();
2719
2720 cx.update(|_window, cx| {
2721 let expected = expected.read(cx);
2722 let actual = actual.read(cx);
2723 expected.assert_search_results(&actual);
2724 })
2725 }
2726
2727 #[gpui::test]
2728 fn test_search_render_page_with_filtered_out_navbar_entries(cx: &mut gpui::TestAppContext) {
2729 let cx = cx.add_empty_window();
2730 let (actual, expected) = cx.update(|window, cx| {
2731 register_settings(cx);
2732
2733 let actual = cx.new(|cx| {
2734 SettingsWindow::new_builder(window, cx)
2735 .add_page("General", |page| {
2736 page.item(SettingsPageItem::SectionHeader("General settings"))
2737 .item(SettingsPageItem::basic_item(
2738 "Confirm Quit",
2739 "Whether to confirm before quitting Zed",
2740 ))
2741 .item(SettingsPageItem::basic_item(
2742 "Auto Update",
2743 "Automatically update Zed",
2744 ))
2745 })
2746 .add_page("AI", |page| {
2747 page.item(SettingsPageItem::basic_item(
2748 "Disable AI",
2749 "Whether to disable all AI features in Zed",
2750 ))
2751 })
2752 .add_page("Appearance & Behavior", |page| {
2753 page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2754 SettingsPageItem::basic_item(
2755 "Cursor Shape",
2756 "Cursor shape for the editor",
2757 ),
2758 )
2759 })
2760 .build(cx)
2761 });
2762
2763 let expected = cx.new(|cx| {
2764 SettingsWindow::new_builder(window, cx)
2765 .add_page("Appearance & Behavior", |page| {
2766 page.item(SettingsPageItem::SectionHeader("Cursor")).item(
2767 SettingsPageItem::basic_item(
2768 "Cursor Shape",
2769 "Cursor shape for the editor",
2770 ),
2771 )
2772 })
2773 .build(cx)
2774 });
2775
2776 actual.update(cx, |settings, cx| settings.search("cursor", window, cx));
2777
2778 (actual, expected)
2779 });
2780
2781 cx.cx.run_until_parked();
2782
2783 cx.update(|_window, cx| {
2784 let expected = expected.read(cx);
2785 let actual = actual.read(cx);
2786 expected.assert_search_results(&actual);
2787 })
2788 }
2789}