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