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