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