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