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