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