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