1mod components;
2mod page_data;
3
4use anyhow::Result;
5use editor::{Editor, EditorEvent};
6use feature_flags::FeatureFlag;
7use fuzzy::StringMatchCandidate;
8use gpui::{
9 Action, App, ClipboardItem, DEFAULT_ADDITIONAL_WINDOW_SIZE, Div, Entity, FocusHandle,
10 Focusable, Global, ListState, ReadGlobal as _, ScrollHandle, Stateful, Subscription, Task,
11 TitlebarOptions, UniformListScrollHandle, Window, WindowBounds, WindowHandle, WindowOptions,
12 actions, div, list, point, prelude::*, px, uniform_list,
13};
14use heck::ToTitleCase as _;
15use project::{Project, WorktreeId};
16use release_channel::ReleaseChannel;
17use schemars::JsonSchema;
18use serde::Deserialize;
19use settings::{Settings, SettingsContent, SettingsStore};
20use std::{
21 any::{Any, TypeId, type_name},
22 cell::RefCell,
23 collections::HashMap,
24 num::{NonZero, NonZeroU32},
25 ops::Range,
26 rc::Rc,
27 sync::{Arc, LazyLock, RwLock},
28};
29use title_bar::platform_title_bar::PlatformTitleBar;
30use ui::{
31 Banner, ContextMenu, Divider, DividerColor, DropdownMenu, DropdownStyle, IconButtonShape,
32 KeyBinding, KeybindingHint, PopoverMenu, Switch, SwitchColor, Tooltip, TreeViewItem,
33 WithScrollbar, prelude::*,
34};
35use ui_input::{NumberField, NumberFieldType};
36use util::{ResultExt as _, paths::PathStyle, rel_path::RelPath};
37use workspace::{AppState, OpenOptions, OpenVisible, Workspace, client_side_decorations};
38use zed_actions::{OpenSettings, OpenSettingsAt};
39
40use crate::components::{SettingsInputField, font_picker, icon_theme_picker, theme_picker};
41
42const NAVBAR_CONTAINER_TAB_INDEX: isize = 0;
43const NAVBAR_GROUP_TAB_INDEX: isize = 1;
44
45const HEADER_CONTAINER_TAB_INDEX: isize = 2;
46const HEADER_GROUP_TAB_INDEX: isize = 3;
47
48const CONTENT_CONTAINER_TAB_INDEX: isize = 4;
49const CONTENT_GROUP_TAB_INDEX: isize = 5;
50
51actions!(
52 settings_editor,
53 [
54 /// Minimizes the settings UI window.
55 Minimize,
56 /// Toggles focus between the navbar and the main content.
57 ToggleFocusNav,
58 /// Expands the navigation entry.
59 ExpandNavEntry,
60 /// Collapses the navigation entry.
61 CollapseNavEntry,
62 /// Focuses the next file in the file list.
63 FocusNextFile,
64 /// Focuses the previous file in the file list.
65 FocusPreviousFile,
66 /// Opens an editor for the current file
67 OpenCurrentFile,
68 /// Focuses the previous root navigation entry.
69 FocusPreviousRootNavEntry,
70 /// Focuses the next root navigation entry.
71 FocusNextRootNavEntry,
72 /// Focuses the first navigation entry.
73 FocusFirstNavEntry,
74 /// Focuses the last navigation entry.
75 FocusLastNavEntry,
76 /// Focuses and opens the next navigation entry without moving focus to content.
77 FocusNextNavEntry,
78 /// Focuses and opens the previous navigation entry without moving focus to content.
79 FocusPreviousNavEntry
80 ]
81);
82
83#[derive(Action, PartialEq, Eq, Clone, Copy, Debug, JsonSchema, Deserialize)]
84#[action(namespace = settings_editor)]
85struct FocusFile(pub u32);
86
87struct SettingField<T: 'static> {
88 pick: fn(&SettingsContent) -> Option<&T>,
89 write: fn(&mut SettingsContent, Option<T>),
90
91 /// A json-path-like string that gives a unique-ish string that identifies
92 /// where in the JSON the setting is defined.
93 ///
94 /// The syntax is `jq`-like, but modified slightly to be URL-safe (and
95 /// without the leading dot), e.g. `foo.bar`.
96 ///
97 /// They are URL-safe (this is important since links are the main use-case
98 /// for these paths).
99 ///
100 /// There are a couple of special cases:
101 /// - discrimminants are represented with a trailing `$`, for example
102 /// `terminal.working_directory$`. This is to distinguish the discrimminant
103 /// setting (i.e. the setting that changes whether the value is a string or
104 /// an object) from the setting in the case that it is a string.
105 /// - language-specific settings begin `languages.$(language)`. Links
106 /// targeting these settings should take the form `languages/Rust/...`, for
107 /// example, but are not currently supported.
108 json_path: Option<&'static str>,
109}
110
111impl<T: 'static> Clone for SettingField<T> {
112 fn clone(&self) -> Self {
113 *self
114 }
115}
116
117// manual impl because derive puts a Copy bound on T, which is inaccurate in our case
118impl<T: 'static> Copy for SettingField<T> {}
119
120/// Helper for unimplemented settings, used in combination with `SettingField::unimplemented`
121/// to keep the setting around in the UI with valid pick and write implementations, but don't actually try to render it.
122/// TODO(settings_ui): In non-dev builds (`#[cfg(not(debug_assertions))]`) make this render as edit-in-json
123#[derive(Clone, Copy)]
124struct UnimplementedSettingField;
125
126impl PartialEq for UnimplementedSettingField {
127 fn eq(&self, _other: &Self) -> bool {
128 true
129 }
130}
131
132impl<T: 'static> SettingField<T> {
133 /// Helper for settings with types that are not yet implemented.
134 #[allow(unused)]
135 fn unimplemented(self) -> SettingField<UnimplementedSettingField> {
136 SettingField {
137 pick: |_| Some(&UnimplementedSettingField),
138 write: |_, _| unreachable!(),
139 json_path: None,
140 }
141 }
142}
143
144trait AnySettingField {
145 fn as_any(&self) -> &dyn Any;
146 fn type_name(&self) -> &'static str;
147 fn type_id(&self) -> TypeId;
148 // 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)
149 fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool);
150 fn reset_to_default_fn(
151 &self,
152 current_file: &SettingsUiFile,
153 file_set_in: &settings::SettingsFile,
154 cx: &App,
155 ) -> Option<Box<dyn Fn(&mut App)>>;
156
157 fn json_path(&self) -> Option<&'static str>;
158}
159
160impl<T: PartialEq + Clone + Send + Sync + 'static> AnySettingField for SettingField<T> {
161 fn as_any(&self) -> &dyn Any {
162 self
163 }
164
165 fn type_name(&self) -> &'static str {
166 type_name::<T>()
167 }
168
169 fn type_id(&self) -> TypeId {
170 TypeId::of::<T>()
171 }
172
173 fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool) {
174 let (file, value) = cx
175 .global::<SettingsStore>()
176 .get_value_from_file(file.to_settings(), self.pick);
177 return (file, value.is_some());
178 }
179
180 fn reset_to_default_fn(
181 &self,
182 current_file: &SettingsUiFile,
183 file_set_in: &settings::SettingsFile,
184 cx: &App,
185 ) -> Option<Box<dyn Fn(&mut App)>> {
186 if file_set_in == &settings::SettingsFile::Default {
187 return None;
188 }
189 if file_set_in != ¤t_file.to_settings() {
190 return None;
191 }
192 let this = *self;
193 let store = SettingsStore::global(cx);
194 let default_value = (this.pick)(store.raw_default_settings());
195 let is_default = store
196 .get_content_for_file(file_set_in.clone())
197 .map_or(None, this.pick)
198 == default_value;
199 if is_default {
200 return None;
201 }
202 let current_file = current_file.clone();
203
204 return Some(Box::new(move |cx| {
205 let store = SettingsStore::global(cx);
206 let default_value = (this.pick)(store.raw_default_settings());
207 let is_set_somewhere_other_than_default = store
208 .get_value_up_to_file(current_file.to_settings(), this.pick)
209 .0
210 != settings::SettingsFile::Default;
211 let value_to_set = if is_set_somewhere_other_than_default {
212 default_value.cloned()
213 } else {
214 None
215 };
216 update_settings_file(current_file.clone(), cx, move |settings, _| {
217 (this.write)(settings, value_to_set);
218 })
219 // todo(settings_ui): Don't log err
220 .log_err();
221 }));
222 }
223
224 fn json_path(&self) -> Option<&'static str> {
225 self.json_path
226 }
227}
228
229#[derive(Default, Clone)]
230struct SettingFieldRenderer {
231 renderers: Rc<
232 RefCell<
233 HashMap<
234 TypeId,
235 Box<
236 dyn Fn(
237 &SettingsWindow,
238 &SettingItem,
239 SettingsUiFile,
240 Option<&SettingsFieldMetadata>,
241 &mut Window,
242 &mut Context<SettingsWindow>,
243 ) -> Stateful<Div>,
244 >,
245 >,
246 >,
247 >,
248}
249
250impl Global for SettingFieldRenderer {}
251
252impl SettingFieldRenderer {
253 fn add_basic_renderer<T: 'static>(
254 &mut self,
255 render_control: impl Fn(
256 SettingField<T>,
257 SettingsUiFile,
258 Option<&SettingsFieldMetadata>,
259 &mut Window,
260 &mut App,
261 ) -> AnyElement
262 + 'static,
263 ) -> &mut Self {
264 self.add_renderer(
265 move |settings_window: &SettingsWindow,
266 item: &SettingItem,
267 field: SettingField<T>,
268 settings_file: SettingsUiFile,
269 metadata: Option<&SettingsFieldMetadata>,
270 window: &mut Window,
271 cx: &mut Context<SettingsWindow>| {
272 render_settings_item(
273 settings_window,
274 item,
275 settings_file.clone(),
276 render_control(field, settings_file, metadata, window, cx),
277 window,
278 cx,
279 )
280 },
281 )
282 }
283
284 fn add_renderer<T: 'static>(
285 &mut self,
286 renderer: impl Fn(
287 &SettingsWindow,
288 &SettingItem,
289 SettingField<T>,
290 SettingsUiFile,
291 Option<&SettingsFieldMetadata>,
292 &mut Window,
293 &mut Context<SettingsWindow>,
294 ) -> Stateful<Div>
295 + 'static,
296 ) -> &mut Self {
297 let key = TypeId::of::<T>();
298 let renderer = Box::new(
299 move |settings_window: &SettingsWindow,
300 item: &SettingItem,
301 settings_file: SettingsUiFile,
302 metadata: Option<&SettingsFieldMetadata>,
303 window: &mut Window,
304 cx: &mut Context<SettingsWindow>| {
305 let field = *item
306 .field
307 .as_ref()
308 .as_any()
309 .downcast_ref::<SettingField<T>>()
310 .unwrap();
311 renderer(
312 settings_window,
313 item,
314 field,
315 settings_file,
316 metadata,
317 window,
318 cx,
319 )
320 },
321 );
322 self.renderers.borrow_mut().insert(key, renderer);
323 self
324 }
325}
326
327struct NonFocusableHandle {
328 handle: FocusHandle,
329 _subscription: Subscription,
330}
331
332impl NonFocusableHandle {
333 fn new(tab_index: isize, tab_stop: bool, window: &mut Window, cx: &mut App) -> Entity<Self> {
334 let handle = cx.focus_handle().tab_index(tab_index).tab_stop(tab_stop);
335 Self::from_handle(handle, window, cx)
336 }
337
338 fn from_handle(handle: FocusHandle, window: &mut Window, cx: &mut App) -> Entity<Self> {
339 cx.new(|cx| {
340 let _subscription = cx.on_focus(&handle, window, {
341 move |_, window, _| {
342 window.focus_next();
343 }
344 });
345 Self {
346 handle,
347 _subscription,
348 }
349 })
350 }
351}
352
353impl Focusable for NonFocusableHandle {
354 fn focus_handle(&self, _: &App) -> FocusHandle {
355 self.handle.clone()
356 }
357}
358
359#[derive(Default)]
360struct SettingsFieldMetadata {
361 placeholder: Option<&'static str>,
362 should_do_titlecase: Option<bool>,
363}
364
365pub struct SettingsUiFeatureFlag;
366
367impl FeatureFlag for SettingsUiFeatureFlag {
368 const NAME: &'static str = "settings-ui";
369}
370
371pub fn init(cx: &mut App) {
372 init_renderers(cx);
373
374 cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
375 workspace.register_action(
376 |workspace, OpenSettingsAt { path }: &OpenSettingsAt, window, cx| {
377 let window_handle = window
378 .window_handle()
379 .downcast::<Workspace>()
380 .expect("Workspaces are root Windows");
381 open_settings_editor(workspace, Some(&path), window_handle, cx);
382 },
383 );
384 })
385 .detach();
386
387 cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
388 workspace.register_action(|workspace, _: &OpenSettings, window, cx| {
389 let window_handle = window
390 .window_handle()
391 .downcast::<Workspace>()
392 .expect("Workspaces are root Windows");
393 open_settings_editor(workspace, None, window_handle, cx);
394 });
395 })
396 .detach();
397}
398
399fn init_renderers(cx: &mut App) {
400 cx.default_global::<SettingFieldRenderer>()
401 .add_basic_renderer::<UnimplementedSettingField>(|_, _, _, _, _| {
402 Button::new("open-in-settings-file", "Edit in settings.json")
403 .style(ButtonStyle::Outlined)
404 .size(ButtonSize::Medium)
405 .tab_index(0_isize)
406 .on_click(|_, window, cx| {
407 window.dispatch_action(Box::new(OpenCurrentFile), cx);
408 })
409 .into_any_element()
410 })
411 .add_basic_renderer::<bool>(render_toggle_button)
412 .add_basic_renderer::<String>(render_text_field)
413 .add_basic_renderer::<SharedString>(render_text_field)
414 .add_basic_renderer::<settings::SaturatingBool>(render_toggle_button)
415 .add_basic_renderer::<settings::CursorShape>(render_dropdown)
416 .add_basic_renderer::<settings::RestoreOnStartupBehavior>(render_dropdown)
417 .add_basic_renderer::<settings::BottomDockLayout>(render_dropdown)
418 .add_basic_renderer::<settings::OnLastWindowClosed>(render_dropdown)
419 .add_basic_renderer::<settings::CloseWindowWhenNoItems>(render_dropdown)
420 .add_basic_renderer::<settings::FontFamilyName>(render_font_picker)
421 .add_basic_renderer::<settings::BaseKeymapContent>(render_dropdown)
422 .add_basic_renderer::<settings::MultiCursorModifier>(render_dropdown)
423 .add_basic_renderer::<settings::HideMouseMode>(render_dropdown)
424 .add_basic_renderer::<settings::CurrentLineHighlight>(render_dropdown)
425 .add_basic_renderer::<settings::ShowWhitespaceSetting>(render_dropdown)
426 .add_basic_renderer::<settings::SoftWrap>(render_dropdown)
427 .add_basic_renderer::<settings::ScrollBeyondLastLine>(render_dropdown)
428 .add_basic_renderer::<settings::SnippetSortOrder>(render_dropdown)
429 .add_basic_renderer::<settings::ClosePosition>(render_dropdown)
430 .add_basic_renderer::<settings::DockSide>(render_dropdown)
431 .add_basic_renderer::<settings::TerminalDockPosition>(render_dropdown)
432 .add_basic_renderer::<settings::DockPosition>(render_dropdown)
433 .add_basic_renderer::<settings::GitGutterSetting>(render_dropdown)
434 .add_basic_renderer::<settings::GitHunkStyleSetting>(render_dropdown)
435 .add_basic_renderer::<settings::DiagnosticSeverityContent>(render_dropdown)
436 .add_basic_renderer::<settings::SeedQuerySetting>(render_dropdown)
437 .add_basic_renderer::<settings::DoubleClickInMultibuffer>(render_dropdown)
438 .add_basic_renderer::<settings::GoToDefinitionFallback>(render_dropdown)
439 .add_basic_renderer::<settings::ActivateOnClose>(render_dropdown)
440 .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
441 .add_basic_renderer::<settings::ShowCloseButton>(render_dropdown)
442 .add_basic_renderer::<settings::ProjectPanelEntrySpacing>(render_dropdown)
443 .add_basic_renderer::<settings::RewrapBehavior>(render_dropdown)
444 .add_basic_renderer::<settings::FormatOnSave>(render_dropdown)
445 .add_basic_renderer::<settings::IndentGuideColoring>(render_dropdown)
446 .add_basic_renderer::<settings::IndentGuideBackgroundColoring>(render_dropdown)
447 .add_basic_renderer::<settings::FileFinderWidthContent>(render_dropdown)
448 .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
449 .add_basic_renderer::<settings::WordsCompletionMode>(render_dropdown)
450 .add_basic_renderer::<settings::LspInsertMode>(render_dropdown)
451 .add_basic_renderer::<settings::AlternateScroll>(render_dropdown)
452 .add_basic_renderer::<settings::TerminalBlink>(render_dropdown)
453 .add_basic_renderer::<settings::CursorShapeContent>(render_dropdown)
454 .add_basic_renderer::<f32>(render_number_field)
455 .add_basic_renderer::<u32>(render_number_field)
456 .add_basic_renderer::<u64>(render_number_field)
457 .add_basic_renderer::<usize>(render_number_field)
458 .add_basic_renderer::<NonZero<usize>>(render_number_field)
459 .add_basic_renderer::<NonZeroU32>(render_number_field)
460 .add_basic_renderer::<settings::CodeFade>(render_number_field)
461 .add_basic_renderer::<settings::DelayMs>(render_number_field)
462 .add_basic_renderer::<gpui::FontWeight>(render_number_field)
463 .add_basic_renderer::<settings::CenteredPaddingSettings>(render_number_field)
464 .add_basic_renderer::<settings::InactiveOpacity>(render_number_field)
465 .add_basic_renderer::<settings::MinimumContrast>(render_number_field)
466 .add_basic_renderer::<settings::ShowScrollbar>(render_dropdown)
467 .add_basic_renderer::<settings::ScrollbarDiagnostics>(render_dropdown)
468 .add_basic_renderer::<settings::ShowMinimap>(render_dropdown)
469 .add_basic_renderer::<settings::DisplayIn>(render_dropdown)
470 .add_basic_renderer::<settings::MinimapThumb>(render_dropdown)
471 .add_basic_renderer::<settings::MinimapThumbBorder>(render_dropdown)
472 .add_basic_renderer::<settings::SteppingGranularity>(render_dropdown)
473 .add_basic_renderer::<settings::NotifyWhenAgentWaiting>(render_dropdown)
474 .add_basic_renderer::<settings::NotifyWhenAgentWaiting>(render_dropdown)
475 .add_basic_renderer::<settings::ImageFileSizeUnit>(render_dropdown)
476 .add_basic_renderer::<settings::StatusStyle>(render_dropdown)
477 .add_basic_renderer::<settings::PaneSplitDirectionHorizontal>(render_dropdown)
478 .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
479 .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
480 .add_basic_renderer::<settings::DocumentColorsRenderMode>(render_dropdown)
481 .add_basic_renderer::<settings::ThemeSelectionDiscriminants>(render_dropdown)
482 .add_basic_renderer::<settings::ThemeMode>(render_dropdown)
483 .add_basic_renderer::<settings::ThemeName>(render_theme_picker)
484 .add_basic_renderer::<settings::IconThemeSelectionDiscriminants>(render_dropdown)
485 .add_basic_renderer::<settings::IconThemeName>(render_icon_theme_picker)
486 .add_basic_renderer::<settings::BufferLineHeightDiscriminants>(render_dropdown)
487 .add_basic_renderer::<settings::AutosaveSettingDiscriminants>(render_dropdown)
488 .add_basic_renderer::<settings::WorkingDirectoryDiscriminants>(render_dropdown)
489 .add_basic_renderer::<settings::MaybeDiscriminants>(render_dropdown)
490 .add_basic_renderer::<settings::IncludeIgnoredContent>(render_dropdown)
491 .add_basic_renderer::<settings::ShowIndentGuides>(render_dropdown)
492 .add_basic_renderer::<settings::ShellDiscriminants>(render_dropdown)
493 // please semicolon stay on next line
494 ;
495}
496
497pub fn open_settings_editor(
498 _workspace: &mut Workspace,
499 path: Option<&str>,
500 workspace_handle: WindowHandle<Workspace>,
501 cx: &mut App,
502) {
503 /// Assumes a settings GUI window is already open
504 fn open_path(
505 path: &str,
506 settings_window: &mut SettingsWindow,
507 window: &mut Window,
508 cx: &mut Context<SettingsWindow>,
509 ) {
510 if path.starts_with("languages.$(language)") {
511 log::error!("language-specific settings links are not currently supported");
512 return;
513 }
514
515 settings_window.search_bar.update(cx, |editor, cx| {
516 editor.set_text(format!("#{path}"), window, cx);
517 });
518 settings_window.update_matches(cx);
519 }
520
521 let existing_window = cx
522 .windows()
523 .into_iter()
524 .find_map(|window| window.downcast::<SettingsWindow>());
525
526 if let Some(existing_window) = existing_window {
527 existing_window
528 .update(cx, |settings_window, window, cx| {
529 settings_window.original_window = Some(workspace_handle);
530 window.activate_window();
531 if let Some(path) = path {
532 open_path(path, settings_window, window, cx);
533 }
534 })
535 .ok();
536 return;
537 }
538
539 // We have to defer this to get the workspace off the stack.
540
541 let path = path.map(ToOwned::to_owned);
542 cx.defer(move |cx| {
543 let current_rem_size: f32 = theme::ThemeSettings::get_global(cx).ui_font_size(cx).into();
544
545 let default_bounds = DEFAULT_ADDITIONAL_WINDOW_SIZE;
546 let default_rem_size = 16.0;
547 let scale_factor = current_rem_size / default_rem_size;
548 let scaled_bounds: gpui::Size<Pixels> = default_bounds.map(|axis| axis * scale_factor);
549
550 let app_id = ReleaseChannel::global(cx).app_id();
551 let window_decorations = match std::env::var("ZED_WINDOW_DECORATIONS") {
552 Ok(val) if val == "server" => gpui::WindowDecorations::Server,
553 Ok(val) if val == "client" => gpui::WindowDecorations::Client,
554 _ => gpui::WindowDecorations::Client,
555 };
556
557 cx.open_window(
558 WindowOptions {
559 titlebar: Some(TitlebarOptions {
560 title: Some("Zed — Settings".into()),
561 appears_transparent: true,
562 traffic_light_position: Some(point(px(12.0), px(12.0))),
563 }),
564 focus: true,
565 show: true,
566 is_movable: true,
567 kind: gpui::WindowKind::Floating,
568 window_background: cx.theme().window_background_appearance(),
569 app_id: Some(app_id.to_owned()),
570 window_decorations: Some(window_decorations),
571 window_min_size: Some(scaled_bounds),
572 window_bounds: Some(WindowBounds::centered(scaled_bounds, cx)),
573 ..Default::default()
574 },
575 |window, cx| {
576 let settings_window =
577 cx.new(|cx| SettingsWindow::new(Some(workspace_handle), window, cx));
578 settings_window.update(cx, |settings_window, cx| {
579 if let Some(path) = path {
580 open_path(&path, settings_window, window, cx);
581 }
582 });
583
584 settings_window
585 },
586 )
587 .log_err();
588 });
589}
590
591/// The current sub page path that is selected.
592/// If this is empty the selected page is rendered,
593/// otherwise the last sub page gets rendered.
594///
595/// Global so that `pick` and `write` callbacks can access it
596/// and use it to dynamically render sub pages (e.g. for language settings)
597static SUB_PAGE_STACK: LazyLock<RwLock<Vec<SubPage>>> = LazyLock::new(|| RwLock::new(Vec::new()));
598
599fn sub_page_stack() -> std::sync::RwLockReadGuard<'static, Vec<SubPage>> {
600 SUB_PAGE_STACK
601 .read()
602 .expect("SUB_PAGE_STACK is never poisoned")
603}
604
605fn sub_page_stack_mut() -> std::sync::RwLockWriteGuard<'static, Vec<SubPage>> {
606 SUB_PAGE_STACK
607 .write()
608 .expect("SUB_PAGE_STACK is never poisoned")
609}
610
611pub struct SettingsWindow {
612 title_bar: Option<Entity<PlatformTitleBar>>,
613 original_window: Option<WindowHandle<Workspace>>,
614 files: Vec<(SettingsUiFile, FocusHandle)>,
615 worktree_root_dirs: HashMap<WorktreeId, String>,
616 current_file: SettingsUiFile,
617 pages: Vec<SettingsPage>,
618 search_bar: Entity<Editor>,
619 search_task: Option<Task<()>>,
620 /// Index into navbar_entries
621 navbar_entry: usize,
622 navbar_entries: Vec<NavBarEntry>,
623 navbar_scroll_handle: UniformListScrollHandle,
624 /// [page_index][page_item_index] will be false
625 /// when the item is filtered out either by searches
626 /// or by the current file
627 navbar_focus_subscriptions: Vec<gpui::Subscription>,
628 filter_table: Vec<Vec<bool>>,
629 has_query: bool,
630 content_handles: Vec<Vec<Entity<NonFocusableHandle>>>,
631 sub_page_scroll_handle: ScrollHandle,
632 focus_handle: FocusHandle,
633 navbar_focus_handle: Entity<NonFocusableHandle>,
634 content_focus_handle: Entity<NonFocusableHandle>,
635 files_focus_handle: FocusHandle,
636 search_index: Option<Arc<SearchIndex>>,
637 list_state: ListState,
638}
639
640struct SearchIndex {
641 bm25_engine: bm25::SearchEngine<usize>,
642 fuzzy_match_candidates: Vec<StringMatchCandidate>,
643 key_lut: Vec<SearchKeyLUTEntry>,
644}
645
646struct SearchKeyLUTEntry {
647 page_index: usize,
648 header_index: usize,
649 item_index: usize,
650 json_path: Option<&'static str>,
651}
652
653struct SubPage {
654 link: SubPageLink,
655 section_header: &'static str,
656}
657
658#[derive(Debug)]
659struct NavBarEntry {
660 title: &'static str,
661 is_root: bool,
662 expanded: bool,
663 page_index: usize,
664 item_index: Option<usize>,
665 focus_handle: FocusHandle,
666}
667
668struct SettingsPage {
669 title: &'static str,
670 items: Vec<SettingsPageItem>,
671}
672
673#[derive(PartialEq)]
674enum SettingsPageItem {
675 SectionHeader(&'static str),
676 SettingItem(SettingItem),
677 SubPageLink(SubPageLink),
678 DynamicItem(DynamicItem),
679}
680
681impl std::fmt::Debug for SettingsPageItem {
682 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
683 match self {
684 SettingsPageItem::SectionHeader(header) => write!(f, "SectionHeader({})", header),
685 SettingsPageItem::SettingItem(setting_item) => {
686 write!(f, "SettingItem({})", setting_item.title)
687 }
688 SettingsPageItem::SubPageLink(sub_page_link) => {
689 write!(f, "SubPageLink({})", sub_page_link.title)
690 }
691 SettingsPageItem::DynamicItem(dynamic_item) => {
692 write!(f, "DynamicItem({})", dynamic_item.discriminant.title)
693 }
694 }
695 }
696}
697
698impl SettingsPageItem {
699 fn render(
700 &self,
701 settings_window: &SettingsWindow,
702 item_index: usize,
703 is_last: bool,
704 window: &mut Window,
705 cx: &mut Context<SettingsWindow>,
706 ) -> AnyElement {
707 let file = settings_window.current_file.clone();
708
709 let border_variant = cx.theme().colors().border_variant;
710 let apply_padding = |element: Stateful<Div>| -> Stateful<Div> {
711 let element = element.pt_4();
712 if is_last {
713 element.pb_10()
714 } else {
715 element.pb_4().border_b_1().border_color(border_variant)
716 }
717 };
718
719 let mut render_setting_item_inner =
720 |setting_item: &SettingItem, padding: bool, cx: &mut Context<SettingsWindow>| {
721 let renderer = cx.default_global::<SettingFieldRenderer>().clone();
722 let (_, found) = setting_item.field.file_set_in(file.clone(), cx);
723
724 let renderers = renderer.renderers.borrow();
725
726 let field_renderer =
727 renderers.get(&AnySettingField::type_id(setting_item.field.as_ref()));
728 let field_renderer_or_warning =
729 field_renderer.ok_or("NO RENDERER").and_then(|renderer| {
730 if cfg!(debug_assertions) && !found {
731 Err("NO DEFAULT")
732 } else {
733 Ok(renderer)
734 }
735 });
736
737 let field = match field_renderer_or_warning {
738 Ok(field_renderer) => window.with_id(item_index, |window| {
739 field_renderer(
740 settings_window,
741 setting_item,
742 file.clone(),
743 setting_item.metadata.as_deref(),
744 window,
745 cx,
746 )
747 }),
748 Err(warning) => render_settings_item(
749 settings_window,
750 setting_item,
751 file.clone(),
752 Button::new("error-warning", warning)
753 .style(ButtonStyle::Outlined)
754 .size(ButtonSize::Medium)
755 .icon(Some(IconName::Debug))
756 .icon_position(IconPosition::Start)
757 .icon_color(Color::Error)
758 .tab_index(0_isize)
759 .tooltip(Tooltip::text(setting_item.field.type_name()))
760 .into_any_element(),
761 window,
762 cx,
763 ),
764 };
765
766 let field = if padding {
767 field.map(apply_padding)
768 } else {
769 field
770 };
771
772 (field, field_renderer_or_warning.is_ok())
773 };
774
775 match self {
776 SettingsPageItem::SectionHeader(header) => v_flex()
777 .w_full()
778 .gap_1p5()
779 .child(
780 Label::new(SharedString::new_static(header))
781 .size(LabelSize::Small)
782 .color(Color::Muted)
783 .buffer_font(cx),
784 )
785 .child(Divider::horizontal().color(DividerColor::BorderFaded))
786 .into_any_element(),
787 SettingsPageItem::SettingItem(setting_item) => {
788 let (field_with_padding, _) = render_setting_item_inner(setting_item, true, cx);
789 field_with_padding.into_any_element()
790 }
791 SettingsPageItem::SubPageLink(sub_page_link) => h_flex()
792 .id(sub_page_link.title.clone())
793 .w_full()
794 .min_w_0()
795 .justify_between()
796 .map(apply_padding)
797 .child(
798 v_flex()
799 .w_full()
800 .max_w_1_2()
801 .child(Label::new(sub_page_link.title.clone())),
802 )
803 .child(
804 Button::new(
805 ("sub-page".into(), sub_page_link.title.clone()),
806 "Configure",
807 )
808 .icon(IconName::ChevronRight)
809 .tab_index(0_isize)
810 .icon_position(IconPosition::End)
811 .icon_color(Color::Muted)
812 .icon_size(IconSize::Small)
813 .style(ButtonStyle::OutlinedGhost)
814 .size(ButtonSize::Medium)
815 .on_click({
816 let sub_page_link = sub_page_link.clone();
817 cx.listener(move |this, _, _, cx| {
818 let mut section_index = item_index;
819 let current_page = this.current_page();
820
821 while !matches!(
822 current_page.items[section_index],
823 SettingsPageItem::SectionHeader(_)
824 ) {
825 section_index -= 1;
826 }
827
828 let SettingsPageItem::SectionHeader(header) =
829 current_page.items[section_index]
830 else {
831 unreachable!("All items always have a section header above them")
832 };
833
834 this.push_sub_page(sub_page_link.clone(), header, cx)
835 })
836 }),
837 )
838 .into_any_element(),
839 SettingsPageItem::DynamicItem(DynamicItem {
840 discriminant: discriminant_setting_item,
841 pick_discriminant,
842 fields,
843 }) => {
844 let file = file.to_settings();
845 let discriminant = SettingsStore::global(cx)
846 .get_value_from_file(file, *pick_discriminant)
847 .1;
848
849 let (discriminant_element, rendered_ok) =
850 render_setting_item_inner(discriminant_setting_item, true, cx);
851
852 let has_sub_fields =
853 rendered_ok && discriminant.map(|d| !fields[d].is_empty()).unwrap_or(false);
854
855 let discriminant_element = if has_sub_fields {
856 discriminant_element.pb_4().border_b_0()
857 } else {
858 discriminant_element
859 };
860
861 let mut content = v_flex().id("dynamic-item").child(discriminant_element);
862
863 if rendered_ok {
864 let discriminant =
865 discriminant.expect("This should be Some if rendered_ok is true");
866 let sub_fields = &fields[discriminant];
867 let sub_field_count = sub_fields.len();
868
869 for (index, field) in sub_fields.iter().enumerate() {
870 let is_last_sub_field = index == sub_field_count - 1;
871 let (raw_field, _) = render_setting_item_inner(field, false, cx);
872
873 content = content.child(
874 raw_field
875 .p_4()
876 .border_x_1()
877 .border_t_1()
878 .when(is_last_sub_field, |this| this.border_b_1())
879 .when(is_last_sub_field && is_last, |this| this.mb_8())
880 .border_dashed()
881 .border_color(cx.theme().colors().border_variant)
882 .bg(cx.theme().colors().element_background.opacity(0.2)),
883 );
884 }
885 }
886
887 return content.into_any_element();
888 }
889 }
890 }
891}
892
893fn render_settings_item(
894 settings_window: &SettingsWindow,
895 setting_item: &SettingItem,
896 file: SettingsUiFile,
897 control: AnyElement,
898 _window: &mut Window,
899 cx: &mut Context<'_, SettingsWindow>,
900) -> Stateful<Div> {
901 let (found_in_file, _) = setting_item.field.file_set_in(file.clone(), cx);
902 let file_set_in = SettingsUiFile::from_settings(found_in_file.clone());
903
904 let clipboard_has_link = cx
905 .read_from_clipboard()
906 .and_then(|entry| entry.text())
907 .map_or(false, |maybe_url| {
908 maybe_url.strip_prefix("zed://settings/") == setting_item.field.json_path()
909 });
910 let (link_icon, link_icon_color) = if clipboard_has_link {
911 (IconName::Check, Color::Success)
912 } else {
913 (IconName::Hash, Color::Muted)
914 };
915
916 h_flex()
917 .id(setting_item.title)
918
919 .relative()
920 .min_w_0()
921 .justify_between()
922 .child(
923 v_flex()
924 .w_1_2()
925 .group("setting-item")
926 .child(
927 h_flex()
928 .w_full()
929 .gap_1()
930 .ml_neg_8()
931 // .group_hover("setting-item", |s| s.gap_10())
932 .child(
933 IconButton::new("copy-link-btn", link_icon)
934 .icon_color(link_icon_color)
935 .icon_size(IconSize::Small)
936 .shape(IconButtonShape::Square)
937 .tooltip(Tooltip::text("Copy Link"))
938 .when_some(setting_item.field.json_path(), |this, path| {
939 this.on_click(cx.listener(move |_, _, _, cx| {
940 let link = format!("zed://settings/{}", path);
941 cx.write_to_clipboard(ClipboardItem::new_string(link));
942 cx.notify();
943 }))
944 })
945)
946 .child(Label::new(SharedString::new_static(setting_item.title)))
947 .when_some(
948 setting_item
949 .field
950 .reset_to_default_fn(&file, &found_in_file, cx),
951 |this, reset_to_default| {
952 this.child(
953 IconButton::new("reset-to-default-btn", IconName::Undo)
954 .icon_color(Color::Muted)
955 .icon_size(IconSize::Small)
956 .tooltip(Tooltip::text("Reset to Default"))
957 .on_click({
958 move |_, _, cx| {
959 reset_to_default(cx);
960 }
961 }),
962 )
963 },
964 )
965 .when_some(
966 file_set_in.filter(|file_set_in| file_set_in != &file),
967 |this, file_set_in| {
968 this.child(
969 Label::new(format!(
970 "— Modified in {}",
971 settings_window
972 .display_name(&file_set_in)
973 .expect("File name should exist")
974 ))
975 .color(Color::Muted)
976 .size(LabelSize::Small),
977 )
978 },
979 ),
980 )
981 .child(
982 Label::new(SharedString::new_static(setting_item.description))
983 .size(LabelSize::Small)
984 .color(Color::Muted),
985 ),
986 )
987 .child(control)
988 // .when(sub_page_stack().is_empty(), |this| {
989 // this.child(
990 // div()
991 // .visible_on_hover("setting-item")
992 // .absolute()
993 // .top_0()
994 // .left_neg_5(
995 // )
996 // .child({
997 // IconButton::new("copy-link-btn", link_icon)
998 // .icon_color(link_icon_color)
999 // .icon_size(IconSize::Small)
1000 // .shape(IconButtonShape::Square)
1001 // .tooltip(Tooltip::text("Copy Link"))
1002 // .when_some(
1003 // setting_item.field.json_path(),
1004 // |this, path| {
1005 // this.on_click(cx.listener(
1006 // move |_, _, _, cx| {
1007 // let link =
1008 // format!("zed://settings/{}", path);
1009 // cx.write_to_clipboard(
1010 // ClipboardItem::new_string(link),
1011 // );
1012 // cx.notify();
1013 // },
1014 // ))
1015 // },
1016 // )
1017 // }),
1018 // )
1019 // })
1020}
1021
1022struct SettingItem {
1023 title: &'static str,
1024 description: &'static str,
1025 field: Box<dyn AnySettingField>,
1026 metadata: Option<Box<SettingsFieldMetadata>>,
1027 files: FileMask,
1028}
1029
1030struct DynamicItem {
1031 discriminant: SettingItem,
1032 pick_discriminant: fn(&SettingsContent) -> Option<usize>,
1033 fields: Vec<Vec<SettingItem>>,
1034}
1035
1036impl PartialEq for DynamicItem {
1037 fn eq(&self, other: &Self) -> bool {
1038 self.discriminant == other.discriminant && self.fields == other.fields
1039 }
1040}
1041
1042#[derive(PartialEq, Eq, Clone, Copy)]
1043struct FileMask(u8);
1044
1045impl std::fmt::Debug for FileMask {
1046 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1047 write!(f, "FileMask(")?;
1048 let mut items = vec![];
1049
1050 if self.contains(USER) {
1051 items.push("USER");
1052 }
1053 if self.contains(PROJECT) {
1054 items.push("LOCAL");
1055 }
1056 if self.contains(SERVER) {
1057 items.push("SERVER");
1058 }
1059
1060 write!(f, "{})", items.join(" | "))
1061 }
1062}
1063
1064const USER: FileMask = FileMask(1 << 0);
1065const PROJECT: FileMask = FileMask(1 << 2);
1066const SERVER: FileMask = FileMask(1 << 3);
1067
1068impl std::ops::BitAnd for FileMask {
1069 type Output = Self;
1070
1071 fn bitand(self, other: Self) -> Self {
1072 Self(self.0 & other.0)
1073 }
1074}
1075
1076impl std::ops::BitOr for FileMask {
1077 type Output = Self;
1078
1079 fn bitor(self, other: Self) -> Self {
1080 Self(self.0 | other.0)
1081 }
1082}
1083
1084impl FileMask {
1085 fn contains(&self, other: FileMask) -> bool {
1086 self.0 & other.0 != 0
1087 }
1088}
1089
1090impl PartialEq for SettingItem {
1091 fn eq(&self, other: &Self) -> bool {
1092 self.title == other.title
1093 && self.description == other.description
1094 && (match (&self.metadata, &other.metadata) {
1095 (None, None) => true,
1096 (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
1097 _ => false,
1098 })
1099 }
1100}
1101
1102#[derive(Clone)]
1103struct SubPageLink {
1104 title: SharedString,
1105 files: FileMask,
1106 render: Arc<
1107 dyn Fn(&mut SettingsWindow, &mut Window, &mut Context<SettingsWindow>) -> AnyElement
1108 + 'static
1109 + Send
1110 + Sync,
1111 >,
1112}
1113
1114impl PartialEq for SubPageLink {
1115 fn eq(&self, other: &Self) -> bool {
1116 self.title == other.title
1117 }
1118}
1119
1120fn all_language_names(cx: &App) -> Vec<SharedString> {
1121 workspace::AppState::global(cx)
1122 .upgrade()
1123 .map_or(vec![], |state| {
1124 state
1125 .languages
1126 .language_names()
1127 .into_iter()
1128 .filter(|name| name.as_ref() != "Zed Keybind Context")
1129 .map(Into::into)
1130 .collect()
1131 })
1132}
1133
1134#[allow(unused)]
1135#[derive(Clone, PartialEq)]
1136enum SettingsUiFile {
1137 User, // Uses all settings.
1138 Project((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
1139 Server(&'static str), // Uses a special name, and the user settings
1140}
1141
1142impl SettingsUiFile {
1143 fn is_server(&self) -> bool {
1144 matches!(self, SettingsUiFile::Server(_))
1145 }
1146
1147 fn worktree_id(&self) -> Option<WorktreeId> {
1148 match self {
1149 SettingsUiFile::User => None,
1150 SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
1151 SettingsUiFile::Server(_) => None,
1152 }
1153 }
1154
1155 fn from_settings(file: settings::SettingsFile) -> Option<Self> {
1156 Some(match file {
1157 settings::SettingsFile::User => SettingsUiFile::User,
1158 settings::SettingsFile::Project(location) => SettingsUiFile::Project(location),
1159 settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
1160 settings::SettingsFile::Default => return None,
1161 })
1162 }
1163
1164 fn to_settings(&self) -> settings::SettingsFile {
1165 match self {
1166 SettingsUiFile::User => settings::SettingsFile::User,
1167 SettingsUiFile::Project(location) => settings::SettingsFile::Project(location.clone()),
1168 SettingsUiFile::Server(_) => settings::SettingsFile::Server,
1169 }
1170 }
1171
1172 fn mask(&self) -> FileMask {
1173 match self {
1174 SettingsUiFile::User => USER,
1175 SettingsUiFile::Project(_) => PROJECT,
1176 SettingsUiFile::Server(_) => SERVER,
1177 }
1178 }
1179}
1180
1181impl SettingsWindow {
1182 fn new(
1183 original_window: Option<WindowHandle<Workspace>>,
1184 window: &mut Window,
1185 cx: &mut Context<Self>,
1186 ) -> Self {
1187 let font_family_cache = theme::FontFamilyCache::global(cx);
1188
1189 cx.spawn(async move |this, cx| {
1190 font_family_cache.prefetch(cx).await;
1191 this.update(cx, |_, cx| {
1192 cx.notify();
1193 })
1194 })
1195 .detach();
1196
1197 let current_file = SettingsUiFile::User;
1198 let search_bar = cx.new(|cx| {
1199 let mut editor = Editor::single_line(window, cx);
1200 editor.set_placeholder_text("Search settings…", window, cx);
1201 editor
1202 });
1203
1204 cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
1205 let EditorEvent::Edited { transaction_id: _ } = event else {
1206 return;
1207 };
1208
1209 this.update_matches(cx);
1210 })
1211 .detach();
1212
1213 cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
1214 this.fetch_files(window, cx);
1215 cx.notify();
1216 })
1217 .detach();
1218
1219 cx.on_window_closed(|cx| {
1220 if let Some(existing_window) = cx
1221 .windows()
1222 .into_iter()
1223 .find_map(|window| window.downcast::<SettingsWindow>())
1224 && cx.windows().len() == 1
1225 {
1226 cx.update_window(*existing_window, |_, window, _| {
1227 window.remove_window();
1228 })
1229 .ok();
1230 }
1231 })
1232 .detach();
1233
1234 if let Some(app_state) = AppState::global(cx).upgrade() {
1235 for project in app_state
1236 .workspace_store
1237 .read(cx)
1238 .workspaces()
1239 .iter()
1240 .filter_map(|space| {
1241 space
1242 .read(cx)
1243 .ok()
1244 .map(|workspace| workspace.project().clone())
1245 })
1246 .collect::<Vec<_>>()
1247 {
1248 cx.subscribe_in(&project, window, Self::handle_project_event)
1249 .detach();
1250 }
1251 } else {
1252 log::error!("App state doesn't exist when creating a new settings window");
1253 }
1254
1255 let this_weak = cx.weak_entity();
1256 cx.observe_new::<Project>({
1257 move |_, window, cx| {
1258 let project = cx.entity();
1259 let Some(window) = window else {
1260 return;
1261 };
1262
1263 this_weak
1264 .update(cx, |_, cx| {
1265 cx.subscribe_in(&project, window, Self::handle_project_event)
1266 .detach();
1267 })
1268 .ok();
1269 }
1270 })
1271 .detach();
1272
1273 let title_bar = if !cfg!(target_os = "macos") {
1274 Some(cx.new(|cx| PlatformTitleBar::new("settings-title-bar", cx)))
1275 } else {
1276 None
1277 };
1278
1279 // high overdraw value so the list scrollbar len doesn't change too much
1280 let list_state = gpui::ListState::new(0, gpui::ListAlignment::Top, px(0.0)).measure_all();
1281 list_state.set_scroll_handler(|_, _, _| {});
1282
1283 let mut this = Self {
1284 title_bar,
1285 original_window,
1286
1287 worktree_root_dirs: HashMap::default(),
1288 files: vec![],
1289
1290 current_file: current_file,
1291 pages: vec![],
1292 navbar_entries: vec![],
1293 navbar_entry: 0,
1294 navbar_scroll_handle: UniformListScrollHandle::default(),
1295 search_bar,
1296 search_task: None,
1297 filter_table: vec![],
1298 has_query: false,
1299 content_handles: vec![],
1300 sub_page_scroll_handle: ScrollHandle::new(),
1301 focus_handle: cx.focus_handle(),
1302 navbar_focus_handle: NonFocusableHandle::new(
1303 NAVBAR_CONTAINER_TAB_INDEX,
1304 false,
1305 window,
1306 cx,
1307 ),
1308 navbar_focus_subscriptions: vec![],
1309 content_focus_handle: NonFocusableHandle::new(
1310 CONTENT_CONTAINER_TAB_INDEX,
1311 false,
1312 window,
1313 cx,
1314 ),
1315 files_focus_handle: cx
1316 .focus_handle()
1317 .tab_index(HEADER_CONTAINER_TAB_INDEX)
1318 .tab_stop(false),
1319 search_index: None,
1320 list_state,
1321 };
1322
1323 this.fetch_files(window, cx);
1324 this.build_ui(window, cx);
1325 this.build_search_index();
1326
1327 this.search_bar.update(cx, |editor, cx| {
1328 editor.focus_handle(cx).focus(window);
1329 });
1330
1331 this
1332 }
1333
1334 fn handle_project_event(
1335 &mut self,
1336 _: &Entity<Project>,
1337 event: &project::Event,
1338 window: &mut Window,
1339 cx: &mut Context<SettingsWindow>,
1340 ) {
1341 match event {
1342 project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded(_) => {
1343 cx.defer_in(window, |this, window, cx| {
1344 this.fetch_files(window, cx);
1345 });
1346 }
1347 _ => {}
1348 }
1349 }
1350
1351 fn toggle_navbar_entry(&mut self, nav_entry_index: usize) {
1352 // We can only toggle root entries
1353 if !self.navbar_entries[nav_entry_index].is_root {
1354 return;
1355 }
1356
1357 let expanded = &mut self.navbar_entries[nav_entry_index].expanded;
1358 *expanded = !*expanded;
1359 self.navbar_entry = nav_entry_index;
1360 self.reset_list_state();
1361 }
1362
1363 fn build_navbar(&mut self, cx: &App) {
1364 let mut navbar_entries = Vec::new();
1365
1366 for (page_index, page) in self.pages.iter().enumerate() {
1367 navbar_entries.push(NavBarEntry {
1368 title: page.title,
1369 is_root: true,
1370 expanded: false,
1371 page_index,
1372 item_index: None,
1373 focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1374 });
1375
1376 for (item_index, item) in page.items.iter().enumerate() {
1377 let SettingsPageItem::SectionHeader(title) = item else {
1378 continue;
1379 };
1380 navbar_entries.push(NavBarEntry {
1381 title,
1382 is_root: false,
1383 expanded: false,
1384 page_index,
1385 item_index: Some(item_index),
1386 focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1387 });
1388 }
1389 }
1390
1391 self.navbar_entries = navbar_entries;
1392 }
1393
1394 fn setup_navbar_focus_subscriptions(
1395 &mut self,
1396 window: &mut Window,
1397 cx: &mut Context<SettingsWindow>,
1398 ) {
1399 let mut focus_subscriptions = Vec::new();
1400
1401 for entry_index in 0..self.navbar_entries.len() {
1402 let focus_handle = self.navbar_entries[entry_index].focus_handle.clone();
1403
1404 let subscription = cx.on_focus(
1405 &focus_handle,
1406 window,
1407 move |this: &mut SettingsWindow,
1408 window: &mut Window,
1409 cx: &mut Context<SettingsWindow>| {
1410 this.open_and_scroll_to_navbar_entry(entry_index, None, false, window, cx);
1411 },
1412 );
1413 focus_subscriptions.push(subscription);
1414 }
1415 self.navbar_focus_subscriptions = focus_subscriptions;
1416 }
1417
1418 fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
1419 let mut index = 0;
1420 let entries = &self.navbar_entries;
1421 let search_matches = &self.filter_table;
1422 let has_query = self.has_query;
1423 std::iter::from_fn(move || {
1424 while index < entries.len() {
1425 let entry = &entries[index];
1426 let included_in_search = if let Some(item_index) = entry.item_index {
1427 search_matches[entry.page_index][item_index]
1428 } else {
1429 search_matches[entry.page_index].iter().any(|b| *b)
1430 || search_matches[entry.page_index].is_empty()
1431 };
1432 if included_in_search {
1433 break;
1434 }
1435 index += 1;
1436 }
1437 if index >= self.navbar_entries.len() {
1438 return None;
1439 }
1440 let entry = &entries[index];
1441 let entry_index = index;
1442
1443 index += 1;
1444 if entry.is_root && !entry.expanded && !has_query {
1445 while index < entries.len() {
1446 if entries[index].is_root {
1447 break;
1448 }
1449 index += 1;
1450 }
1451 }
1452
1453 return Some((entry_index, entry));
1454 })
1455 }
1456
1457 fn filter_matches_to_file(&mut self) {
1458 let current_file = self.current_file.mask();
1459 for (page, page_filter) in std::iter::zip(&self.pages, &mut self.filter_table) {
1460 let mut header_index = 0;
1461 let mut any_found_since_last_header = true;
1462
1463 for (index, item) in page.items.iter().enumerate() {
1464 match item {
1465 SettingsPageItem::SectionHeader(_) => {
1466 if !any_found_since_last_header {
1467 page_filter[header_index] = false;
1468 }
1469 header_index = index;
1470 any_found_since_last_header = false;
1471 }
1472 SettingsPageItem::SettingItem(SettingItem { files, .. })
1473 | SettingsPageItem::SubPageLink(SubPageLink { files, .. })
1474 | SettingsPageItem::DynamicItem(DynamicItem {
1475 discriminant: SettingItem { files, .. },
1476 ..
1477 }) => {
1478 if !files.contains(current_file) {
1479 page_filter[index] = false;
1480 } else {
1481 any_found_since_last_header = true;
1482 }
1483 }
1484 }
1485 }
1486 if let Some(last_header) = page_filter.get_mut(header_index)
1487 && !any_found_since_last_header
1488 {
1489 *last_header = false;
1490 }
1491 }
1492 }
1493
1494 fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
1495 self.search_task.take();
1496 let mut query = self.search_bar.read(cx).text(cx);
1497 if query.is_empty() || self.search_index.is_none() {
1498 for page in &mut self.filter_table {
1499 page.fill(true);
1500 }
1501 self.has_query = false;
1502 self.filter_matches_to_file();
1503 self.reset_list_state();
1504 cx.notify();
1505 return;
1506 }
1507
1508 let is_json_link_query;
1509 if query.starts_with("#") {
1510 query.remove(0);
1511 is_json_link_query = true;
1512 } else {
1513 is_json_link_query = false;
1514 }
1515
1516 let search_index = self.search_index.as_ref().unwrap().clone();
1517
1518 fn update_matches_inner(
1519 this: &mut SettingsWindow,
1520 search_index: &SearchIndex,
1521 match_indices: impl Iterator<Item = usize>,
1522 cx: &mut Context<SettingsWindow>,
1523 ) {
1524 for page in &mut this.filter_table {
1525 page.fill(false);
1526 }
1527
1528 for match_index in match_indices {
1529 let SearchKeyLUTEntry {
1530 page_index,
1531 header_index,
1532 item_index,
1533 ..
1534 } = search_index.key_lut[match_index];
1535 let page = &mut this.filter_table[page_index];
1536 page[header_index] = true;
1537 page[item_index] = true;
1538 }
1539 this.has_query = true;
1540 this.filter_matches_to_file();
1541 this.open_first_nav_page();
1542 this.reset_list_state();
1543 cx.notify();
1544 }
1545
1546 self.search_task = Some(cx.spawn(async move |this, cx| {
1547 if is_json_link_query {
1548 let mut indices = vec![];
1549 for (index, SearchKeyLUTEntry { json_path, .. }) in
1550 search_index.key_lut.iter().enumerate()
1551 {
1552 let Some(json_path) = json_path else {
1553 continue;
1554 };
1555
1556 if let Some(post) = query.strip_prefix(json_path)
1557 && (post.is_empty() || post.starts_with('.'))
1558 {
1559 indices.push(index);
1560 }
1561 }
1562 if !indices.is_empty() {
1563 this.update(cx, |this, cx| {
1564 update_matches_inner(this, search_index.as_ref(), indices.into_iter(), cx);
1565 })
1566 .ok();
1567 return;
1568 }
1569 }
1570 let bm25_task = cx.background_spawn({
1571 let search_index = search_index.clone();
1572 let max_results = search_index.key_lut.len();
1573 let query = query.clone();
1574 async move { search_index.bm25_engine.search(&query, max_results) }
1575 });
1576 let cancel_flag = std::sync::atomic::AtomicBool::new(false);
1577 let fuzzy_search_task = fuzzy::match_strings(
1578 search_index.fuzzy_match_candidates.as_slice(),
1579 &query,
1580 false,
1581 true,
1582 search_index.fuzzy_match_candidates.len(),
1583 &cancel_flag,
1584 cx.background_executor().clone(),
1585 );
1586
1587 let fuzzy_matches = fuzzy_search_task.await;
1588
1589 _ = this
1590 .update(cx, |this, cx| {
1591 // For tuning the score threshold
1592 // for fuzzy_match in &fuzzy_matches {
1593 // let SearchItemKey {
1594 // page_index,
1595 // header_index,
1596 // item_index,
1597 // } = search_index.key_lut[fuzzy_match.candidate_id];
1598 // let SettingsPageItem::SectionHeader(header) =
1599 // this.pages[page_index].items[header_index]
1600 // else {
1601 // continue;
1602 // };
1603 // let SettingsPageItem::SettingItem(SettingItem {
1604 // title, description, ..
1605 // }) = this.pages[page_index].items[item_index]
1606 // else {
1607 // continue;
1608 // };
1609 // let score = fuzzy_match.score;
1610 // eprint!("# {header} :: QUERY = {query} :: SCORE = {score}\n{title}\n{description}\n\n");
1611 // }
1612 update_matches_inner(
1613 this,
1614 search_index.as_ref(),
1615 fuzzy_matches
1616 .into_iter()
1617 // MAGIC NUMBER: Was found to have right balance between not too many weird matches, but also
1618 // flexible enough to catch misspellings and <4 letter queries
1619 // More flexible is good for us here because fuzzy matches will only be used for things that don't
1620 // match using bm25
1621 .take_while(|fuzzy_match| fuzzy_match.score >= 0.3)
1622 .map(|fuzzy_match| fuzzy_match.candidate_id),
1623 cx,
1624 );
1625 })
1626 .ok();
1627
1628 let bm25_matches = bm25_task.await;
1629
1630 _ = this
1631 .update(cx, |this, cx| {
1632 if bm25_matches.is_empty() {
1633 return;
1634 }
1635 update_matches_inner(
1636 this,
1637 search_index.as_ref(),
1638 bm25_matches
1639 .into_iter()
1640 .map(|bm25_match| bm25_match.document.id),
1641 cx,
1642 );
1643 })
1644 .ok();
1645 }));
1646 }
1647
1648 fn build_filter_table(&mut self) {
1649 self.filter_table = self
1650 .pages
1651 .iter()
1652 .map(|page| vec![true; page.items.len()])
1653 .collect::<Vec<_>>();
1654 }
1655
1656 fn build_search_index(&mut self) {
1657 let mut key_lut: Vec<SearchKeyLUTEntry> = vec![];
1658 let mut documents = Vec::default();
1659 let mut fuzzy_match_candidates = Vec::default();
1660
1661 fn push_candidates(
1662 fuzzy_match_candidates: &mut Vec<StringMatchCandidate>,
1663 key_index: usize,
1664 input: &str,
1665 ) {
1666 for word in input.split_ascii_whitespace() {
1667 fuzzy_match_candidates.push(StringMatchCandidate::new(key_index, word));
1668 }
1669 }
1670
1671 // PERF: We are currently searching all items even in project files
1672 // where many settings are filtered out, using the logic in filter_matches_to_file
1673 // we could only search relevant items based on the current file
1674 for (page_index, page) in self.pages.iter().enumerate() {
1675 let mut header_index = 0;
1676 let mut header_str = "";
1677 for (item_index, item) in page.items.iter().enumerate() {
1678 let key_index = key_lut.len();
1679 let mut json_path = None;
1680 match item {
1681 SettingsPageItem::DynamicItem(DynamicItem {
1682 discriminant: item, ..
1683 })
1684 | SettingsPageItem::SettingItem(item) => {
1685 json_path = item
1686 .field
1687 .json_path()
1688 .map(|path| path.trim_end_matches('$'));
1689 documents.push(bm25::Document {
1690 id: key_index,
1691 contents: [page.title, header_str, item.title, item.description]
1692 .join("\n"),
1693 });
1694 push_candidates(&mut fuzzy_match_candidates, key_index, item.title);
1695 push_candidates(&mut fuzzy_match_candidates, key_index, item.description);
1696 }
1697 SettingsPageItem::SectionHeader(header) => {
1698 documents.push(bm25::Document {
1699 id: key_index,
1700 contents: header.to_string(),
1701 });
1702 push_candidates(&mut fuzzy_match_candidates, key_index, header);
1703 header_index = item_index;
1704 header_str = *header;
1705 }
1706 SettingsPageItem::SubPageLink(sub_page_link) => {
1707 documents.push(bm25::Document {
1708 id: key_index,
1709 contents: [page.title, header_str, sub_page_link.title.as_ref()]
1710 .join("\n"),
1711 });
1712 push_candidates(
1713 &mut fuzzy_match_candidates,
1714 key_index,
1715 sub_page_link.title.as_ref(),
1716 );
1717 }
1718 }
1719 push_candidates(&mut fuzzy_match_candidates, key_index, page.title);
1720 push_candidates(&mut fuzzy_match_candidates, key_index, header_str);
1721
1722 key_lut.push(SearchKeyLUTEntry {
1723 page_index,
1724 header_index,
1725 item_index,
1726 json_path,
1727 });
1728 }
1729 }
1730 let engine =
1731 bm25::SearchEngineBuilder::with_documents(bm25::Language::English, documents).build();
1732 self.search_index = Some(Arc::new(SearchIndex {
1733 bm25_engine: engine,
1734 key_lut,
1735 fuzzy_match_candidates,
1736 }));
1737 }
1738
1739 fn build_content_handles(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1740 self.content_handles = self
1741 .pages
1742 .iter()
1743 .map(|page| {
1744 std::iter::repeat_with(|| NonFocusableHandle::new(0, false, window, cx))
1745 .take(page.items.len())
1746 .collect()
1747 })
1748 .collect::<Vec<_>>();
1749 }
1750
1751 fn reset_list_state(&mut self) {
1752 // plus one for the title
1753 let mut visible_items_count = self.visible_page_items().count();
1754
1755 if visible_items_count > 0 {
1756 // show page title if page is non empty
1757 visible_items_count += 1;
1758 }
1759
1760 self.list_state.reset(visible_items_count);
1761 }
1762
1763 fn build_ui(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1764 if self.pages.is_empty() {
1765 self.pages = page_data::settings_data(cx);
1766 self.build_navbar(cx);
1767 self.setup_navbar_focus_subscriptions(window, cx);
1768 self.build_content_handles(window, cx);
1769 }
1770 sub_page_stack_mut().clear();
1771 // PERF: doesn't have to be rebuilt, can just be filled with true. pages is constant once it is built
1772 self.build_filter_table();
1773 self.reset_list_state();
1774 self.update_matches(cx);
1775
1776 cx.notify();
1777 }
1778
1779 fn fetch_files(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1780 self.worktree_root_dirs.clear();
1781 let prev_files = self.files.clone();
1782 let settings_store = cx.global::<SettingsStore>();
1783 let mut ui_files = vec![];
1784 let all_files = settings_store.get_all_files();
1785 for file in all_files {
1786 let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
1787 continue;
1788 };
1789 if settings_ui_file.is_server() {
1790 continue;
1791 }
1792
1793 if let Some(worktree_id) = settings_ui_file.worktree_id() {
1794 let directory_name = all_projects(cx)
1795 .find_map(|project| project.read(cx).worktree_for_id(worktree_id, cx))
1796 .and_then(|worktree| worktree.read(cx).root_dir())
1797 .and_then(|root_dir| {
1798 root_dir
1799 .file_name()
1800 .map(|os_string| os_string.to_string_lossy().to_string())
1801 });
1802
1803 let Some(directory_name) = directory_name else {
1804 log::error!(
1805 "No directory name found for settings file at worktree ID: {}",
1806 worktree_id
1807 );
1808 continue;
1809 };
1810
1811 self.worktree_root_dirs.insert(worktree_id, directory_name);
1812 }
1813
1814 let focus_handle = prev_files
1815 .iter()
1816 .find_map(|(prev_file, handle)| {
1817 (prev_file == &settings_ui_file).then(|| handle.clone())
1818 })
1819 .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
1820 ui_files.push((settings_ui_file, focus_handle));
1821 }
1822
1823 ui_files.reverse();
1824
1825 let mut missing_worktrees = Vec::new();
1826
1827 for worktree in all_projects(cx)
1828 .flat_map(|project| project.read(cx).worktrees(cx))
1829 .filter(|tree| !self.worktree_root_dirs.contains_key(&tree.read(cx).id()))
1830 {
1831 let worktree = worktree.read(cx);
1832 let worktree_id = worktree.id();
1833 let Some(directory_name) = worktree.root_dir().and_then(|file| {
1834 file.file_name()
1835 .map(|os_string| os_string.to_string_lossy().to_string())
1836 }) else {
1837 continue;
1838 };
1839
1840 missing_worktrees.push((worktree_id, directory_name.clone()));
1841 let path = RelPath::empty().to_owned().into_arc();
1842
1843 let settings_ui_file = SettingsUiFile::Project((worktree_id, path));
1844
1845 let focus_handle = prev_files
1846 .iter()
1847 .find_map(|(prev_file, handle)| {
1848 (prev_file == &settings_ui_file).then(|| handle.clone())
1849 })
1850 .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
1851
1852 ui_files.push((settings_ui_file, focus_handle));
1853 }
1854
1855 self.worktree_root_dirs.extend(missing_worktrees);
1856
1857 self.files = ui_files;
1858 let current_file_still_exists = self
1859 .files
1860 .iter()
1861 .any(|(file, _)| file == &self.current_file);
1862 if !current_file_still_exists {
1863 self.change_file(0, window, cx);
1864 }
1865 }
1866
1867 fn open_navbar_entry_page(&mut self, navbar_entry: usize) {
1868 if !self.is_nav_entry_visible(navbar_entry) {
1869 self.open_first_nav_page();
1870 }
1871
1872 let is_new_page = self.navbar_entries[self.navbar_entry].page_index
1873 != self.navbar_entries[navbar_entry].page_index;
1874 self.navbar_entry = navbar_entry;
1875
1876 // We only need to reset visible items when updating matches
1877 // and selecting a new page
1878 if is_new_page {
1879 self.reset_list_state();
1880 }
1881
1882 sub_page_stack_mut().clear();
1883 }
1884
1885 fn open_first_nav_page(&mut self) {
1886 let Some(first_navbar_entry_index) = self.visible_navbar_entries().next().map(|e| e.0)
1887 else {
1888 return;
1889 };
1890 self.open_navbar_entry_page(first_navbar_entry_index);
1891 }
1892
1893 fn change_file(&mut self, ix: usize, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1894 if ix >= self.files.len() {
1895 self.current_file = SettingsUiFile::User;
1896 self.build_ui(window, cx);
1897 return;
1898 }
1899
1900 if self.files[ix].0 == self.current_file {
1901 return;
1902 }
1903 self.current_file = self.files[ix].0.clone();
1904
1905 self.build_ui(window, cx);
1906
1907 if self
1908 .visible_navbar_entries()
1909 .any(|(index, _)| index == self.navbar_entry)
1910 {
1911 self.open_and_scroll_to_navbar_entry(self.navbar_entry, None, true, window, cx);
1912 } else {
1913 self.open_first_nav_page();
1914 };
1915 }
1916
1917 fn render_files_header(
1918 &self,
1919 window: &mut Window,
1920 cx: &mut Context<SettingsWindow>,
1921 ) -> impl IntoElement {
1922 static OVERFLOW_LIMIT: usize = 1;
1923
1924 let file_button =
1925 |ix, file: &SettingsUiFile, focus_handle, cx: &mut Context<SettingsWindow>| {
1926 Button::new(
1927 ix,
1928 self.display_name(&file)
1929 .expect("Files should always have a name"),
1930 )
1931 .toggle_state(file == &self.current_file)
1932 .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
1933 .track_focus(focus_handle)
1934 .on_click(cx.listener({
1935 let focus_handle = focus_handle.clone();
1936 move |this, _: &gpui::ClickEvent, window, cx| {
1937 this.change_file(ix, window, cx);
1938 focus_handle.focus(window);
1939 }
1940 }))
1941 };
1942
1943 let this = cx.entity();
1944
1945 h_flex()
1946 .w_full()
1947 .pb_4()
1948 .gap_1()
1949 .justify_between()
1950 .track_focus(&self.files_focus_handle)
1951 .tab_group()
1952 .tab_index(HEADER_GROUP_TAB_INDEX)
1953 .child(
1954 h_flex()
1955 .gap_1()
1956 .children(
1957 self.files.iter().enumerate().take(OVERFLOW_LIMIT).map(
1958 |(ix, (file, focus_handle))| file_button(ix, file, focus_handle, cx),
1959 ),
1960 )
1961 .when(self.files.len() > OVERFLOW_LIMIT, |div| {
1962 let selected_file_ix = self
1963 .files
1964 .iter()
1965 .enumerate()
1966 .skip(OVERFLOW_LIMIT)
1967 .find_map(|(ix, (file, _))| {
1968 if file == &self.current_file {
1969 Some(ix)
1970 } else {
1971 None
1972 }
1973 })
1974 .unwrap_or(OVERFLOW_LIMIT);
1975
1976 let (file, focus_handle) = &self.files[selected_file_ix];
1977
1978 div.child(file_button(selected_file_ix, file, focus_handle, cx))
1979 .when(self.files.len() > OVERFLOW_LIMIT + 1, |div| {
1980 div.child(
1981 DropdownMenu::new(
1982 "more-files",
1983 format!("+{}", self.files.len() - (OVERFLOW_LIMIT + 1)),
1984 ContextMenu::build(window, cx, move |mut menu, _, _| {
1985 for (mut ix, (file, focus_handle)) in self
1986 .files
1987 .iter()
1988 .enumerate()
1989 .skip(OVERFLOW_LIMIT + 1)
1990 {
1991 let (display_name, focus_handle) =
1992 if selected_file_ix == ix {
1993 ix = OVERFLOW_LIMIT;
1994 (
1995 self.display_name(&self.files[ix].0),
1996 self.files[ix].1.clone(),
1997 )
1998 } else {
1999 (
2000 self.display_name(&file),
2001 focus_handle.clone(),
2002 )
2003 };
2004
2005 menu = menu.entry(
2006 display_name
2007 .expect("Files should always have a name"),
2008 None,
2009 {
2010 let this = this.clone();
2011 move |window, cx| {
2012 this.update(cx, |this, cx| {
2013 this.change_file(ix, window, cx);
2014 });
2015 focus_handle.focus(window);
2016 }
2017 },
2018 );
2019 }
2020
2021 menu
2022 }),
2023 )
2024 .style(DropdownStyle::Subtle)
2025 .trigger_tooltip(Tooltip::text("View Other Projects"))
2026 .trigger_icon(IconName::ChevronDown)
2027 .attach(gpui::Corner::BottomLeft)
2028 .offset(gpui::Point {
2029 x: px(0.0),
2030 y: px(2.0),
2031 })
2032 .tab_index(0),
2033 )
2034 })
2035 }),
2036 )
2037 .child(
2038 Button::new("edit-in-json", "Edit in settings.json")
2039 .tab_index(0_isize)
2040 .style(ButtonStyle::OutlinedGhost)
2041 .on_click(cx.listener(|this, _, _, cx| {
2042 this.open_current_settings_file(cx);
2043 })),
2044 )
2045 }
2046
2047 pub(crate) fn display_name(&self, file: &SettingsUiFile) -> Option<String> {
2048 match file {
2049 SettingsUiFile::User => Some("User".to_string()),
2050 SettingsUiFile::Project((worktree_id, path)) => self
2051 .worktree_root_dirs
2052 .get(&worktree_id)
2053 .map(|directory_name| {
2054 let path_style = PathStyle::local();
2055 if path.is_empty() {
2056 directory_name.clone()
2057 } else {
2058 format!(
2059 "{}{}{}",
2060 directory_name,
2061 path_style.separator(),
2062 path.display(path_style)
2063 )
2064 }
2065 }),
2066 SettingsUiFile::Server(file) => Some(file.to_string()),
2067 }
2068 }
2069
2070 // TODO:
2071 // Reconsider this after preview launch
2072 // fn file_location_str(&self) -> String {
2073 // match &self.current_file {
2074 // SettingsUiFile::User => "settings.json".to_string(),
2075 // SettingsUiFile::Project((worktree_id, path)) => self
2076 // .worktree_root_dirs
2077 // .get(&worktree_id)
2078 // .map(|directory_name| {
2079 // let path_style = PathStyle::local();
2080 // let file_path = path.join(paths::local_settings_file_relative_path());
2081 // format!(
2082 // "{}{}{}",
2083 // directory_name,
2084 // path_style.separator(),
2085 // file_path.display(path_style)
2086 // )
2087 // })
2088 // .expect("Current file should always be present in root dir map"),
2089 // SettingsUiFile::Server(file) => file.to_string(),
2090 // }
2091 // }
2092
2093 fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
2094 h_flex()
2095 .py_1()
2096 .px_1p5()
2097 .mb_3()
2098 .gap_1p5()
2099 .rounded_sm()
2100 .bg(cx.theme().colors().editor_background)
2101 .border_1()
2102 .border_color(cx.theme().colors().border)
2103 .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
2104 .child(self.search_bar.clone())
2105 }
2106
2107 fn render_nav(
2108 &self,
2109 window: &mut Window,
2110 cx: &mut Context<SettingsWindow>,
2111 ) -> impl IntoElement {
2112 let visible_count = self.visible_navbar_entries().count();
2113
2114 let focus_keybind_label = if self
2115 .navbar_focus_handle
2116 .read(cx)
2117 .handle
2118 .contains_focused(window, cx)
2119 || self
2120 .visible_navbar_entries()
2121 .any(|(_, entry)| entry.focus_handle.is_focused(window))
2122 {
2123 "Focus Content"
2124 } else {
2125 "Focus Navbar"
2126 };
2127
2128 v_flex()
2129 .key_context("NavigationMenu")
2130 .on_action(cx.listener(|this, _: &CollapseNavEntry, window, cx| {
2131 let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
2132 return;
2133 };
2134 let focused_entry_parent = this.root_entry_containing(focused_entry);
2135 if this.navbar_entries[focused_entry_parent].expanded {
2136 this.toggle_navbar_entry(focused_entry_parent);
2137 window.focus(&this.navbar_entries[focused_entry_parent].focus_handle);
2138 }
2139 cx.notify();
2140 }))
2141 .on_action(cx.listener(|this, _: &ExpandNavEntry, window, cx| {
2142 let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
2143 return;
2144 };
2145 if !this.navbar_entries[focused_entry].is_root {
2146 return;
2147 }
2148 if !this.navbar_entries[focused_entry].expanded {
2149 this.toggle_navbar_entry(focused_entry);
2150 }
2151 cx.notify();
2152 }))
2153 .on_action(
2154 cx.listener(|this, _: &FocusPreviousRootNavEntry, window, cx| {
2155 let entry_index = this
2156 .focused_nav_entry(window, cx)
2157 .unwrap_or(this.navbar_entry);
2158 let mut root_index = None;
2159 for (index, entry) in this.visible_navbar_entries() {
2160 if index >= entry_index {
2161 break;
2162 }
2163 if entry.is_root {
2164 root_index = Some(index);
2165 }
2166 }
2167 let Some(previous_root_index) = root_index else {
2168 return;
2169 };
2170 this.focus_and_scroll_to_nav_entry(previous_root_index, window, cx);
2171 }),
2172 )
2173 .on_action(cx.listener(|this, _: &FocusNextRootNavEntry, window, cx| {
2174 let entry_index = this
2175 .focused_nav_entry(window, cx)
2176 .unwrap_or(this.navbar_entry);
2177 let mut root_index = None;
2178 for (index, entry) in this.visible_navbar_entries() {
2179 if index <= entry_index {
2180 continue;
2181 }
2182 if entry.is_root {
2183 root_index = Some(index);
2184 break;
2185 }
2186 }
2187 let Some(next_root_index) = root_index else {
2188 return;
2189 };
2190 this.focus_and_scroll_to_nav_entry(next_root_index, window, cx);
2191 }))
2192 .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, cx| {
2193 if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
2194 this.focus_and_scroll_to_nav_entry(first_entry_index, window, cx);
2195 }
2196 }))
2197 .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, cx| {
2198 if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
2199 this.focus_and_scroll_to_nav_entry(last_entry_index, window, cx);
2200 }
2201 }))
2202 .on_action(cx.listener(|this, _: &FocusNextNavEntry, window, cx| {
2203 let entry_index = this
2204 .focused_nav_entry(window, cx)
2205 .unwrap_or(this.navbar_entry);
2206 let mut next_index = None;
2207 for (index, _) in this.visible_navbar_entries() {
2208 if index > entry_index {
2209 next_index = Some(index);
2210 break;
2211 }
2212 }
2213 let Some(next_entry_index) = next_index else {
2214 return;
2215 };
2216 this.open_and_scroll_to_navbar_entry(
2217 next_entry_index,
2218 Some(gpui::ScrollStrategy::Bottom),
2219 false,
2220 window,
2221 cx,
2222 );
2223 }))
2224 .on_action(cx.listener(|this, _: &FocusPreviousNavEntry, window, cx| {
2225 let entry_index = this
2226 .focused_nav_entry(window, cx)
2227 .unwrap_or(this.navbar_entry);
2228 let mut prev_index = None;
2229 for (index, _) in this.visible_navbar_entries() {
2230 if index >= entry_index {
2231 break;
2232 }
2233 prev_index = Some(index);
2234 }
2235 let Some(prev_entry_index) = prev_index else {
2236 return;
2237 };
2238 this.open_and_scroll_to_navbar_entry(
2239 prev_entry_index,
2240 Some(gpui::ScrollStrategy::Top),
2241 false,
2242 window,
2243 cx,
2244 );
2245 }))
2246 .w_56()
2247 .h_full()
2248 .p_2p5()
2249 .when(cfg!(target_os = "macos"), |this| this.pt_10())
2250 .flex_none()
2251 .border_r_1()
2252 .border_color(cx.theme().colors().border)
2253 .bg(cx.theme().colors().panel_background)
2254 .child(self.render_search(window, cx))
2255 .child(
2256 v_flex()
2257 .flex_1()
2258 .overflow_hidden()
2259 .track_focus(&self.navbar_focus_handle.focus_handle(cx))
2260 .tab_group()
2261 .tab_index(NAVBAR_GROUP_TAB_INDEX)
2262 .child(
2263 uniform_list(
2264 "settings-ui-nav-bar",
2265 visible_count + 1,
2266 cx.processor(move |this, range: Range<usize>, _, cx| {
2267 this.visible_navbar_entries()
2268 .skip(range.start.saturating_sub(1))
2269 .take(range.len())
2270 .map(|(entry_index, entry)| {
2271 TreeViewItem::new(
2272 ("settings-ui-navbar-entry", entry_index),
2273 entry.title,
2274 )
2275 .track_focus(&entry.focus_handle)
2276 .root_item(entry.is_root)
2277 .toggle_state(this.is_navbar_entry_selected(entry_index))
2278 .when(entry.is_root, |item| {
2279 item.expanded(entry.expanded || this.has_query)
2280 .on_toggle(cx.listener(
2281 move |this, _, window, cx| {
2282 this.toggle_navbar_entry(entry_index);
2283 window.focus(
2284 &this.navbar_entries[entry_index]
2285 .focus_handle,
2286 );
2287 cx.notify();
2288 },
2289 ))
2290 })
2291 .on_click(
2292 cx.listener(move |this, _, window, cx| {
2293 this.open_and_scroll_to_navbar_entry(
2294 entry_index,
2295 None,
2296 true,
2297 window,
2298 cx,
2299 );
2300 }),
2301 )
2302 })
2303 .collect()
2304 }),
2305 )
2306 .size_full()
2307 .track_scroll(self.navbar_scroll_handle.clone()),
2308 )
2309 .vertical_scrollbar_for(self.navbar_scroll_handle.clone(), window, cx),
2310 )
2311 .child(
2312 h_flex()
2313 .w_full()
2314 .h_8()
2315 .p_2()
2316 .pb_0p5()
2317 .flex_shrink_0()
2318 .border_t_1()
2319 .border_color(cx.theme().colors().border_variant)
2320 .child(
2321 KeybindingHint::new(
2322 KeyBinding::for_action_in(
2323 &ToggleFocusNav,
2324 &self.navbar_focus_handle.focus_handle(cx),
2325 cx,
2326 ),
2327 cx.theme().colors().surface_background.opacity(0.5),
2328 )
2329 .suffix(focus_keybind_label),
2330 ),
2331 )
2332 }
2333
2334 fn open_and_scroll_to_navbar_entry(
2335 &mut self,
2336 navbar_entry_index: usize,
2337 scroll_strategy: Option<gpui::ScrollStrategy>,
2338 focus_content: bool,
2339 window: &mut Window,
2340 cx: &mut Context<Self>,
2341 ) {
2342 self.open_navbar_entry_page(navbar_entry_index);
2343 cx.notify();
2344
2345 let mut handle_to_focus = None;
2346
2347 if self.navbar_entries[navbar_entry_index].is_root
2348 || !self.is_nav_entry_visible(navbar_entry_index)
2349 {
2350 self.sub_page_scroll_handle
2351 .set_offset(point(px(0.), px(0.)));
2352 if focus_content {
2353 let Some(first_item_index) =
2354 self.visible_page_items().next().map(|(index, _)| index)
2355 else {
2356 return;
2357 };
2358 handle_to_focus = Some(self.focus_handle_for_content_element(first_item_index, cx));
2359 } else if !self.is_nav_entry_visible(navbar_entry_index) {
2360 let Some(first_visible_nav_entry_index) =
2361 self.visible_navbar_entries().next().map(|(index, _)| index)
2362 else {
2363 return;
2364 };
2365 self.focus_and_scroll_to_nav_entry(first_visible_nav_entry_index, window, cx);
2366 } else {
2367 handle_to_focus =
2368 Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2369 }
2370 } else {
2371 let entry_item_index = self.navbar_entries[navbar_entry_index]
2372 .item_index
2373 .expect("Non-root items should have an item index");
2374 self.scroll_to_content_item(entry_item_index, window, cx);
2375 if focus_content {
2376 handle_to_focus = Some(self.focus_handle_for_content_element(entry_item_index, cx));
2377 } else {
2378 handle_to_focus =
2379 Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2380 }
2381 }
2382
2383 if let Some(scroll_strategy) = scroll_strategy
2384 && let Some(logical_entry_index) = self
2385 .visible_navbar_entries()
2386 .into_iter()
2387 .position(|(index, _)| index == navbar_entry_index)
2388 {
2389 self.navbar_scroll_handle
2390 .scroll_to_item(logical_entry_index + 1, scroll_strategy);
2391 }
2392
2393 // Page scroll handle updates the active item index
2394 // in it's next paint call after using scroll_handle.scroll_to_top_of_item
2395 // The call after that updates the offset of the scroll handle. So to
2396 // ensure the scroll handle doesn't lag behind we need to render three frames
2397 // back to back.
2398 cx.on_next_frame(window, move |_, window, cx| {
2399 if let Some(handle) = handle_to_focus.as_ref() {
2400 window.focus(handle);
2401 }
2402
2403 cx.on_next_frame(window, |_, _, cx| {
2404 cx.notify();
2405 });
2406 cx.notify();
2407 });
2408 cx.notify();
2409 }
2410
2411 fn scroll_to_content_item(
2412 &self,
2413 content_item_index: usize,
2414 _window: &mut Window,
2415 cx: &mut Context<Self>,
2416 ) {
2417 let index = self
2418 .visible_page_items()
2419 .position(|(index, _)| index == content_item_index)
2420 .unwrap_or(0);
2421 if index == 0 {
2422 self.sub_page_scroll_handle
2423 .set_offset(point(px(0.), px(0.)));
2424 self.list_state.scroll_to(gpui::ListOffset {
2425 item_ix: 0,
2426 offset_in_item: px(0.),
2427 });
2428 return;
2429 }
2430 self.list_state.scroll_to(gpui::ListOffset {
2431 item_ix: index + 1,
2432 offset_in_item: px(0.),
2433 });
2434 cx.notify();
2435 }
2436
2437 fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
2438 self.visible_navbar_entries()
2439 .any(|(index, _)| index == nav_entry_index)
2440 }
2441
2442 fn focus_and_scroll_to_first_visible_nav_entry(
2443 &self,
2444 window: &mut Window,
2445 cx: &mut Context<Self>,
2446 ) {
2447 if let Some(nav_entry_index) = self.visible_navbar_entries().next().map(|(index, _)| index)
2448 {
2449 self.focus_and_scroll_to_nav_entry(nav_entry_index, window, cx);
2450 }
2451 }
2452
2453 fn focus_and_scroll_to_nav_entry(
2454 &self,
2455 nav_entry_index: usize,
2456 window: &mut Window,
2457 cx: &mut Context<Self>,
2458 ) {
2459 let Some(position) = self
2460 .visible_navbar_entries()
2461 .position(|(index, _)| index == nav_entry_index)
2462 else {
2463 return;
2464 };
2465 self.navbar_scroll_handle
2466 .scroll_to_item(position, gpui::ScrollStrategy::Top);
2467 window.focus(&self.navbar_entries[nav_entry_index].focus_handle);
2468 cx.notify();
2469 }
2470
2471 fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
2472 let page_idx = self.current_page_index();
2473
2474 self.current_page()
2475 .items
2476 .iter()
2477 .enumerate()
2478 .filter_map(move |(item_index, item)| {
2479 self.filter_table[page_idx][item_index].then_some((item_index, item))
2480 })
2481 }
2482
2483 fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
2484 let mut items = vec![];
2485 items.push(self.current_page().title.into());
2486 items.extend(
2487 sub_page_stack()
2488 .iter()
2489 .flat_map(|page| [page.section_header.into(), page.link.title.clone()]),
2490 );
2491
2492 let last = items.pop().unwrap();
2493 h_flex()
2494 .gap_1()
2495 .children(
2496 items
2497 .into_iter()
2498 .flat_map(|item| [item, "/".into()])
2499 .map(|item| Label::new(item).color(Color::Muted)),
2500 )
2501 .child(Label::new(last))
2502 }
2503
2504 fn render_empty_state(&self, search_query: SharedString) -> impl IntoElement {
2505 v_flex()
2506 .size_full()
2507 .items_center()
2508 .justify_center()
2509 .gap_1()
2510 .child(Label::new("No Results"))
2511 .child(
2512 Label::new(search_query)
2513 .size(LabelSize::Small)
2514 .color(Color::Muted),
2515 )
2516 }
2517
2518 fn render_page_items(
2519 &mut self,
2520 page_index: usize,
2521 _window: &mut Window,
2522 cx: &mut Context<SettingsWindow>,
2523 ) -> impl IntoElement {
2524 let mut page_content = v_flex().id("settings-ui-page").size_full();
2525
2526 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2527 let has_no_results = self.visible_page_items().next().is_none() && has_active_search;
2528
2529 if has_no_results {
2530 let search_query = self.search_bar.read(cx).text(cx);
2531 page_content = page_content.child(
2532 self.render_empty_state(format!("No settings match \"{}\"", search_query).into()),
2533 )
2534 } else {
2535 let last_non_header_index = self
2536 .visible_page_items()
2537 .filter_map(|(index, item)| {
2538 (!matches!(item, SettingsPageItem::SectionHeader(_))).then_some(index)
2539 })
2540 .last();
2541
2542 let root_nav_label = self
2543 .navbar_entries
2544 .iter()
2545 .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2546 .map(|entry| entry.title);
2547
2548 let list_content = list(
2549 self.list_state.clone(),
2550 cx.processor(move |this, index, window, cx| {
2551 if index == 0 {
2552 return div()
2553 .when(sub_page_stack().is_empty(), |this| {
2554 this.when_some(root_nav_label, |this, title| {
2555 this.child(
2556 Label::new(title).size(LabelSize::Large).mt_2().mb_3(),
2557 )
2558 })
2559 })
2560 .into_any_element();
2561 }
2562
2563 let mut visible_items = this.visible_page_items();
2564 let Some((actual_item_index, item)) = visible_items.nth(index - 1) else {
2565 return gpui::Empty.into_any_element();
2566 };
2567
2568 let no_bottom_border = visible_items
2569 .next()
2570 .map(|(_, item)| matches!(item, SettingsPageItem::SectionHeader(_)))
2571 .unwrap_or(false);
2572
2573 let is_last = Some(actual_item_index) == last_non_header_index;
2574
2575 let item_focus_handle =
2576 this.content_handles[page_index][actual_item_index].focus_handle(cx);
2577
2578 v_flex()
2579 .id(("settings-page-item", actual_item_index))
2580 .w_full()
2581 .min_w_0()
2582 .track_focus(&item_focus_handle)
2583 .child(item.render(
2584 this,
2585 actual_item_index,
2586 no_bottom_border || is_last,
2587 window,
2588 cx,
2589 ))
2590 .into_any_element()
2591 }),
2592 );
2593
2594 page_content = page_content.child(list_content.size_full())
2595 }
2596 page_content
2597 }
2598
2599 fn render_sub_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
2600 &self,
2601 items: Items,
2602 page_index: Option<usize>,
2603 window: &mut Window,
2604 cx: &mut Context<SettingsWindow>,
2605 ) -> impl IntoElement {
2606 let mut page_content = v_flex()
2607 .id("settings-ui-page")
2608 .size_full()
2609 .overflow_y_scroll()
2610 .track_scroll(&self.sub_page_scroll_handle);
2611
2612 let items: Vec<_> = items.collect();
2613 let items_len = items.len();
2614 let mut section_header = None;
2615
2616 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2617 let has_no_results = items_len == 0 && has_active_search;
2618
2619 if has_no_results {
2620 let search_query = self.search_bar.read(cx).text(cx);
2621 page_content = page_content.child(
2622 self.render_empty_state(format!("No settings match \"{}\"", search_query).into()),
2623 )
2624 } else {
2625 let last_non_header_index = items
2626 .iter()
2627 .enumerate()
2628 .rev()
2629 .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
2630 .map(|(index, _)| index);
2631
2632 let root_nav_label = self
2633 .navbar_entries
2634 .iter()
2635 .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2636 .map(|entry| entry.title);
2637
2638 page_content = page_content
2639 .when(sub_page_stack().is_empty(), |this| {
2640 this.when_some(root_nav_label, |this, title| {
2641 this.child(Label::new(title).size(LabelSize::Large).mt_2().mb_3())
2642 })
2643 })
2644 .children(items.clone().into_iter().enumerate().map(
2645 |(index, (actual_item_index, item))| {
2646 let no_bottom_border = items
2647 .get(index + 1)
2648 .map(|(_, next_item)| {
2649 matches!(next_item, SettingsPageItem::SectionHeader(_))
2650 })
2651 .unwrap_or(false);
2652 let is_last = Some(index) == last_non_header_index;
2653
2654 if let SettingsPageItem::SectionHeader(header) = item {
2655 section_header = Some(*header);
2656 }
2657 v_flex()
2658 .w_full()
2659 .min_w_0()
2660 .id(("settings-page-item", actual_item_index))
2661 .when_some(page_index, |element, page_index| {
2662 element.track_focus(
2663 &self.content_handles[page_index][actual_item_index]
2664 .focus_handle(cx),
2665 )
2666 })
2667 .child(item.render(
2668 self,
2669 actual_item_index,
2670 no_bottom_border || is_last,
2671 window,
2672 cx,
2673 ))
2674 },
2675 ))
2676 }
2677 page_content
2678 }
2679
2680 fn render_page(
2681 &mut self,
2682 window: &mut Window,
2683 cx: &mut Context<SettingsWindow>,
2684 ) -> impl IntoElement {
2685 let page_header;
2686 let page_content;
2687
2688 if sub_page_stack().is_empty() {
2689 page_header = self.render_files_header(window, cx).into_any_element();
2690
2691 page_content = self
2692 .render_page_items(self.current_page_index(), window, cx)
2693 .into_any_element();
2694 } else {
2695 page_header = h_flex()
2696 .ml_neg_1p5()
2697 .pb_4()
2698 .gap_1()
2699 .child(
2700 IconButton::new("back-btn", IconName::ArrowLeft)
2701 .icon_size(IconSize::Small)
2702 .shape(IconButtonShape::Square)
2703 .on_click(cx.listener(|this, _, _, cx| {
2704 this.pop_sub_page(cx);
2705 })),
2706 )
2707 .child(self.render_sub_page_breadcrumbs())
2708 .into_any_element();
2709
2710 let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
2711 page_content = (active_page_render_fn)(self, window, cx);
2712 }
2713
2714 let mut warning_banner = gpui::Empty.into_any_element();
2715 if let Some(error) =
2716 SettingsStore::global(cx).error_for_file(self.current_file.to_settings())
2717 {
2718 warning_banner = v_flex()
2719 .pb_4()
2720 .child(
2721 Banner::new()
2722 .severity(Severity::Warning)
2723 .child(
2724 v_flex()
2725 .my_0p5()
2726 .gap_0p5()
2727 .child(Label::new("Your settings file is in an invalid state."))
2728 .child(
2729 Label::new(error).size(LabelSize::Small).color(Color::Muted),
2730 ),
2731 )
2732 .action_slot(
2733 div().pr_1().child(
2734 Button::new("fix-in-json", "Fix in settings.json")
2735 .tab_index(0_isize)
2736 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
2737 .on_click(cx.listener(|this, _, _, cx| {
2738 this.open_current_settings_file(cx);
2739 })),
2740 ),
2741 ),
2742 )
2743 .into_any_element()
2744 }
2745
2746 return v_flex()
2747 .id("Settings-ui-page")
2748 .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
2749 if !sub_page_stack().is_empty() {
2750 window.focus_next();
2751 return;
2752 }
2753 for (logical_index, (actual_index, _)) in this.visible_page_items().enumerate() {
2754 let handle = this.content_handles[this.current_page_index()][actual_index]
2755 .focus_handle(cx);
2756 let mut offset = 1; // for page header
2757
2758 if let Some((_, next_item)) = this.visible_page_items().nth(logical_index + 1)
2759 && matches!(next_item, SettingsPageItem::SectionHeader(_))
2760 {
2761 offset += 1;
2762 }
2763 if handle.contains_focused(window, cx) {
2764 let next_logical_index = logical_index + offset + 1;
2765 this.list_state.scroll_to_reveal_item(next_logical_index);
2766 // We need to render the next item to ensure it's focus handle is in the element tree
2767 cx.on_next_frame(window, |_, window, cx| {
2768 window.focus_next();
2769 cx.notify();
2770 });
2771 cx.notify();
2772 return;
2773 }
2774 }
2775 window.focus_next();
2776 }))
2777 .on_action(cx.listener(|this, _: &menu::SelectPrevious, window, cx| {
2778 if !sub_page_stack().is_empty() {
2779 window.focus_prev();
2780 return;
2781 }
2782 let mut prev_was_header = false;
2783 for (logical_index, (actual_index, item)) in this.visible_page_items().enumerate() {
2784 let is_header = matches!(item, SettingsPageItem::SectionHeader(_));
2785 let handle = this.content_handles[this.current_page_index()][actual_index]
2786 .focus_handle(cx);
2787 let mut offset = 1; // for page header
2788
2789 if prev_was_header {
2790 offset -= 1;
2791 }
2792 if handle.contains_focused(window, cx) {
2793 let next_logical_index = logical_index + offset - 1;
2794 this.list_state.scroll_to_reveal_item(next_logical_index);
2795 // We need to render the next item to ensure it's focus handle is in the element tree
2796 cx.on_next_frame(window, |_, window, cx| {
2797 window.focus_prev();
2798 cx.notify();
2799 });
2800 cx.notify();
2801 return;
2802 }
2803 prev_was_header = is_header;
2804 }
2805 window.focus_prev();
2806 }))
2807 .when(sub_page_stack().is_empty(), |this| {
2808 this.vertical_scrollbar_for(self.list_state.clone(), window, cx)
2809 })
2810 .when(!sub_page_stack().is_empty(), |this| {
2811 this.vertical_scrollbar_for(self.sub_page_scroll_handle.clone(), window, cx)
2812 })
2813 .track_focus(&self.content_focus_handle.focus_handle(cx))
2814 .flex_1()
2815 .pt_6()
2816 // .px_8()
2817 .bg(cx.theme().colors().editor_background)
2818 .child(warning_banner)
2819 .child(page_header)
2820 .child(
2821 div()
2822 .px_8()
2823 // .debug_bg_red()
2824 .size_full()
2825 .tab_group()
2826 .tab_index(CONTENT_GROUP_TAB_INDEX)
2827 .child(page_content),
2828 );
2829 }
2830
2831 /// This function will create a new settings file if one doesn't exist
2832 /// if the current file is a project settings with a valid worktree id
2833 /// We do this because the settings ui allows initializing project settings
2834 fn open_current_settings_file(&mut self, cx: &mut Context<Self>) {
2835 match &self.current_file {
2836 SettingsUiFile::User => {
2837 let Some(original_window) = self.original_window else {
2838 return;
2839 };
2840 original_window
2841 .update(cx, |workspace, window, cx| {
2842 workspace
2843 .with_local_workspace(window, cx, |workspace, window, cx| {
2844 let create_task = workspace.project().update(cx, |project, cx| {
2845 project.find_or_create_worktree(
2846 paths::config_dir().as_path(),
2847 false,
2848 cx,
2849 )
2850 });
2851 let open_task = workspace.open_paths(
2852 vec![paths::settings_file().to_path_buf()],
2853 OpenOptions {
2854 visible: Some(OpenVisible::None),
2855 ..Default::default()
2856 },
2857 None,
2858 window,
2859 cx,
2860 );
2861
2862 cx.spawn_in(window, async move |workspace, cx| {
2863 create_task.await.ok();
2864 open_task.await;
2865
2866 workspace.update_in(cx, |_, window, cx| {
2867 window.activate_window();
2868 cx.notify();
2869 })
2870 })
2871 .detach();
2872 })
2873 .detach();
2874 })
2875 .ok();
2876 }
2877 SettingsUiFile::Project((worktree_id, path)) => {
2878 let settings_path = path.join(paths::local_settings_file_relative_path());
2879 let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
2880 return;
2881 };
2882
2883 let Some((worktree, corresponding_workspace)) = app_state
2884 .workspace_store
2885 .read(cx)
2886 .workspaces()
2887 .iter()
2888 .find_map(|workspace| {
2889 workspace
2890 .read_with(cx, |workspace, cx| {
2891 workspace
2892 .project()
2893 .read(cx)
2894 .worktree_for_id(*worktree_id, cx)
2895 })
2896 .ok()
2897 .flatten()
2898 .zip(Some(*workspace))
2899 })
2900 else {
2901 log::error!(
2902 "No corresponding workspace contains worktree id: {}",
2903 worktree_id
2904 );
2905
2906 return;
2907 };
2908
2909 let create_task = if worktree.read(cx).entry_for_path(&settings_path).is_some() {
2910 None
2911 } else {
2912 Some(worktree.update(cx, |tree, cx| {
2913 tree.create_entry(
2914 settings_path.clone(),
2915 false,
2916 Some("{\n\n}".as_bytes().to_vec()),
2917 cx,
2918 )
2919 }))
2920 };
2921
2922 let worktree_id = *worktree_id;
2923
2924 // TODO: move zed::open_local_file() APIs to this crate, and
2925 // re-implement the "initial_contents" behavior
2926 corresponding_workspace
2927 .update(cx, |_, window, cx| {
2928 cx.spawn_in(window, async move |workspace, cx| {
2929 if let Some(create_task) = create_task {
2930 create_task.await.ok()?;
2931 };
2932
2933 workspace
2934 .update_in(cx, |workspace, window, cx| {
2935 workspace.open_path(
2936 (worktree_id, settings_path.clone()),
2937 None,
2938 true,
2939 window,
2940 cx,
2941 )
2942 })
2943 .ok()?
2944 .await
2945 .log_err()?;
2946
2947 workspace
2948 .update_in(cx, |_, window, cx| {
2949 window.activate_window();
2950 cx.notify();
2951 })
2952 .ok();
2953
2954 Some(())
2955 })
2956 .detach();
2957 })
2958 .ok();
2959 }
2960 SettingsUiFile::Server(_) => {
2961 return;
2962 }
2963 };
2964 }
2965
2966 fn current_page_index(&self) -> usize {
2967 self.page_index_from_navbar_index(self.navbar_entry)
2968 }
2969
2970 fn current_page(&self) -> &SettingsPage {
2971 &self.pages[self.current_page_index()]
2972 }
2973
2974 fn page_index_from_navbar_index(&self, index: usize) -> usize {
2975 if self.navbar_entries.is_empty() {
2976 return 0;
2977 }
2978
2979 self.navbar_entries[index].page_index
2980 }
2981
2982 fn is_navbar_entry_selected(&self, ix: usize) -> bool {
2983 ix == self.navbar_entry
2984 }
2985
2986 fn push_sub_page(
2987 &mut self,
2988 sub_page_link: SubPageLink,
2989 section_header: &'static str,
2990 cx: &mut Context<SettingsWindow>,
2991 ) {
2992 sub_page_stack_mut().push(SubPage {
2993 link: sub_page_link,
2994 section_header,
2995 });
2996 cx.notify();
2997 }
2998
2999 fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
3000 sub_page_stack_mut().pop();
3001 cx.notify();
3002 }
3003
3004 fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
3005 if let Some((_, handle)) = self.files.get(index) {
3006 handle.focus(window);
3007 }
3008 }
3009
3010 fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
3011 if self.files_focus_handle.contains_focused(window, cx)
3012 && let Some(index) = self
3013 .files
3014 .iter()
3015 .position(|(_, handle)| handle.is_focused(window))
3016 {
3017 return index;
3018 }
3019 if let Some(current_file_index) = self
3020 .files
3021 .iter()
3022 .position(|(file, _)| file == &self.current_file)
3023 {
3024 return current_file_index;
3025 }
3026 0
3027 }
3028
3029 fn focus_handle_for_content_element(
3030 &self,
3031 actual_item_index: usize,
3032 cx: &Context<Self>,
3033 ) -> FocusHandle {
3034 let page_index = self.current_page_index();
3035 self.content_handles[page_index][actual_item_index].focus_handle(cx)
3036 }
3037
3038 fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
3039 if !self
3040 .navbar_focus_handle
3041 .focus_handle(cx)
3042 .contains_focused(window, cx)
3043 {
3044 return None;
3045 }
3046 for (index, entry) in self.navbar_entries.iter().enumerate() {
3047 if entry.focus_handle.is_focused(window) {
3048 return Some(index);
3049 }
3050 }
3051 None
3052 }
3053
3054 fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
3055 let mut index = Some(nav_entry_index);
3056 while let Some(prev_index) = index
3057 && !self.navbar_entries[prev_index].is_root
3058 {
3059 index = prev_index.checked_sub(1);
3060 }
3061 return index.expect("No root entry found");
3062 }
3063}
3064
3065impl Render for SettingsWindow {
3066 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3067 let ui_font = theme::setup_ui_font(window, cx);
3068
3069 client_side_decorations(
3070 v_flex()
3071 .text_color(cx.theme().colors().text)
3072 .size_full()
3073 .children(self.title_bar.clone())
3074 .child(
3075 div()
3076 .id("settings-window")
3077 .key_context("SettingsWindow")
3078 .track_focus(&self.focus_handle)
3079 .on_action(cx.listener(|this, _: &OpenCurrentFile, _, cx| {
3080 this.open_current_settings_file(cx);
3081 }))
3082 .on_action(|_: &Minimize, window, _cx| {
3083 window.minimize_window();
3084 })
3085 .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
3086 this.search_bar.focus_handle(cx).focus(window);
3087 }))
3088 .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
3089 if this
3090 .navbar_focus_handle
3091 .focus_handle(cx)
3092 .contains_focused(window, cx)
3093 {
3094 this.open_and_scroll_to_navbar_entry(
3095 this.navbar_entry,
3096 None,
3097 true,
3098 window,
3099 cx,
3100 );
3101 } else {
3102 this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
3103 }
3104 }))
3105 .on_action(cx.listener(
3106 |this, FocusFile(file_index): &FocusFile, window, _| {
3107 this.focus_file_at_index(*file_index as usize, window);
3108 },
3109 ))
3110 .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
3111 let next_index = usize::min(
3112 this.focused_file_index(window, cx) + 1,
3113 this.files.len().saturating_sub(1),
3114 );
3115 this.focus_file_at_index(next_index, window);
3116 }))
3117 .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
3118 let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
3119 this.focus_file_at_index(prev_index, window);
3120 }))
3121 .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
3122 if this
3123 .search_bar
3124 .focus_handle(cx)
3125 .contains_focused(window, cx)
3126 {
3127 this.focus_and_scroll_to_first_visible_nav_entry(window, cx);
3128 } else {
3129 window.focus_next();
3130 }
3131 }))
3132 .on_action(|_: &menu::SelectPrevious, window, _| {
3133 window.focus_prev();
3134 })
3135 .flex()
3136 .flex_row()
3137 .flex_1()
3138 .min_h_0()
3139 .font(ui_font)
3140 .bg(cx.theme().colors().background)
3141 .text_color(cx.theme().colors().text)
3142 .when(!cfg!(target_os = "macos"), |this| {
3143 this.border_t_1().border_color(cx.theme().colors().border)
3144 })
3145 .child(self.render_nav(window, cx))
3146 .child(self.render_page(window, cx)),
3147 ),
3148 window,
3149 cx,
3150 )
3151 }
3152}
3153
3154fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
3155 workspace::AppState::global(cx)
3156 .upgrade()
3157 .map(|app_state| {
3158 app_state
3159 .workspace_store
3160 .read(cx)
3161 .workspaces()
3162 .iter()
3163 .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
3164 })
3165 .into_iter()
3166 .flatten()
3167}
3168
3169fn update_settings_file(
3170 file: SettingsUiFile,
3171 cx: &mut App,
3172 update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
3173) -> Result<()> {
3174 match file {
3175 SettingsUiFile::Project((worktree_id, rel_path)) => {
3176 let rel_path = rel_path.join(paths::local_settings_file_relative_path());
3177 let Some((worktree, project)) = all_projects(cx).find_map(|project| {
3178 project
3179 .read(cx)
3180 .worktree_for_id(worktree_id, cx)
3181 .zip(Some(project))
3182 }) else {
3183 anyhow::bail!("Could not find project with worktree id: {}", worktree_id);
3184 };
3185
3186 project.update(cx, |project, cx| {
3187 let task = if project.contains_local_settings_file(worktree_id, &rel_path, cx) {
3188 None
3189 } else {
3190 Some(worktree.update(cx, |worktree, cx| {
3191 worktree.create_entry(rel_path.clone(), false, None, cx)
3192 }))
3193 };
3194
3195 cx.spawn(async move |project, cx| {
3196 if let Some(task) = task
3197 && task.await.is_err()
3198 {
3199 return;
3200 };
3201
3202 project
3203 .update(cx, |project, cx| {
3204 project.update_local_settings_file(worktree_id, rel_path, cx, update);
3205 })
3206 .ok();
3207 })
3208 .detach();
3209 });
3210
3211 return Ok(());
3212 }
3213 SettingsUiFile::User => {
3214 // todo(settings_ui) error?
3215 SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
3216 Ok(())
3217 }
3218 SettingsUiFile::Server(_) => unimplemented!(),
3219 }
3220}
3221
3222fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
3223 field: SettingField<T>,
3224 file: SettingsUiFile,
3225 metadata: Option<&SettingsFieldMetadata>,
3226 _window: &mut Window,
3227 cx: &mut App,
3228) -> AnyElement {
3229 let (_, initial_text) =
3230 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3231 let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
3232
3233 SettingsInputField::new()
3234 .tab_index(0)
3235 .when_some(initial_text, |editor, text| {
3236 editor.with_initial_text(text.as_ref().to_string())
3237 })
3238 .when_some(
3239 metadata.and_then(|metadata| metadata.placeholder),
3240 |editor, placeholder| editor.with_placeholder(placeholder),
3241 )
3242 .on_confirm({
3243 move |new_text, cx| {
3244 update_settings_file(file.clone(), cx, move |settings, _cx| {
3245 (field.write)(settings, new_text.map(Into::into));
3246 })
3247 .log_err(); // todo(settings_ui) don't log err
3248 }
3249 })
3250 .into_any_element()
3251}
3252
3253fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
3254 field: SettingField<B>,
3255 file: SettingsUiFile,
3256 _metadata: Option<&SettingsFieldMetadata>,
3257 _window: &mut Window,
3258 cx: &mut App,
3259) -> AnyElement {
3260 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3261
3262 let toggle_state = if value.copied().map_or(false, Into::into) {
3263 ToggleState::Selected
3264 } else {
3265 ToggleState::Unselected
3266 };
3267
3268 Switch::new("toggle_button", toggle_state)
3269 .tab_index(0_isize)
3270 .color(SwitchColor::Accent)
3271 .on_click({
3272 move |state, _window, cx| {
3273 let state = *state == ui::ToggleState::Selected;
3274 update_settings_file(file.clone(), cx, move |settings, _cx| {
3275 (field.write)(settings, Some(state.into()));
3276 })
3277 .log_err(); // todo(settings_ui) don't log err
3278 }
3279 })
3280 .into_any_element()
3281}
3282
3283fn render_number_field<T: NumberFieldType + Send + Sync>(
3284 field: SettingField<T>,
3285 file: SettingsUiFile,
3286 _metadata: Option<&SettingsFieldMetadata>,
3287 window: &mut Window,
3288 cx: &mut App,
3289) -> AnyElement {
3290 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3291 let value = value.copied().unwrap_or_else(T::min_value);
3292 NumberField::new("numeric_stepper", value, window, cx)
3293 .on_change({
3294 move |value, _window, cx| {
3295 let value = *value;
3296 update_settings_file(file.clone(), cx, move |settings, _cx| {
3297 (field.write)(settings, Some(value));
3298 })
3299 .log_err(); // todo(settings_ui) don't log err
3300 }
3301 })
3302 .into_any_element()
3303}
3304
3305fn render_dropdown<T>(
3306 field: SettingField<T>,
3307 file: SettingsUiFile,
3308 metadata: Option<&SettingsFieldMetadata>,
3309 window: &mut Window,
3310 cx: &mut App,
3311) -> AnyElement
3312where
3313 T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
3314{
3315 let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
3316 let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
3317 let should_do_titlecase = metadata
3318 .and_then(|metadata| metadata.should_do_titlecase)
3319 .unwrap_or(true);
3320
3321 let (_, current_value) =
3322 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3323 let current_value = current_value.copied().unwrap_or(variants()[0]);
3324
3325 let current_value_label =
3326 labels()[variants().iter().position(|v| *v == current_value).unwrap()];
3327
3328 DropdownMenu::new(
3329 "dropdown",
3330 if should_do_titlecase {
3331 current_value_label.to_title_case()
3332 } else {
3333 current_value_label.to_string()
3334 },
3335 window.use_state(cx, |window, cx| {
3336 ContextMenu::new(window, cx, move |mut menu, _, _| {
3337 for (&value, &label) in std::iter::zip(variants(), labels()) {
3338 let file = file.clone();
3339 menu = menu.toggleable_entry(
3340 if should_do_titlecase {
3341 label.to_title_case()
3342 } else {
3343 label.to_string()
3344 },
3345 value == current_value,
3346 IconPosition::End,
3347 None,
3348 move |_, cx| {
3349 if value == current_value {
3350 return;
3351 }
3352 update_settings_file(file.clone(), cx, move |settings, _cx| {
3353 (field.write)(settings, Some(value));
3354 })
3355 .log_err(); // todo(settings_ui) don't log err
3356 },
3357 );
3358 }
3359 menu
3360 })
3361 }),
3362 )
3363 .tab_index(0)
3364 .trigger_size(ButtonSize::Medium)
3365 .style(DropdownStyle::Outlined)
3366 .offset(gpui::Point {
3367 x: px(0.0),
3368 y: px(2.0),
3369 })
3370 .into_any_element()
3371}
3372
3373fn render_picker_trigger_button(id: SharedString, label: SharedString) -> Button {
3374 Button::new(id, label)
3375 .tab_index(0_isize)
3376 .style(ButtonStyle::Outlined)
3377 .size(ButtonSize::Medium)
3378 .icon(IconName::ChevronUpDown)
3379 .icon_color(Color::Muted)
3380 .icon_size(IconSize::Small)
3381 .icon_position(IconPosition::End)
3382}
3383
3384fn render_font_picker(
3385 field: SettingField<settings::FontFamilyName>,
3386 file: SettingsUiFile,
3387 _metadata: Option<&SettingsFieldMetadata>,
3388 _window: &mut Window,
3389 cx: &mut App,
3390) -> AnyElement {
3391 let current_value = SettingsStore::global(cx)
3392 .get_value_from_file(file.to_settings(), field.pick)
3393 .1
3394 .cloned()
3395 .unwrap_or_else(|| SharedString::default().into());
3396
3397 PopoverMenu::new("font-picker")
3398 .trigger(render_picker_trigger_button(
3399 "font_family_picker_trigger".into(),
3400 current_value.clone().into(),
3401 ))
3402 .menu(move |window, cx| {
3403 let file = file.clone();
3404 let current_value = current_value.clone();
3405
3406 Some(cx.new(move |cx| {
3407 font_picker(
3408 current_value.clone().into(),
3409 move |font_name, cx| {
3410 update_settings_file(file.clone(), cx, move |settings, _cx| {
3411 (field.write)(settings, Some(font_name.into()));
3412 })
3413 .log_err(); // todo(settings_ui) don't log err
3414 },
3415 window,
3416 cx,
3417 )
3418 }))
3419 })
3420 .anchor(gpui::Corner::TopLeft)
3421 .offset(gpui::Point {
3422 x: px(0.0),
3423 y: px(2.0),
3424 })
3425 .with_handle(ui::PopoverMenuHandle::default())
3426 .into_any_element()
3427}
3428
3429fn render_theme_picker(
3430 field: SettingField<settings::ThemeName>,
3431 file: SettingsUiFile,
3432 _metadata: Option<&SettingsFieldMetadata>,
3433 _window: &mut Window,
3434 cx: &mut App,
3435) -> AnyElement {
3436 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3437 let current_value = value
3438 .cloned()
3439 .map(|theme_name| theme_name.0.into())
3440 .unwrap_or_else(|| cx.theme().name.clone());
3441
3442 PopoverMenu::new("theme-picker")
3443 .trigger(render_picker_trigger_button(
3444 "theme_picker_trigger".into(),
3445 current_value.clone(),
3446 ))
3447 .menu(move |window, cx| {
3448 Some(cx.new(|cx| {
3449 let file = file.clone();
3450 let current_value = current_value.clone();
3451 theme_picker(
3452 current_value,
3453 move |theme_name, cx| {
3454 update_settings_file(file.clone(), cx, move |settings, _cx| {
3455 (field.write)(settings, Some(settings::ThemeName(theme_name.into())));
3456 })
3457 .log_err(); // todo(settings_ui) don't log err
3458 },
3459 window,
3460 cx,
3461 )
3462 }))
3463 })
3464 .anchor(gpui::Corner::TopLeft)
3465 .offset(gpui::Point {
3466 x: px(0.0),
3467 y: px(2.0),
3468 })
3469 .with_handle(ui::PopoverMenuHandle::default())
3470 .into_any_element()
3471}
3472
3473fn render_icon_theme_picker(
3474 field: SettingField<settings::IconThemeName>,
3475 file: SettingsUiFile,
3476 _metadata: Option<&SettingsFieldMetadata>,
3477 _window: &mut Window,
3478 cx: &mut App,
3479) -> AnyElement {
3480 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3481 let current_value = value
3482 .cloned()
3483 .map(|theme_name| theme_name.0.into())
3484 .unwrap_or_else(|| cx.theme().name.clone());
3485
3486 PopoverMenu::new("icon-theme-picker")
3487 .trigger(render_picker_trigger_button(
3488 "icon_theme_picker_trigger".into(),
3489 current_value.clone(),
3490 ))
3491 .menu(move |window, cx| {
3492 Some(cx.new(|cx| {
3493 let file = file.clone();
3494 let current_value = current_value.clone();
3495 icon_theme_picker(
3496 current_value,
3497 move |theme_name, cx| {
3498 update_settings_file(file.clone(), cx, move |settings, _cx| {
3499 (field.write)(
3500 settings,
3501 Some(settings::IconThemeName(theme_name.into())),
3502 );
3503 })
3504 .log_err(); // todo(settings_ui) don't log err
3505 },
3506 window,
3507 cx,
3508 )
3509 }))
3510 })
3511 .anchor(gpui::Corner::TopLeft)
3512 .offset(gpui::Point {
3513 x: px(0.0),
3514 y: px(2.0),
3515 })
3516 .with_handle(ui::PopoverMenuHandle::default())
3517 .into_any_element()
3518}
3519
3520#[cfg(test)]
3521pub mod test {
3522
3523 use super::*;
3524
3525 impl SettingsWindow {
3526 fn navbar_entry(&self) -> usize {
3527 self.navbar_entry
3528 }
3529 }
3530
3531 impl PartialEq for NavBarEntry {
3532 fn eq(&self, other: &Self) -> bool {
3533 self.title == other.title
3534 && self.is_root == other.is_root
3535 && self.expanded == other.expanded
3536 && self.page_index == other.page_index
3537 && self.item_index == other.item_index
3538 // ignoring focus_handle
3539 }
3540 }
3541
3542 pub fn register_settings(cx: &mut App) {
3543 settings::init(cx);
3544 theme::init(theme::LoadThemes::JustBase, cx);
3545 workspace::init_settings(cx);
3546 project::Project::init_settings(cx);
3547 language::init(cx);
3548 editor::init(cx);
3549 menu::init();
3550 }
3551
3552 fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
3553 let mut pages: Vec<SettingsPage> = Vec::new();
3554 let mut expanded_pages = Vec::new();
3555 let mut selected_idx = None;
3556 let mut index = 0;
3557 let mut in_expanded_section = false;
3558
3559 for mut line in input
3560 .lines()
3561 .map(|line| line.trim())
3562 .filter(|line| !line.is_empty())
3563 {
3564 if let Some(pre) = line.strip_suffix('*') {
3565 assert!(selected_idx.is_none(), "Only one selected entry allowed");
3566 selected_idx = Some(index);
3567 line = pre;
3568 }
3569 let (kind, title) = line.split_once(" ").unwrap();
3570 assert_eq!(kind.len(), 1);
3571 let kind = kind.chars().next().unwrap();
3572 if kind == 'v' {
3573 let page_idx = pages.len();
3574 expanded_pages.push(page_idx);
3575 pages.push(SettingsPage {
3576 title,
3577 items: vec![],
3578 });
3579 index += 1;
3580 in_expanded_section = true;
3581 } else if kind == '>' {
3582 pages.push(SettingsPage {
3583 title,
3584 items: vec![],
3585 });
3586 index += 1;
3587 in_expanded_section = false;
3588 } else if kind == '-' {
3589 pages
3590 .last_mut()
3591 .unwrap()
3592 .items
3593 .push(SettingsPageItem::SectionHeader(title));
3594 if selected_idx == Some(index) && !in_expanded_section {
3595 panic!("Items in unexpanded sections cannot be selected");
3596 }
3597 index += 1;
3598 } else {
3599 panic!(
3600 "Entries must start with one of 'v', '>', or '-'\n line: {}",
3601 line
3602 );
3603 }
3604 }
3605
3606 let mut settings_window = SettingsWindow {
3607 title_bar: None,
3608 original_window: None,
3609 worktree_root_dirs: HashMap::default(),
3610 files: Vec::default(),
3611 current_file: crate::SettingsUiFile::User,
3612 pages,
3613 search_bar: cx.new(|cx| Editor::single_line(window, cx)),
3614 navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
3615 navbar_entries: Vec::default(),
3616 navbar_scroll_handle: UniformListScrollHandle::default(),
3617 navbar_focus_subscriptions: vec![],
3618 filter_table: vec![],
3619 has_query: false,
3620 content_handles: vec![],
3621 search_task: None,
3622 sub_page_scroll_handle: ScrollHandle::new(),
3623 focus_handle: cx.focus_handle(),
3624 navbar_focus_handle: NonFocusableHandle::new(
3625 NAVBAR_CONTAINER_TAB_INDEX,
3626 false,
3627 window,
3628 cx,
3629 ),
3630 content_focus_handle: NonFocusableHandle::new(
3631 CONTENT_CONTAINER_TAB_INDEX,
3632 false,
3633 window,
3634 cx,
3635 ),
3636 files_focus_handle: cx.focus_handle(),
3637 search_index: None,
3638 list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
3639 };
3640
3641 settings_window.build_filter_table();
3642 settings_window.build_navbar(cx);
3643 for expanded_page_index in expanded_pages {
3644 for entry in &mut settings_window.navbar_entries {
3645 if entry.page_index == expanded_page_index && entry.is_root {
3646 entry.expanded = true;
3647 }
3648 }
3649 }
3650 settings_window
3651 }
3652
3653 #[track_caller]
3654 fn check_navbar_toggle(
3655 before: &'static str,
3656 toggle_page: &'static str,
3657 after: &'static str,
3658 window: &mut Window,
3659 cx: &mut App,
3660 ) {
3661 let mut settings_window = parse(before, window, cx);
3662 let toggle_page_idx = settings_window
3663 .pages
3664 .iter()
3665 .position(|page| page.title == toggle_page)
3666 .expect("page not found");
3667 let toggle_idx = settings_window
3668 .navbar_entries
3669 .iter()
3670 .position(|entry| entry.page_index == toggle_page_idx)
3671 .expect("page not found");
3672 settings_window.toggle_navbar_entry(toggle_idx);
3673
3674 let expected_settings_window = parse(after, window, cx);
3675
3676 pretty_assertions::assert_eq!(
3677 settings_window
3678 .visible_navbar_entries()
3679 .map(|(_, entry)| entry)
3680 .collect::<Vec<_>>(),
3681 expected_settings_window
3682 .visible_navbar_entries()
3683 .map(|(_, entry)| entry)
3684 .collect::<Vec<_>>(),
3685 );
3686 pretty_assertions::assert_eq!(
3687 settings_window.navbar_entries[settings_window.navbar_entry()],
3688 expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
3689 );
3690 }
3691
3692 macro_rules! check_navbar_toggle {
3693 ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
3694 #[gpui::test]
3695 fn $name(cx: &mut gpui::TestAppContext) {
3696 let window = cx.add_empty_window();
3697 window.update(|window, cx| {
3698 register_settings(cx);
3699 check_navbar_toggle($before, $toggle_page, $after, window, cx);
3700 });
3701 }
3702 };
3703 }
3704
3705 check_navbar_toggle!(
3706 navbar_basic_open,
3707 before: r"
3708 v General
3709 - General
3710 - Privacy*
3711 v Project
3712 - Project Settings
3713 ",
3714 toggle_page: "General",
3715 after: r"
3716 > General*
3717 v Project
3718 - Project Settings
3719 "
3720 );
3721
3722 check_navbar_toggle!(
3723 navbar_basic_close,
3724 before: r"
3725 > General*
3726 - General
3727 - Privacy
3728 v Project
3729 - Project Settings
3730 ",
3731 toggle_page: "General",
3732 after: r"
3733 v General*
3734 - General
3735 - Privacy
3736 v Project
3737 - Project Settings
3738 "
3739 );
3740
3741 check_navbar_toggle!(
3742 navbar_basic_second_root_entry_close,
3743 before: r"
3744 > General
3745 - General
3746 - Privacy
3747 v Project
3748 - Project Settings*
3749 ",
3750 toggle_page: "Project",
3751 after: r"
3752 > General
3753 > Project*
3754 "
3755 );
3756
3757 check_navbar_toggle!(
3758 navbar_toggle_subroot,
3759 before: r"
3760 v General Page
3761 - General
3762 - Privacy
3763 v Project
3764 - Worktree Settings Content*
3765 v AI
3766 - General
3767 > Appearance & Behavior
3768 ",
3769 toggle_page: "Project",
3770 after: r"
3771 v General Page
3772 - General
3773 - Privacy
3774 > Project*
3775 v AI
3776 - General
3777 > Appearance & Behavior
3778 "
3779 );
3780
3781 check_navbar_toggle!(
3782 navbar_toggle_close_propagates_selected_index,
3783 before: r"
3784 v General Page
3785 - General
3786 - Privacy
3787 v Project
3788 - Worktree Settings Content
3789 v AI
3790 - General*
3791 > Appearance & Behavior
3792 ",
3793 toggle_page: "General Page",
3794 after: r"
3795 > General Page*
3796 v Project
3797 - Worktree Settings Content
3798 v AI
3799 - General
3800 > Appearance & Behavior
3801 "
3802 );
3803
3804 check_navbar_toggle!(
3805 navbar_toggle_expand_propagates_selected_index,
3806 before: r"
3807 > General Page
3808 - General
3809 - Privacy
3810 v Project
3811 - Worktree Settings Content
3812 v AI
3813 - General*
3814 > Appearance & Behavior
3815 ",
3816 toggle_page: "General Page",
3817 after: r"
3818 v General Page*
3819 - General
3820 - Privacy
3821 v Project
3822 - Worktree Settings Content
3823 v AI
3824 - General
3825 > Appearance & Behavior
3826 "
3827 );
3828}