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