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