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 KeyContext, ListState, ReadGlobal as _, ScrollHandle, Stateful, Subscription, Task,
11 TitlebarOptions, UniformListScrollHandle, Window, WindowBounds, WindowHandle, WindowOptions,
12 actions, div, list, point, prelude::*, px, uniform_list,
13};
14use heck::ToTitleCase as _;
15use project::{Project, WorktreeId};
16use release_channel::ReleaseChannel;
17use schemars::JsonSchema;
18use serde::Deserialize;
19use settings::{Settings, SettingsContent, SettingsStore};
20use std::{
21 any::{Any, TypeId, type_name},
22 cell::RefCell,
23 collections::{HashMap, 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 settings::SettingsFile::Global => return None,
1143 })
1144 }
1145
1146 fn to_settings(&self) -> settings::SettingsFile {
1147 match self {
1148 SettingsUiFile::User => settings::SettingsFile::User,
1149 SettingsUiFile::Project(location) => settings::SettingsFile::Project(location.clone()),
1150 SettingsUiFile::Server(_) => settings::SettingsFile::Server,
1151 }
1152 }
1153
1154 fn mask(&self) -> FileMask {
1155 match self {
1156 SettingsUiFile::User => USER,
1157 SettingsUiFile::Project(_) => PROJECT,
1158 SettingsUiFile::Server(_) => SERVER,
1159 }
1160 }
1161}
1162
1163impl SettingsWindow {
1164 fn new(
1165 original_window: Option<WindowHandle<Workspace>>,
1166 window: &mut Window,
1167 cx: &mut Context<Self>,
1168 ) -> Self {
1169 let font_family_cache = theme::FontFamilyCache::global(cx);
1170
1171 cx.spawn(async move |this, cx| {
1172 font_family_cache.prefetch(cx).await;
1173 this.update(cx, |_, cx| {
1174 cx.notify();
1175 })
1176 })
1177 .detach();
1178
1179 let current_file = SettingsUiFile::User;
1180 let search_bar = cx.new(|cx| {
1181 let mut editor = Editor::single_line(window, cx);
1182 editor.set_placeholder_text("Search settings…", window, cx);
1183 editor
1184 });
1185
1186 cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
1187 let EditorEvent::Edited { transaction_id: _ } = event else {
1188 return;
1189 };
1190
1191 this.update_matches(cx);
1192 })
1193 .detach();
1194
1195 cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
1196 this.fetch_files(window, cx);
1197 cx.notify();
1198 })
1199 .detach();
1200
1201 cx.on_window_closed(|cx| {
1202 if let Some(existing_window) = cx
1203 .windows()
1204 .into_iter()
1205 .find_map(|window| window.downcast::<SettingsWindow>())
1206 && cx.windows().len() == 1
1207 {
1208 cx.update_window(*existing_window, |_, window, _| {
1209 window.remove_window();
1210 })
1211 .ok();
1212
1213 telemetry::event!("Settings Closed")
1214 }
1215 })
1216 .detach();
1217
1218 if let Some(app_state) = AppState::global(cx).upgrade() {
1219 for project in app_state
1220 .workspace_store
1221 .read(cx)
1222 .workspaces()
1223 .iter()
1224 .filter_map(|space| {
1225 space
1226 .read(cx)
1227 .ok()
1228 .map(|workspace| workspace.project().clone())
1229 })
1230 .collect::<Vec<_>>()
1231 {
1232 cx.subscribe_in(&project, window, Self::handle_project_event)
1233 .detach();
1234 }
1235 } else {
1236 log::error!("App state doesn't exist when creating a new settings window");
1237 }
1238
1239 let this_weak = cx.weak_entity();
1240 cx.observe_new::<Project>({
1241 move |_, window, cx| {
1242 let project = cx.entity();
1243 let Some(window) = window else {
1244 return;
1245 };
1246
1247 this_weak
1248 .update(cx, |_, cx| {
1249 cx.subscribe_in(&project, window, Self::handle_project_event)
1250 .detach();
1251 })
1252 .ok();
1253 }
1254 })
1255 .detach();
1256
1257 let title_bar = if !cfg!(target_os = "macos") {
1258 Some(cx.new(|cx| PlatformTitleBar::new("settings-title-bar", cx)))
1259 } else {
1260 None
1261 };
1262
1263 // high overdraw value so the list scrollbar len doesn't change too much
1264 let list_state = gpui::ListState::new(0, gpui::ListAlignment::Top, px(0.0)).measure_all();
1265 list_state.set_scroll_handler(|_, _, _| {});
1266
1267 let mut this = Self {
1268 title_bar,
1269 original_window,
1270
1271 worktree_root_dirs: HashMap::default(),
1272 files: vec![],
1273
1274 current_file: current_file,
1275 pages: vec![],
1276 navbar_entries: vec![],
1277 navbar_entry: 0,
1278 navbar_scroll_handle: UniformListScrollHandle::default(),
1279 search_bar,
1280 search_task: None,
1281 filter_table: vec![],
1282 has_query: false,
1283 content_handles: vec![],
1284 sub_page_scroll_handle: ScrollHandle::new(),
1285 focus_handle: cx.focus_handle(),
1286 navbar_focus_handle: NonFocusableHandle::new(
1287 NAVBAR_CONTAINER_TAB_INDEX,
1288 false,
1289 window,
1290 cx,
1291 ),
1292 navbar_focus_subscriptions: vec![],
1293 content_focus_handle: NonFocusableHandle::new(
1294 CONTENT_CONTAINER_TAB_INDEX,
1295 false,
1296 window,
1297 cx,
1298 ),
1299 files_focus_handle: cx
1300 .focus_handle()
1301 .tab_index(HEADER_CONTAINER_TAB_INDEX)
1302 .tab_stop(false),
1303 search_index: None,
1304 shown_errors: HashSet::default(),
1305 list_state,
1306 };
1307
1308 this.fetch_files(window, cx);
1309 this.build_ui(window, cx);
1310 this.build_search_index();
1311
1312 this.search_bar.update(cx, |editor, cx| {
1313 editor.focus_handle(cx).focus(window);
1314 });
1315
1316 this
1317 }
1318
1319 fn handle_project_event(
1320 &mut self,
1321 _: &Entity<Project>,
1322 event: &project::Event,
1323 window: &mut Window,
1324 cx: &mut Context<SettingsWindow>,
1325 ) {
1326 match event {
1327 project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded(_) => {
1328 cx.defer_in(window, |this, window, cx| {
1329 this.fetch_files(window, cx);
1330 });
1331 }
1332 _ => {}
1333 }
1334 }
1335
1336 fn toggle_navbar_entry(&mut self, nav_entry_index: usize) {
1337 // We can only toggle root entries
1338 if !self.navbar_entries[nav_entry_index].is_root {
1339 return;
1340 }
1341
1342 let expanded = &mut self.navbar_entries[nav_entry_index].expanded;
1343 *expanded = !*expanded;
1344 self.navbar_entry = nav_entry_index;
1345 self.reset_list_state();
1346 }
1347
1348 fn build_navbar(&mut self, cx: &App) {
1349 let mut navbar_entries = Vec::new();
1350
1351 for (page_index, page) in self.pages.iter().enumerate() {
1352 navbar_entries.push(NavBarEntry {
1353 title: page.title,
1354 is_root: true,
1355 expanded: false,
1356 page_index,
1357 item_index: None,
1358 focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1359 });
1360
1361 for (item_index, item) in page.items.iter().enumerate() {
1362 let SettingsPageItem::SectionHeader(title) = item else {
1363 continue;
1364 };
1365 navbar_entries.push(NavBarEntry {
1366 title,
1367 is_root: false,
1368 expanded: false,
1369 page_index,
1370 item_index: Some(item_index),
1371 focus_handle: cx.focus_handle().tab_index(0).tab_stop(true),
1372 });
1373 }
1374 }
1375
1376 self.navbar_entries = navbar_entries;
1377 }
1378
1379 fn setup_navbar_focus_subscriptions(
1380 &mut self,
1381 window: &mut Window,
1382 cx: &mut Context<SettingsWindow>,
1383 ) {
1384 let mut focus_subscriptions = Vec::new();
1385
1386 for entry_index in 0..self.navbar_entries.len() {
1387 let focus_handle = self.navbar_entries[entry_index].focus_handle.clone();
1388
1389 let subscription = cx.on_focus(
1390 &focus_handle,
1391 window,
1392 move |this: &mut SettingsWindow,
1393 window: &mut Window,
1394 cx: &mut Context<SettingsWindow>| {
1395 this.open_and_scroll_to_navbar_entry(entry_index, None, false, window, cx);
1396 },
1397 );
1398 focus_subscriptions.push(subscription);
1399 }
1400 self.navbar_focus_subscriptions = focus_subscriptions;
1401 }
1402
1403 fn visible_navbar_entries(&self) -> impl Iterator<Item = (usize, &NavBarEntry)> {
1404 let mut index = 0;
1405 let entries = &self.navbar_entries;
1406 let search_matches = &self.filter_table;
1407 let has_query = self.has_query;
1408 std::iter::from_fn(move || {
1409 while index < entries.len() {
1410 let entry = &entries[index];
1411 let included_in_search = if let Some(item_index) = entry.item_index {
1412 search_matches[entry.page_index][item_index]
1413 } else {
1414 search_matches[entry.page_index].iter().any(|b| *b)
1415 || search_matches[entry.page_index].is_empty()
1416 };
1417 if included_in_search {
1418 break;
1419 }
1420 index += 1;
1421 }
1422 if index >= self.navbar_entries.len() {
1423 return None;
1424 }
1425 let entry = &entries[index];
1426 let entry_index = index;
1427
1428 index += 1;
1429 if entry.is_root && !entry.expanded && !has_query {
1430 while index < entries.len() {
1431 if entries[index].is_root {
1432 break;
1433 }
1434 index += 1;
1435 }
1436 }
1437
1438 return Some((entry_index, entry));
1439 })
1440 }
1441
1442 fn filter_matches_to_file(&mut self) {
1443 let current_file = self.current_file.mask();
1444 for (page, page_filter) in std::iter::zip(&self.pages, &mut self.filter_table) {
1445 let mut header_index = 0;
1446 let mut any_found_since_last_header = true;
1447
1448 for (index, item) in page.items.iter().enumerate() {
1449 match item {
1450 SettingsPageItem::SectionHeader(_) => {
1451 if !any_found_since_last_header {
1452 page_filter[header_index] = false;
1453 }
1454 header_index = index;
1455 any_found_since_last_header = false;
1456 }
1457 SettingsPageItem::SettingItem(SettingItem { files, .. })
1458 | SettingsPageItem::SubPageLink(SubPageLink { files, .. })
1459 | SettingsPageItem::DynamicItem(DynamicItem {
1460 discriminant: SettingItem { files, .. },
1461 ..
1462 }) => {
1463 if !files.contains(current_file) {
1464 page_filter[index] = false;
1465 } else {
1466 any_found_since_last_header = true;
1467 }
1468 }
1469 }
1470 }
1471 if let Some(last_header) = page_filter.get_mut(header_index)
1472 && !any_found_since_last_header
1473 {
1474 *last_header = false;
1475 }
1476 }
1477 }
1478
1479 fn update_matches(&mut self, cx: &mut Context<SettingsWindow>) {
1480 self.search_task.take();
1481 let query = self.search_bar.read(cx).text(cx);
1482 if query.is_empty() || self.search_index.is_none() {
1483 for page in &mut self.filter_table {
1484 page.fill(true);
1485 }
1486 self.has_query = false;
1487 self.filter_matches_to_file();
1488 self.reset_list_state();
1489 cx.notify();
1490 return;
1491 }
1492
1493 let search_index = self.search_index.as_ref().unwrap().clone();
1494
1495 fn update_matches_inner(
1496 this: &mut SettingsWindow,
1497 search_index: &SearchIndex,
1498 match_indices: impl Iterator<Item = usize>,
1499 cx: &mut Context<SettingsWindow>,
1500 ) {
1501 for page in &mut this.filter_table {
1502 page.fill(false);
1503 }
1504
1505 for match_index in match_indices {
1506 let SearchItemKey {
1507 page_index,
1508 header_index,
1509 item_index,
1510 } = search_index.key_lut[match_index];
1511 let page = &mut this.filter_table[page_index];
1512 page[header_index] = true;
1513 page[item_index] = true;
1514 }
1515 this.has_query = true;
1516 this.filter_matches_to_file();
1517 this.open_first_nav_page();
1518 this.reset_list_state();
1519 cx.notify();
1520 }
1521
1522 self.search_task = Some(cx.spawn(async move |this, cx| {
1523 let bm25_task = cx.background_spawn({
1524 let search_index = search_index.clone();
1525 let max_results = search_index.key_lut.len();
1526 let query = query.clone();
1527 async move { search_index.bm25_engine.search(&query, max_results) }
1528 });
1529 let cancel_flag = std::sync::atomic::AtomicBool::new(false);
1530 let fuzzy_search_task = fuzzy::match_strings(
1531 search_index.fuzzy_match_candidates.as_slice(),
1532 &query,
1533 false,
1534 true,
1535 search_index.fuzzy_match_candidates.len(),
1536 &cancel_flag,
1537 cx.background_executor().clone(),
1538 );
1539
1540 let fuzzy_matches = fuzzy_search_task.await;
1541
1542 _ = this
1543 .update(cx, |this, cx| {
1544 // For tuning the score threshold
1545 // for fuzzy_match in &fuzzy_matches {
1546 // let SearchItemKey {
1547 // page_index,
1548 // header_index,
1549 // item_index,
1550 // } = search_index.key_lut[fuzzy_match.candidate_id];
1551 // let SettingsPageItem::SectionHeader(header) =
1552 // this.pages[page_index].items[header_index]
1553 // else {
1554 // continue;
1555 // };
1556 // let SettingsPageItem::SettingItem(SettingItem {
1557 // title, description, ..
1558 // }) = this.pages[page_index].items[item_index]
1559 // else {
1560 // continue;
1561 // };
1562 // let score = fuzzy_match.score;
1563 // eprint!("# {header} :: QUERY = {query} :: SCORE = {score}\n{title}\n{description}\n\n");
1564 // }
1565 update_matches_inner(
1566 this,
1567 search_index.as_ref(),
1568 fuzzy_matches
1569 .into_iter()
1570 // MAGIC NUMBER: Was found to have right balance between not too many weird matches, but also
1571 // flexible enough to catch misspellings and <4 letter queries
1572 // More flexible is good for us here because fuzzy matches will only be used for things that don't
1573 // match using bm25
1574 .take_while(|fuzzy_match| fuzzy_match.score >= 0.3)
1575 .map(|fuzzy_match| fuzzy_match.candidate_id),
1576 cx,
1577 );
1578 })
1579 .ok();
1580
1581 let bm25_matches = bm25_task.await;
1582
1583 _ = this
1584 .update(cx, |this, cx| {
1585 if bm25_matches.is_empty() {
1586 return;
1587 }
1588 update_matches_inner(
1589 this,
1590 search_index.as_ref(),
1591 bm25_matches
1592 .into_iter()
1593 .map(|bm25_match| bm25_match.document.id),
1594 cx,
1595 );
1596 })
1597 .ok();
1598
1599 cx.background_executor().timer(Duration::from_secs(1)).await;
1600 telemetry::event!("Settings Searched", query = query)
1601 }));
1602 }
1603
1604 fn build_filter_table(&mut self) {
1605 self.filter_table = self
1606 .pages
1607 .iter()
1608 .map(|page| vec![true; page.items.len()])
1609 .collect::<Vec<_>>();
1610 }
1611
1612 fn build_search_index(&mut self) {
1613 let mut key_lut: Vec<SearchItemKey> = vec![];
1614 let mut documents = Vec::default();
1615 let mut fuzzy_match_candidates = Vec::default();
1616
1617 fn push_candidates(
1618 fuzzy_match_candidates: &mut Vec<StringMatchCandidate>,
1619 key_index: usize,
1620 input: &str,
1621 ) {
1622 for word in input.split_ascii_whitespace() {
1623 fuzzy_match_candidates.push(StringMatchCandidate::new(key_index, word));
1624 }
1625 }
1626
1627 // PERF: We are currently searching all items even in project files
1628 // where many settings are filtered out, using the logic in filter_matches_to_file
1629 // we could only search relevant items based on the current file
1630 for (page_index, page) in self.pages.iter().enumerate() {
1631 let mut header_index = 0;
1632 let mut header_str = "";
1633 for (item_index, item) in page.items.iter().enumerate() {
1634 let key_index = key_lut.len();
1635 match item {
1636 SettingsPageItem::DynamicItem(DynamicItem {
1637 discriminant: item, ..
1638 })
1639 | SettingsPageItem::SettingItem(item) => {
1640 documents.push(bm25::Document {
1641 id: key_index,
1642 contents: [page.title, header_str, item.title, item.description]
1643 .join("\n"),
1644 });
1645 push_candidates(&mut fuzzy_match_candidates, key_index, item.title);
1646 push_candidates(&mut fuzzy_match_candidates, key_index, item.description);
1647 }
1648 SettingsPageItem::SectionHeader(header) => {
1649 documents.push(bm25::Document {
1650 id: key_index,
1651 contents: header.to_string(),
1652 });
1653 push_candidates(&mut fuzzy_match_candidates, key_index, header);
1654 header_index = item_index;
1655 header_str = *header;
1656 }
1657 SettingsPageItem::SubPageLink(sub_page_link) => {
1658 documents.push(bm25::Document {
1659 id: key_index,
1660 contents: [page.title, header_str, sub_page_link.title.as_ref()]
1661 .join("\n"),
1662 });
1663 push_candidates(
1664 &mut fuzzy_match_candidates,
1665 key_index,
1666 sub_page_link.title.as_ref(),
1667 );
1668 }
1669 }
1670 push_candidates(&mut fuzzy_match_candidates, key_index, page.title);
1671 push_candidates(&mut fuzzy_match_candidates, key_index, header_str);
1672
1673 key_lut.push(SearchItemKey {
1674 page_index,
1675 header_index,
1676 item_index,
1677 });
1678 }
1679 }
1680 let engine =
1681 bm25::SearchEngineBuilder::with_documents(bm25::Language::English, documents).build();
1682 self.search_index = Some(Arc::new(SearchIndex {
1683 bm25_engine: engine,
1684 key_lut,
1685 fuzzy_match_candidates,
1686 }));
1687 }
1688
1689 fn build_content_handles(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1690 self.content_handles = self
1691 .pages
1692 .iter()
1693 .map(|page| {
1694 std::iter::repeat_with(|| NonFocusableHandle::new(0, false, window, cx))
1695 .take(page.items.len())
1696 .collect()
1697 })
1698 .collect::<Vec<_>>();
1699 }
1700
1701 fn reset_list_state(&mut self) {
1702 // plus one for the title
1703 let mut visible_items_count = self.visible_page_items().count();
1704
1705 if visible_items_count > 0 {
1706 // show page title if page is non empty
1707 visible_items_count += 1;
1708 }
1709
1710 self.list_state.reset(visible_items_count);
1711 }
1712
1713 fn build_ui(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1714 if self.pages.is_empty() {
1715 self.pages = page_data::settings_data(cx);
1716 self.build_navbar(cx);
1717 self.setup_navbar_focus_subscriptions(window, cx);
1718 self.build_content_handles(window, cx);
1719 }
1720 sub_page_stack_mut().clear();
1721 // PERF: doesn't have to be rebuilt, can just be filled with true. pages is constant once it is built
1722 self.build_filter_table();
1723 self.reset_list_state();
1724 self.update_matches(cx);
1725
1726 cx.notify();
1727 }
1728
1729 fn fetch_files(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1730 self.worktree_root_dirs.clear();
1731 let prev_files = self.files.clone();
1732 let settings_store = cx.global::<SettingsStore>();
1733 let mut ui_files = vec![];
1734 let mut all_files = settings_store.get_all_files();
1735 if !all_files.contains(&settings::SettingsFile::User) {
1736 all_files.push(settings::SettingsFile::User);
1737 }
1738 for file in all_files {
1739 let Some(settings_ui_file) = SettingsUiFile::from_settings(file) else {
1740 continue;
1741 };
1742 if settings_ui_file.is_server() {
1743 continue;
1744 }
1745
1746 if let Some(worktree_id) = settings_ui_file.worktree_id() {
1747 let directory_name = all_projects(cx)
1748 .find_map(|project| project.read(cx).worktree_for_id(worktree_id, cx))
1749 .and_then(|worktree| worktree.read(cx).root_dir())
1750 .and_then(|root_dir| {
1751 root_dir
1752 .file_name()
1753 .map(|os_string| os_string.to_string_lossy().to_string())
1754 });
1755
1756 let Some(directory_name) = directory_name else {
1757 log::error!(
1758 "No directory name found for settings file at worktree ID: {}",
1759 worktree_id
1760 );
1761 continue;
1762 };
1763
1764 self.worktree_root_dirs.insert(worktree_id, directory_name);
1765 }
1766
1767 let focus_handle = prev_files
1768 .iter()
1769 .find_map(|(prev_file, handle)| {
1770 (prev_file == &settings_ui_file).then(|| handle.clone())
1771 })
1772 .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
1773 ui_files.push((settings_ui_file, focus_handle));
1774 }
1775
1776 ui_files.reverse();
1777
1778 let mut missing_worktrees = Vec::new();
1779
1780 for worktree in all_projects(cx)
1781 .flat_map(|project| project.read(cx).worktrees(cx))
1782 .filter(|tree| !self.worktree_root_dirs.contains_key(&tree.read(cx).id()))
1783 {
1784 let worktree = worktree.read(cx);
1785 let worktree_id = worktree.id();
1786 let Some(directory_name) = worktree.root_dir().and_then(|file| {
1787 file.file_name()
1788 .map(|os_string| os_string.to_string_lossy().to_string())
1789 }) else {
1790 continue;
1791 };
1792
1793 missing_worktrees.push((worktree_id, directory_name.clone()));
1794 let path = RelPath::empty().to_owned().into_arc();
1795
1796 let settings_ui_file = SettingsUiFile::Project((worktree_id, path));
1797
1798 let focus_handle = prev_files
1799 .iter()
1800 .find_map(|(prev_file, handle)| {
1801 (prev_file == &settings_ui_file).then(|| handle.clone())
1802 })
1803 .unwrap_or_else(|| cx.focus_handle().tab_index(0).tab_stop(true));
1804
1805 ui_files.push((settings_ui_file, focus_handle));
1806 }
1807
1808 self.worktree_root_dirs.extend(missing_worktrees);
1809
1810 self.files = ui_files;
1811 let current_file_still_exists = self
1812 .files
1813 .iter()
1814 .any(|(file, _)| file == &self.current_file);
1815 if !current_file_still_exists {
1816 self.change_file(0, window, cx);
1817 }
1818 }
1819
1820 fn open_navbar_entry_page(&mut self, navbar_entry: usize) {
1821 if !self.is_nav_entry_visible(navbar_entry) {
1822 self.open_first_nav_page();
1823 }
1824
1825 let is_new_page = self.navbar_entries[self.navbar_entry].page_index
1826 != self.navbar_entries[navbar_entry].page_index;
1827 self.navbar_entry = navbar_entry;
1828
1829 // We only need to reset visible items when updating matches
1830 // and selecting a new page
1831 if is_new_page {
1832 self.reset_list_state();
1833 }
1834
1835 sub_page_stack_mut().clear();
1836 }
1837
1838 fn open_first_nav_page(&mut self) {
1839 let Some(first_navbar_entry_index) = self.visible_navbar_entries().next().map(|e| e.0)
1840 else {
1841 return;
1842 };
1843 self.open_navbar_entry_page(first_navbar_entry_index);
1844 }
1845
1846 fn change_file(&mut self, ix: usize, window: &mut Window, cx: &mut Context<SettingsWindow>) {
1847 if ix >= self.files.len() {
1848 self.current_file = SettingsUiFile::User;
1849 self.build_ui(window, cx);
1850 return;
1851 }
1852
1853 if self.files[ix].0 == self.current_file {
1854 return;
1855 }
1856 self.current_file = self.files[ix].0.clone();
1857
1858 if let SettingsUiFile::Project((_, _)) = &self.current_file {
1859 telemetry::event!("Setting Project Clicked");
1860 }
1861
1862 self.build_ui(window, cx);
1863
1864 if self
1865 .visible_navbar_entries()
1866 .any(|(index, _)| index == self.navbar_entry)
1867 {
1868 self.open_and_scroll_to_navbar_entry(self.navbar_entry, None, true, window, cx);
1869 } else {
1870 self.open_first_nav_page();
1871 };
1872 }
1873
1874 fn render_files_header(
1875 &self,
1876 window: &mut Window,
1877 cx: &mut Context<SettingsWindow>,
1878 ) -> impl IntoElement {
1879 static OVERFLOW_LIMIT: usize = 1;
1880
1881 let file_button =
1882 |ix, file: &SettingsUiFile, focus_handle, cx: &mut Context<SettingsWindow>| {
1883 Button::new(
1884 ix,
1885 self.display_name(&file)
1886 .expect("Files should always have a name"),
1887 )
1888 .toggle_state(file == &self.current_file)
1889 .selected_style(ButtonStyle::Tinted(ui::TintColor::Accent))
1890 .track_focus(focus_handle)
1891 .on_click(cx.listener({
1892 let focus_handle = focus_handle.clone();
1893 move |this, _: &gpui::ClickEvent, window, cx| {
1894 this.change_file(ix, window, cx);
1895 focus_handle.focus(window);
1896 }
1897 }))
1898 };
1899
1900 let this = cx.entity();
1901
1902 h_flex()
1903 .w_full()
1904 .pb_4()
1905 .gap_1()
1906 .justify_between()
1907 .track_focus(&self.files_focus_handle)
1908 .tab_group()
1909 .tab_index(HEADER_GROUP_TAB_INDEX)
1910 .child(
1911 h_flex()
1912 .gap_1()
1913 .children(
1914 self.files.iter().enumerate().take(OVERFLOW_LIMIT).map(
1915 |(ix, (file, focus_handle))| file_button(ix, file, focus_handle, cx),
1916 ),
1917 )
1918 .when(self.files.len() > OVERFLOW_LIMIT, |div| {
1919 let selected_file_ix = self
1920 .files
1921 .iter()
1922 .enumerate()
1923 .skip(OVERFLOW_LIMIT)
1924 .find_map(|(ix, (file, _))| {
1925 if file == &self.current_file {
1926 Some(ix)
1927 } else {
1928 None
1929 }
1930 })
1931 .unwrap_or(OVERFLOW_LIMIT);
1932
1933 let (file, focus_handle) = &self.files[selected_file_ix];
1934
1935 div.child(file_button(selected_file_ix, file, focus_handle, cx))
1936 .when(self.files.len() > OVERFLOW_LIMIT + 1, |div| {
1937 div.child(
1938 DropdownMenu::new(
1939 "more-files",
1940 format!("+{}", self.files.len() - (OVERFLOW_LIMIT + 1)),
1941 ContextMenu::build(window, cx, move |mut menu, _, _| {
1942 for (mut ix, (file, focus_handle)) in self
1943 .files
1944 .iter()
1945 .enumerate()
1946 .skip(OVERFLOW_LIMIT + 1)
1947 {
1948 let (display_name, focus_handle) =
1949 if selected_file_ix == ix {
1950 ix = OVERFLOW_LIMIT;
1951 (
1952 self.display_name(&self.files[ix].0),
1953 self.files[ix].1.clone(),
1954 )
1955 } else {
1956 (
1957 self.display_name(&file),
1958 focus_handle.clone(),
1959 )
1960 };
1961
1962 menu = menu.entry(
1963 display_name
1964 .expect("Files should always have a name"),
1965 None,
1966 {
1967 let this = this.clone();
1968 move |window, cx| {
1969 this.update(cx, |this, cx| {
1970 this.change_file(ix, window, cx);
1971 });
1972 focus_handle.focus(window);
1973 }
1974 },
1975 );
1976 }
1977
1978 menu
1979 }),
1980 )
1981 .style(DropdownStyle::Subtle)
1982 .trigger_tooltip(Tooltip::text("View Other Projects"))
1983 .trigger_icon(IconName::ChevronDown)
1984 .attach(gpui::Corner::BottomLeft)
1985 .offset(gpui::Point {
1986 x: px(0.0),
1987 y: px(2.0),
1988 })
1989 .tab_index(0),
1990 )
1991 })
1992 }),
1993 )
1994 .child(
1995 Button::new("edit-in-json", "Edit in settings.json")
1996 .tab_index(0_isize)
1997 .style(ButtonStyle::OutlinedGhost)
1998 .on_click(cx.listener(|this, _, _, cx| {
1999 this.open_current_settings_file(cx);
2000 })),
2001 )
2002 }
2003
2004 pub(crate) fn display_name(&self, file: &SettingsUiFile) -> Option<String> {
2005 match file {
2006 SettingsUiFile::User => Some("User".to_string()),
2007 SettingsUiFile::Project((worktree_id, path)) => self
2008 .worktree_root_dirs
2009 .get(&worktree_id)
2010 .map(|directory_name| {
2011 let path_style = PathStyle::local();
2012 if path.is_empty() {
2013 directory_name.clone()
2014 } else {
2015 format!(
2016 "{}{}{}",
2017 directory_name,
2018 path_style.separator(),
2019 path.display(path_style)
2020 )
2021 }
2022 }),
2023 SettingsUiFile::Server(file) => Some(file.to_string()),
2024 }
2025 }
2026
2027 // TODO:
2028 // Reconsider this after preview launch
2029 // fn file_location_str(&self) -> String {
2030 // match &self.current_file {
2031 // SettingsUiFile::User => "settings.json".to_string(),
2032 // SettingsUiFile::Project((worktree_id, path)) => self
2033 // .worktree_root_dirs
2034 // .get(&worktree_id)
2035 // .map(|directory_name| {
2036 // let path_style = PathStyle::local();
2037 // let file_path = path.join(paths::local_settings_file_relative_path());
2038 // format!(
2039 // "{}{}{}",
2040 // directory_name,
2041 // path_style.separator(),
2042 // file_path.display(path_style)
2043 // )
2044 // })
2045 // .expect("Current file should always be present in root dir map"),
2046 // SettingsUiFile::Server(file) => file.to_string(),
2047 // }
2048 // }
2049
2050 fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
2051 h_flex()
2052 .py_1()
2053 .px_1p5()
2054 .mb_3()
2055 .gap_1p5()
2056 .rounded_sm()
2057 .bg(cx.theme().colors().editor_background)
2058 .border_1()
2059 .border_color(cx.theme().colors().border)
2060 .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
2061 .child(self.search_bar.clone())
2062 }
2063
2064 fn render_nav(
2065 &self,
2066 window: &mut Window,
2067 cx: &mut Context<SettingsWindow>,
2068 ) -> impl IntoElement {
2069 let visible_count = self.visible_navbar_entries().count();
2070
2071 let focus_keybind_label = if self
2072 .navbar_focus_handle
2073 .read(cx)
2074 .handle
2075 .contains_focused(window, cx)
2076 || self
2077 .visible_navbar_entries()
2078 .any(|(_, entry)| entry.focus_handle.is_focused(window))
2079 {
2080 "Focus Content"
2081 } else {
2082 "Focus Navbar"
2083 };
2084
2085 let mut key_context = KeyContext::new_with_defaults();
2086 key_context.add("NavigationMenu");
2087 key_context.add("menu");
2088 if self.search_bar.focus_handle(cx).is_focused(window) {
2089 key_context.add("search");
2090 }
2091
2092 v_flex()
2093 .key_context(key_context)
2094 .on_action(cx.listener(|this, _: &CollapseNavEntry, window, cx| {
2095 let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
2096 return;
2097 };
2098 let focused_entry_parent = this.root_entry_containing(focused_entry);
2099 if this.navbar_entries[focused_entry_parent].expanded {
2100 this.toggle_navbar_entry(focused_entry_parent);
2101 window.focus(&this.navbar_entries[focused_entry_parent].focus_handle);
2102 }
2103 cx.notify();
2104 }))
2105 .on_action(cx.listener(|this, _: &ExpandNavEntry, window, cx| {
2106 let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
2107 return;
2108 };
2109 if !this.navbar_entries[focused_entry].is_root {
2110 return;
2111 }
2112 if !this.navbar_entries[focused_entry].expanded {
2113 this.toggle_navbar_entry(focused_entry);
2114 }
2115 cx.notify();
2116 }))
2117 .on_action(
2118 cx.listener(|this, _: &FocusPreviousRootNavEntry, window, cx| {
2119 let entry_index = this
2120 .focused_nav_entry(window, cx)
2121 .unwrap_or(this.navbar_entry);
2122 let mut root_index = None;
2123 for (index, entry) in this.visible_navbar_entries() {
2124 if index >= entry_index {
2125 break;
2126 }
2127 if entry.is_root {
2128 root_index = Some(index);
2129 }
2130 }
2131 let Some(previous_root_index) = root_index else {
2132 return;
2133 };
2134 this.focus_and_scroll_to_nav_entry(previous_root_index, window, cx);
2135 }),
2136 )
2137 .on_action(cx.listener(|this, _: &FocusNextRootNavEntry, window, cx| {
2138 let entry_index = this
2139 .focused_nav_entry(window, cx)
2140 .unwrap_or(this.navbar_entry);
2141 let mut root_index = None;
2142 for (index, entry) in this.visible_navbar_entries() {
2143 if index <= entry_index {
2144 continue;
2145 }
2146 if entry.is_root {
2147 root_index = Some(index);
2148 break;
2149 }
2150 }
2151 let Some(next_root_index) = root_index else {
2152 return;
2153 };
2154 this.focus_and_scroll_to_nav_entry(next_root_index, window, cx);
2155 }))
2156 .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, cx| {
2157 if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
2158 this.focus_and_scroll_to_nav_entry(first_entry_index, window, cx);
2159 }
2160 }))
2161 .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, cx| {
2162 if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
2163 this.focus_and_scroll_to_nav_entry(last_entry_index, window, cx);
2164 }
2165 }))
2166 .on_action(cx.listener(|this, _: &FocusNextNavEntry, window, cx| {
2167 let entry_index = this
2168 .focused_nav_entry(window, cx)
2169 .unwrap_or(this.navbar_entry);
2170 let mut next_index = None;
2171 for (index, _) in this.visible_navbar_entries() {
2172 if index > entry_index {
2173 next_index = Some(index);
2174 break;
2175 }
2176 }
2177 let Some(next_entry_index) = next_index else {
2178 return;
2179 };
2180 this.open_and_scroll_to_navbar_entry(
2181 next_entry_index,
2182 Some(gpui::ScrollStrategy::Bottom),
2183 false,
2184 window,
2185 cx,
2186 );
2187 }))
2188 .on_action(cx.listener(|this, _: &FocusPreviousNavEntry, window, cx| {
2189 let entry_index = this
2190 .focused_nav_entry(window, cx)
2191 .unwrap_or(this.navbar_entry);
2192 let mut prev_index = None;
2193 for (index, _) in this.visible_navbar_entries() {
2194 if index >= entry_index {
2195 break;
2196 }
2197 prev_index = Some(index);
2198 }
2199 let Some(prev_entry_index) = prev_index else {
2200 return;
2201 };
2202 this.open_and_scroll_to_navbar_entry(
2203 prev_entry_index,
2204 Some(gpui::ScrollStrategy::Top),
2205 false,
2206 window,
2207 cx,
2208 );
2209 }))
2210 .w_56()
2211 .h_full()
2212 .p_2p5()
2213 .when(cfg!(target_os = "macos"), |this| this.pt_10())
2214 .flex_none()
2215 .border_r_1()
2216 .border_color(cx.theme().colors().border)
2217 .bg(cx.theme().colors().panel_background)
2218 .child(self.render_search(window, cx))
2219 .child(
2220 v_flex()
2221 .flex_1()
2222 .overflow_hidden()
2223 .track_focus(&self.navbar_focus_handle.focus_handle(cx))
2224 .tab_group()
2225 .tab_index(NAVBAR_GROUP_TAB_INDEX)
2226 .child(
2227 uniform_list(
2228 "settings-ui-nav-bar",
2229 visible_count + 1,
2230 cx.processor(move |this, range: Range<usize>, _, cx| {
2231 this.visible_navbar_entries()
2232 .skip(range.start.saturating_sub(1))
2233 .take(range.len())
2234 .map(|(entry_index, entry)| {
2235 TreeViewItem::new(
2236 ("settings-ui-navbar-entry", entry_index),
2237 entry.title,
2238 )
2239 .track_focus(&entry.focus_handle)
2240 .root_item(entry.is_root)
2241 .toggle_state(this.is_navbar_entry_selected(entry_index))
2242 .when(entry.is_root, |item| {
2243 item.expanded(entry.expanded || this.has_query)
2244 .on_toggle(cx.listener(
2245 move |this, _, window, cx| {
2246 this.toggle_navbar_entry(entry_index);
2247 window.focus(
2248 &this.navbar_entries[entry_index]
2249 .focus_handle,
2250 );
2251 cx.notify();
2252 },
2253 ))
2254 })
2255 .on_click({
2256 let category = this.pages[entry.page_index].title;
2257 let subcategory =
2258 (!entry.is_root).then_some(entry.title);
2259
2260 cx.listener(move |this, _, window, cx| {
2261 telemetry::event!(
2262 "Settings Navigation Clicked",
2263 category = category,
2264 subcategory = subcategory
2265 );
2266
2267 this.open_and_scroll_to_navbar_entry(
2268 entry_index,
2269 None,
2270 true,
2271 window,
2272 cx,
2273 );
2274 })
2275 })
2276 })
2277 .collect()
2278 }),
2279 )
2280 .size_full()
2281 .track_scroll(self.navbar_scroll_handle.clone()),
2282 )
2283 .vertical_scrollbar_for(self.navbar_scroll_handle.clone(), window, cx),
2284 )
2285 .child(
2286 h_flex()
2287 .w_full()
2288 .h_8()
2289 .p_2()
2290 .pb_0p5()
2291 .flex_shrink_0()
2292 .border_t_1()
2293 .border_color(cx.theme().colors().border_variant)
2294 .child(
2295 KeybindingHint::new(
2296 KeyBinding::for_action_in(
2297 &ToggleFocusNav,
2298 &self.navbar_focus_handle.focus_handle(cx),
2299 cx,
2300 ),
2301 cx.theme().colors().surface_background.opacity(0.5),
2302 )
2303 .suffix(focus_keybind_label),
2304 ),
2305 )
2306 }
2307
2308 fn open_and_scroll_to_navbar_entry(
2309 &mut self,
2310 navbar_entry_index: usize,
2311 scroll_strategy: Option<gpui::ScrollStrategy>,
2312 focus_content: bool,
2313 window: &mut Window,
2314 cx: &mut Context<Self>,
2315 ) {
2316 self.open_navbar_entry_page(navbar_entry_index);
2317 cx.notify();
2318
2319 let mut handle_to_focus = None;
2320
2321 if self.navbar_entries[navbar_entry_index].is_root
2322 || !self.is_nav_entry_visible(navbar_entry_index)
2323 {
2324 self.sub_page_scroll_handle
2325 .set_offset(point(px(0.), px(0.)));
2326 if focus_content {
2327 let Some(first_item_index) =
2328 self.visible_page_items().next().map(|(index, _)| index)
2329 else {
2330 return;
2331 };
2332 handle_to_focus = Some(self.focus_handle_for_content_element(first_item_index, cx));
2333 } else if !self.is_nav_entry_visible(navbar_entry_index) {
2334 let Some(first_visible_nav_entry_index) =
2335 self.visible_navbar_entries().next().map(|(index, _)| index)
2336 else {
2337 return;
2338 };
2339 self.focus_and_scroll_to_nav_entry(first_visible_nav_entry_index, window, cx);
2340 } else {
2341 handle_to_focus =
2342 Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2343 }
2344 } else {
2345 let entry_item_index = self.navbar_entries[navbar_entry_index]
2346 .item_index
2347 .expect("Non-root items should have an item index");
2348 self.scroll_to_content_item(entry_item_index, window, cx);
2349 if focus_content {
2350 handle_to_focus = Some(self.focus_handle_for_content_element(entry_item_index, cx));
2351 } else {
2352 handle_to_focus =
2353 Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2354 }
2355 }
2356
2357 if let Some(scroll_strategy) = scroll_strategy
2358 && let Some(logical_entry_index) = self
2359 .visible_navbar_entries()
2360 .into_iter()
2361 .position(|(index, _)| index == navbar_entry_index)
2362 {
2363 self.navbar_scroll_handle
2364 .scroll_to_item(logical_entry_index + 1, scroll_strategy);
2365 }
2366
2367 // Page scroll handle updates the active item index
2368 // in it's next paint call after using scroll_handle.scroll_to_top_of_item
2369 // The call after that updates the offset of the scroll handle. So to
2370 // ensure the scroll handle doesn't lag behind we need to render three frames
2371 // back to back.
2372 cx.on_next_frame(window, move |_, window, cx| {
2373 if let Some(handle) = handle_to_focus.as_ref() {
2374 window.focus(handle);
2375 }
2376
2377 cx.on_next_frame(window, |_, _, cx| {
2378 cx.notify();
2379 });
2380 cx.notify();
2381 });
2382 cx.notify();
2383 }
2384
2385 fn scroll_to_content_item(
2386 &self,
2387 content_item_index: usize,
2388 _window: &mut Window,
2389 cx: &mut Context<Self>,
2390 ) {
2391 let index = self
2392 .visible_page_items()
2393 .position(|(index, _)| index == content_item_index)
2394 .unwrap_or(0);
2395 if index == 0 {
2396 self.sub_page_scroll_handle
2397 .set_offset(point(px(0.), px(0.)));
2398 self.list_state.scroll_to(gpui::ListOffset {
2399 item_ix: 0,
2400 offset_in_item: px(0.),
2401 });
2402 return;
2403 }
2404 self.list_state.scroll_to(gpui::ListOffset {
2405 item_ix: index + 1,
2406 offset_in_item: px(0.),
2407 });
2408 cx.notify();
2409 }
2410
2411 fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
2412 self.visible_navbar_entries()
2413 .any(|(index, _)| index == nav_entry_index)
2414 }
2415
2416 fn focus_and_scroll_to_first_visible_nav_entry(
2417 &self,
2418 window: &mut Window,
2419 cx: &mut Context<Self>,
2420 ) {
2421 if let Some(nav_entry_index) = self.visible_navbar_entries().next().map(|(index, _)| index)
2422 {
2423 self.focus_and_scroll_to_nav_entry(nav_entry_index, window, cx);
2424 }
2425 }
2426
2427 fn focus_and_scroll_to_nav_entry(
2428 &self,
2429 nav_entry_index: usize,
2430 window: &mut Window,
2431 cx: &mut Context<Self>,
2432 ) {
2433 let Some(position) = self
2434 .visible_navbar_entries()
2435 .position(|(index, _)| index == nav_entry_index)
2436 else {
2437 return;
2438 };
2439 self.navbar_scroll_handle
2440 .scroll_to_item(position, gpui::ScrollStrategy::Top);
2441 window.focus(&self.navbar_entries[nav_entry_index].focus_handle);
2442 cx.notify();
2443 }
2444
2445 fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
2446 let page_idx = self.current_page_index();
2447
2448 self.current_page()
2449 .items
2450 .iter()
2451 .enumerate()
2452 .filter_map(move |(item_index, item)| {
2453 self.filter_table[page_idx][item_index].then_some((item_index, item))
2454 })
2455 }
2456
2457 fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
2458 let mut items = vec![];
2459 items.push(self.current_page().title.into());
2460 items.extend(
2461 sub_page_stack()
2462 .iter()
2463 .flat_map(|page| [page.section_header.into(), page.link.title.clone()]),
2464 );
2465
2466 let last = items.pop().unwrap();
2467 h_flex()
2468 .gap_1()
2469 .children(
2470 items
2471 .into_iter()
2472 .flat_map(|item| [item, "/".into()])
2473 .map(|item| Label::new(item).color(Color::Muted)),
2474 )
2475 .child(Label::new(last))
2476 }
2477
2478 fn render_empty_state(&self, search_query: SharedString) -> impl IntoElement {
2479 v_flex()
2480 .size_full()
2481 .items_center()
2482 .justify_center()
2483 .gap_1()
2484 .child(Label::new("No Results"))
2485 .child(
2486 Label::new(search_query)
2487 .size(LabelSize::Small)
2488 .color(Color::Muted),
2489 )
2490 }
2491
2492 fn render_page_items(
2493 &mut self,
2494 page_index: usize,
2495 _window: &mut Window,
2496 cx: &mut Context<SettingsWindow>,
2497 ) -> impl IntoElement {
2498 let mut page_content = v_flex().id("settings-ui-page").size_full();
2499
2500 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2501 let has_no_results = self.visible_page_items().next().is_none() && has_active_search;
2502
2503 if has_no_results {
2504 let search_query = self.search_bar.read(cx).text(cx);
2505 page_content = page_content.child(
2506 self.render_empty_state(format!("No settings match \"{}\"", search_query).into()),
2507 )
2508 } else {
2509 let last_non_header_index = self
2510 .visible_page_items()
2511 .filter_map(|(index, item)| {
2512 (!matches!(item, SettingsPageItem::SectionHeader(_))).then_some(index)
2513 })
2514 .last();
2515
2516 let root_nav_label = self
2517 .navbar_entries
2518 .iter()
2519 .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2520 .map(|entry| entry.title);
2521
2522 let list_content = list(
2523 self.list_state.clone(),
2524 cx.processor(move |this, index, window, cx| {
2525 if index == 0 {
2526 return div()
2527 .when(sub_page_stack().is_empty(), |this| {
2528 this.when_some(root_nav_label, |this, title| {
2529 this.child(
2530 Label::new(title).size(LabelSize::Large).mt_2().mb_3(),
2531 )
2532 })
2533 })
2534 .into_any_element();
2535 }
2536
2537 let mut visible_items = this.visible_page_items();
2538 let Some((actual_item_index, item)) = visible_items.nth(index - 1) else {
2539 return gpui::Empty.into_any_element();
2540 };
2541
2542 let no_bottom_border = visible_items
2543 .next()
2544 .map(|(_, item)| matches!(item, SettingsPageItem::SectionHeader(_)))
2545 .unwrap_or(false);
2546
2547 let is_last = Some(actual_item_index) == last_non_header_index;
2548
2549 let item_focus_handle =
2550 this.content_handles[page_index][actual_item_index].focus_handle(cx);
2551
2552 v_flex()
2553 .id(("settings-page-item", actual_item_index))
2554 .w_full()
2555 .min_w_0()
2556 .track_focus(&item_focus_handle)
2557 .child(item.render(
2558 this,
2559 actual_item_index,
2560 no_bottom_border || is_last,
2561 window,
2562 cx,
2563 ))
2564 .into_any_element()
2565 }),
2566 );
2567
2568 page_content = page_content.child(list_content.size_full())
2569 }
2570 page_content
2571 }
2572
2573 fn render_sub_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
2574 &self,
2575 items: Items,
2576 page_index: Option<usize>,
2577 window: &mut Window,
2578 cx: &mut Context<SettingsWindow>,
2579 ) -> impl IntoElement {
2580 let mut page_content = v_flex()
2581 .id("settings-ui-page")
2582 .size_full()
2583 .overflow_y_scroll()
2584 .track_scroll(&self.sub_page_scroll_handle);
2585
2586 let items: Vec<_> = items.collect();
2587 let items_len = items.len();
2588 let mut section_header = None;
2589
2590 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2591 let has_no_results = items_len == 0 && has_active_search;
2592
2593 if has_no_results {
2594 let search_query = self.search_bar.read(cx).text(cx);
2595 page_content = page_content.child(
2596 self.render_empty_state(format!("No settings match \"{}\"", search_query).into()),
2597 )
2598 } else {
2599 let last_non_header_index = items
2600 .iter()
2601 .enumerate()
2602 .rev()
2603 .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
2604 .map(|(index, _)| index);
2605
2606 let root_nav_label = self
2607 .navbar_entries
2608 .iter()
2609 .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2610 .map(|entry| entry.title);
2611
2612 page_content = page_content
2613 .when(sub_page_stack().is_empty(), |this| {
2614 this.when_some(root_nav_label, |this, title| {
2615 this.child(Label::new(title).size(LabelSize::Large).mt_2().mb_3())
2616 })
2617 })
2618 .children(items.clone().into_iter().enumerate().map(
2619 |(index, (actual_item_index, item))| {
2620 let no_bottom_border = items
2621 .get(index + 1)
2622 .map(|(_, next_item)| {
2623 matches!(next_item, SettingsPageItem::SectionHeader(_))
2624 })
2625 .unwrap_or(false);
2626 let is_last = Some(index) == last_non_header_index;
2627
2628 if let SettingsPageItem::SectionHeader(header) = item {
2629 section_header = Some(*header);
2630 }
2631 v_flex()
2632 .w_full()
2633 .min_w_0()
2634 .id(("settings-page-item", actual_item_index))
2635 .when_some(page_index, |element, page_index| {
2636 element.track_focus(
2637 &self.content_handles[page_index][actual_item_index]
2638 .focus_handle(cx),
2639 )
2640 })
2641 .child(item.render(
2642 self,
2643 actual_item_index,
2644 no_bottom_border || is_last,
2645 window,
2646 cx,
2647 ))
2648 },
2649 ))
2650 }
2651 page_content
2652 }
2653
2654 fn render_page(
2655 &mut self,
2656 window: &mut Window,
2657 cx: &mut Context<SettingsWindow>,
2658 ) -> impl IntoElement {
2659 let page_header;
2660 let page_content;
2661
2662 if sub_page_stack().is_empty() {
2663 page_header = self.render_files_header(window, cx).into_any_element();
2664
2665 page_content = self
2666 .render_page_items(self.current_page_index(), window, cx)
2667 .into_any_element();
2668 } else {
2669 page_header = h_flex()
2670 .ml_neg_1p5()
2671 .pb_4()
2672 .gap_1()
2673 .child(
2674 IconButton::new("back-btn", IconName::ArrowLeft)
2675 .icon_size(IconSize::Small)
2676 .shape(IconButtonShape::Square)
2677 .on_click(cx.listener(|this, _, _, cx| {
2678 this.pop_sub_page(cx);
2679 })),
2680 )
2681 .child(self.render_sub_page_breadcrumbs())
2682 .into_any_element();
2683
2684 let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
2685 page_content = (active_page_render_fn)(self, window, cx);
2686 }
2687
2688 let mut warning_banner = gpui::Empty.into_any_element();
2689 if let Some(error) =
2690 SettingsStore::global(cx).error_for_file(self.current_file.to_settings())
2691 {
2692 fn banner(
2693 label: &'static str,
2694 error: String,
2695 shown_errors: &mut HashSet<String>,
2696 cx: &mut Context<SettingsWindow>,
2697 ) -> impl IntoElement {
2698 if shown_errors.insert(error.clone()) {
2699 telemetry::event!("Settings Error Shown", label = label, error = &error);
2700 }
2701 Banner::new()
2702 .severity(Severity::Warning)
2703 .child(
2704 v_flex()
2705 .my_0p5()
2706 .gap_0p5()
2707 .child(Label::new(label))
2708 .child(Label::new(error).size(LabelSize::Small).color(Color::Muted)),
2709 )
2710 .action_slot(
2711 div().pr_1().child(
2712 Button::new("fix-in-json", "Fix in settings.json")
2713 .tab_index(0_isize)
2714 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
2715 .on_click(cx.listener(|this, _, _, cx| {
2716 this.open_current_settings_file(cx);
2717 })),
2718 ),
2719 )
2720 }
2721 let parse_error = error.parse_error();
2722 let parse_failed = parse_error.is_some();
2723 warning_banner = v_flex()
2724 .gap_2()
2725 .pb_4()
2726 .when_some(parse_error, |this, err| {
2727 this.child(banner(
2728 "Failed to load your settings. Some values may be incorrect and changes may be lost.",
2729 err,
2730 &mut self.shown_errors,
2731 cx,
2732 ))
2733 })
2734 .map(|this| match &error.migration_status {
2735 settings::MigrationStatus::Succeeded => this.child(banner(
2736 "Your settings are out of date, and need to be updated.",
2737 match &self.current_file {
2738 SettingsUiFile::User => "They can be automatically migrated to the latest version.",
2739 SettingsUiFile::Server(_) | SettingsUiFile::Project(_) => "They must be manually migrated to the latest version."
2740 }.to_string(),
2741 &mut self.shown_errors,
2742 cx,
2743 )),
2744 settings::MigrationStatus::Failed { error: err } if !parse_failed => this
2745 .child(banner(
2746 "Your settings file is out of date, automatic migration failed",
2747 err.clone(),
2748 &mut self.shown_errors,
2749 cx,
2750 )),
2751 _ => this,
2752 })
2753 .into_any_element()
2754 }
2755
2756 return v_flex()
2757 .id("settings-ui-page")
2758 .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
2759 if !sub_page_stack().is_empty() {
2760 window.focus_next();
2761 return;
2762 }
2763 for (logical_index, (actual_index, _)) in this.visible_page_items().enumerate() {
2764 let handle = this.content_handles[this.current_page_index()][actual_index]
2765 .focus_handle(cx);
2766 let mut offset = 1; // for page header
2767
2768 if let Some((_, next_item)) = this.visible_page_items().nth(logical_index + 1)
2769 && matches!(next_item, SettingsPageItem::SectionHeader(_))
2770 {
2771 offset += 1;
2772 }
2773 if handle.contains_focused(window, cx) {
2774 let next_logical_index = logical_index + offset + 1;
2775 this.list_state.scroll_to_reveal_item(next_logical_index);
2776 // We need to render the next item to ensure it's focus handle is in the element tree
2777 cx.on_next_frame(window, |_, window, cx| {
2778 cx.notify();
2779 cx.on_next_frame(window, |_, window, cx| {
2780 window.focus_next();
2781 cx.notify();
2782 });
2783 });
2784 cx.notify();
2785 return;
2786 }
2787 }
2788 window.focus_next();
2789 }))
2790 .on_action(cx.listener(|this, _: &menu::SelectPrevious, window, cx| {
2791 if !sub_page_stack().is_empty() {
2792 window.focus_prev();
2793 return;
2794 }
2795 let mut prev_was_header = false;
2796 for (logical_index, (actual_index, item)) in this.visible_page_items().enumerate() {
2797 let is_header = matches!(item, SettingsPageItem::SectionHeader(_));
2798 let handle = this.content_handles[this.current_page_index()][actual_index]
2799 .focus_handle(cx);
2800 let mut offset = 1; // for page header
2801
2802 if prev_was_header {
2803 offset -= 1;
2804 }
2805 if handle.contains_focused(window, cx) {
2806 let next_logical_index = logical_index + offset - 1;
2807 this.list_state.scroll_to_reveal_item(next_logical_index);
2808 // We need to render the next item to ensure it's focus handle is in the element tree
2809 cx.on_next_frame(window, |_, window, cx| {
2810 cx.notify();
2811 cx.on_next_frame(window, |_, window, cx| {
2812 window.focus_prev();
2813 cx.notify();
2814 });
2815 });
2816 cx.notify();
2817 return;
2818 }
2819 prev_was_header = is_header;
2820 }
2821 window.focus_prev();
2822 }))
2823 .when(sub_page_stack().is_empty(), |this| {
2824 this.vertical_scrollbar_for(self.list_state.clone(), window, cx)
2825 })
2826 .when(!sub_page_stack().is_empty(), |this| {
2827 this.vertical_scrollbar_for(self.sub_page_scroll_handle.clone(), window, cx)
2828 })
2829 .track_focus(&self.content_focus_handle.focus_handle(cx))
2830 .flex_1()
2831 .pt_6()
2832 .px_8()
2833 .bg(cx.theme().colors().editor_background)
2834 .child(page_header)
2835 .child(warning_banner)
2836 .child(
2837 div()
2838 .size_full()
2839 .tab_group()
2840 .tab_index(CONTENT_GROUP_TAB_INDEX)
2841 .child(page_content),
2842 );
2843 }
2844
2845 /// This function will create a new settings file if one doesn't exist
2846 /// if the current file is a project settings with a valid worktree id
2847 /// We do this because the settings ui allows initializing project settings
2848 fn open_current_settings_file(&mut self, cx: &mut Context<Self>) {
2849 match &self.current_file {
2850 SettingsUiFile::User => {
2851 let Some(original_window) = self.original_window else {
2852 return;
2853 };
2854 original_window
2855 .update(cx, |workspace, window, cx| {
2856 workspace
2857 .with_local_workspace(window, cx, |workspace, window, cx| {
2858 let create_task = workspace.project().update(cx, |project, cx| {
2859 project.find_or_create_worktree(
2860 paths::config_dir().as_path(),
2861 false,
2862 cx,
2863 )
2864 });
2865 let open_task = workspace.open_paths(
2866 vec![paths::settings_file().to_path_buf()],
2867 OpenOptions {
2868 visible: Some(OpenVisible::None),
2869 ..Default::default()
2870 },
2871 None,
2872 window,
2873 cx,
2874 );
2875
2876 cx.spawn_in(window, async move |workspace, cx| {
2877 create_task.await.ok();
2878 open_task.await;
2879
2880 workspace.update_in(cx, |_, window, cx| {
2881 window.activate_window();
2882 cx.notify();
2883 })
2884 })
2885 .detach();
2886 })
2887 .detach();
2888 })
2889 .ok();
2890 }
2891 SettingsUiFile::Project((worktree_id, path)) => {
2892 let settings_path = path.join(paths::local_settings_file_relative_path());
2893 let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
2894 return;
2895 };
2896
2897 let Some((worktree, corresponding_workspace)) = app_state
2898 .workspace_store
2899 .read(cx)
2900 .workspaces()
2901 .iter()
2902 .find_map(|workspace| {
2903 workspace
2904 .read_with(cx, |workspace, cx| {
2905 workspace
2906 .project()
2907 .read(cx)
2908 .worktree_for_id(*worktree_id, cx)
2909 })
2910 .ok()
2911 .flatten()
2912 .zip(Some(*workspace))
2913 })
2914 else {
2915 log::error!(
2916 "No corresponding workspace contains worktree id: {}",
2917 worktree_id
2918 );
2919
2920 return;
2921 };
2922
2923 let create_task = if worktree.read(cx).entry_for_path(&settings_path).is_some() {
2924 None
2925 } else {
2926 Some(worktree.update(cx, |tree, cx| {
2927 tree.create_entry(
2928 settings_path.clone(),
2929 false,
2930 Some("{\n\n}".as_bytes().to_vec()),
2931 cx,
2932 )
2933 }))
2934 };
2935
2936 let worktree_id = *worktree_id;
2937
2938 // TODO: move zed::open_local_file() APIs to this crate, and
2939 // re-implement the "initial_contents" behavior
2940 corresponding_workspace
2941 .update(cx, |_, window, cx| {
2942 cx.spawn_in(window, async move |workspace, cx| {
2943 if let Some(create_task) = create_task {
2944 create_task.await.ok()?;
2945 };
2946
2947 workspace
2948 .update_in(cx, |workspace, window, cx| {
2949 workspace.open_path(
2950 (worktree_id, settings_path.clone()),
2951 None,
2952 true,
2953 window,
2954 cx,
2955 )
2956 })
2957 .ok()?
2958 .await
2959 .log_err()?;
2960
2961 workspace
2962 .update_in(cx, |_, window, cx| {
2963 window.activate_window();
2964 cx.notify();
2965 })
2966 .ok();
2967
2968 Some(())
2969 })
2970 .detach();
2971 })
2972 .ok();
2973 }
2974 SettingsUiFile::Server(_) => {
2975 return;
2976 }
2977 };
2978 }
2979
2980 fn current_page_index(&self) -> usize {
2981 self.page_index_from_navbar_index(self.navbar_entry)
2982 }
2983
2984 fn current_page(&self) -> &SettingsPage {
2985 &self.pages[self.current_page_index()]
2986 }
2987
2988 fn page_index_from_navbar_index(&self, index: usize) -> usize {
2989 if self.navbar_entries.is_empty() {
2990 return 0;
2991 }
2992
2993 self.navbar_entries[index].page_index
2994 }
2995
2996 fn is_navbar_entry_selected(&self, ix: usize) -> bool {
2997 ix == self.navbar_entry
2998 }
2999
3000 fn push_sub_page(
3001 &mut self,
3002 sub_page_link: SubPageLink,
3003 section_header: &'static str,
3004 cx: &mut Context<SettingsWindow>,
3005 ) {
3006 sub_page_stack_mut().push(SubPage {
3007 link: sub_page_link,
3008 section_header,
3009 });
3010 cx.notify();
3011 }
3012
3013 fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
3014 sub_page_stack_mut().pop();
3015 cx.notify();
3016 }
3017
3018 fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
3019 if let Some((_, handle)) = self.files.get(index) {
3020 handle.focus(window);
3021 }
3022 }
3023
3024 fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
3025 if self.files_focus_handle.contains_focused(window, cx)
3026 && let Some(index) = self
3027 .files
3028 .iter()
3029 .position(|(_, handle)| handle.is_focused(window))
3030 {
3031 return index;
3032 }
3033 if let Some(current_file_index) = self
3034 .files
3035 .iter()
3036 .position(|(file, _)| file == &self.current_file)
3037 {
3038 return current_file_index;
3039 }
3040 0
3041 }
3042
3043 fn focus_handle_for_content_element(
3044 &self,
3045 actual_item_index: usize,
3046 cx: &Context<Self>,
3047 ) -> FocusHandle {
3048 let page_index = self.current_page_index();
3049 self.content_handles[page_index][actual_item_index].focus_handle(cx)
3050 }
3051
3052 fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
3053 if !self
3054 .navbar_focus_handle
3055 .focus_handle(cx)
3056 .contains_focused(window, cx)
3057 {
3058 return None;
3059 }
3060 for (index, entry) in self.navbar_entries.iter().enumerate() {
3061 if entry.focus_handle.is_focused(window) {
3062 return Some(index);
3063 }
3064 }
3065 None
3066 }
3067
3068 fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
3069 let mut index = Some(nav_entry_index);
3070 while let Some(prev_index) = index
3071 && !self.navbar_entries[prev_index].is_root
3072 {
3073 index = prev_index.checked_sub(1);
3074 }
3075 return index.expect("No root entry found");
3076 }
3077}
3078
3079impl Render for SettingsWindow {
3080 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3081 let ui_font = theme::setup_ui_font(window, cx);
3082
3083 client_side_decorations(
3084 v_flex()
3085 .text_color(cx.theme().colors().text)
3086 .size_full()
3087 .children(self.title_bar.clone())
3088 .child(
3089 div()
3090 .id("settings-window")
3091 .key_context("SettingsWindow")
3092 .track_focus(&self.focus_handle)
3093 .on_action(cx.listener(|this, _: &OpenCurrentFile, _, cx| {
3094 this.open_current_settings_file(cx);
3095 }))
3096 .on_action(|_: &Minimize, window, _cx| {
3097 window.minimize_window();
3098 })
3099 .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
3100 this.search_bar.focus_handle(cx).focus(window);
3101 }))
3102 .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
3103 if this
3104 .navbar_focus_handle
3105 .focus_handle(cx)
3106 .contains_focused(window, cx)
3107 {
3108 this.open_and_scroll_to_navbar_entry(
3109 this.navbar_entry,
3110 None,
3111 true,
3112 window,
3113 cx,
3114 );
3115 } else {
3116 this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
3117 }
3118 }))
3119 .on_action(cx.listener(
3120 |this, FocusFile(file_index): &FocusFile, window, _| {
3121 this.focus_file_at_index(*file_index as usize, window);
3122 },
3123 ))
3124 .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
3125 let next_index = usize::min(
3126 this.focused_file_index(window, cx) + 1,
3127 this.files.len().saturating_sub(1),
3128 );
3129 this.focus_file_at_index(next_index, window);
3130 }))
3131 .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
3132 let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
3133 this.focus_file_at_index(prev_index, window);
3134 }))
3135 .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
3136 if this
3137 .search_bar
3138 .focus_handle(cx)
3139 .contains_focused(window, cx)
3140 {
3141 this.focus_and_scroll_to_first_visible_nav_entry(window, cx);
3142 } else {
3143 window.focus_next();
3144 }
3145 }))
3146 .on_action(|_: &menu::SelectPrevious, window, _| {
3147 window.focus_prev();
3148 })
3149 .flex()
3150 .flex_row()
3151 .flex_1()
3152 .min_h_0()
3153 .font(ui_font)
3154 .bg(cx.theme().colors().background)
3155 .text_color(cx.theme().colors().text)
3156 .when(!cfg!(target_os = "macos"), |this| {
3157 this.border_t_1().border_color(cx.theme().colors().border)
3158 })
3159 .child(self.render_nav(window, cx))
3160 .child(self.render_page(window, cx)),
3161 ),
3162 window,
3163 cx,
3164 )
3165 }
3166}
3167
3168fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
3169 workspace::AppState::global(cx)
3170 .upgrade()
3171 .map(|app_state| {
3172 app_state
3173 .workspace_store
3174 .read(cx)
3175 .workspaces()
3176 .iter()
3177 .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
3178 })
3179 .into_iter()
3180 .flatten()
3181}
3182
3183fn update_settings_file(
3184 file: SettingsUiFile,
3185 file_name: Option<&'static str>,
3186 cx: &mut App,
3187 update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
3188) -> Result<()> {
3189 telemetry::event!("Settings Change", setting = file_name, type = file.setting_type());
3190
3191 match file {
3192 SettingsUiFile::Project((worktree_id, rel_path)) => {
3193 let rel_path = rel_path.join(paths::local_settings_file_relative_path());
3194 let Some((worktree, project)) = all_projects(cx).find_map(|project| {
3195 project
3196 .read(cx)
3197 .worktree_for_id(worktree_id, cx)
3198 .zip(Some(project))
3199 }) else {
3200 anyhow::bail!("Could not find project with worktree id: {}", worktree_id);
3201 };
3202
3203 project.update(cx, |project, cx| {
3204 let task = if project.contains_local_settings_file(worktree_id, &rel_path, cx) {
3205 None
3206 } else {
3207 Some(worktree.update(cx, |worktree, cx| {
3208 worktree.create_entry(rel_path.clone(), false, None, cx)
3209 }))
3210 };
3211
3212 cx.spawn(async move |project, cx| {
3213 if let Some(task) = task
3214 && task.await.is_err()
3215 {
3216 return;
3217 };
3218
3219 project
3220 .update(cx, |project, cx| {
3221 project.update_local_settings_file(worktree_id, rel_path, cx, update);
3222 })
3223 .ok();
3224 })
3225 .detach();
3226 });
3227
3228 return Ok(());
3229 }
3230 SettingsUiFile::User => {
3231 // todo(settings_ui) error?
3232 SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
3233 Ok(())
3234 }
3235 SettingsUiFile::Server(_) => unimplemented!(),
3236 }
3237}
3238
3239fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
3240 field: SettingField<T>,
3241 file: SettingsUiFile,
3242 metadata: Option<&SettingsFieldMetadata>,
3243 _window: &mut Window,
3244 cx: &mut App,
3245) -> AnyElement {
3246 let (_, initial_text) =
3247 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3248 let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
3249
3250 SettingsInputField::new()
3251 .tab_index(0)
3252 .when_some(initial_text, |editor, text| {
3253 editor.with_initial_text(text.as_ref().to_string())
3254 })
3255 .when_some(
3256 metadata.and_then(|metadata| metadata.placeholder),
3257 |editor, placeholder| editor.with_placeholder(placeholder),
3258 )
3259 .on_confirm({
3260 move |new_text, cx| {
3261 update_settings_file(file.clone(), field.json_path, cx, move |settings, _cx| {
3262 (field.write)(settings, new_text.map(Into::into));
3263 })
3264 .log_err(); // todo(settings_ui) don't log err
3265 }
3266 })
3267 .into_any_element()
3268}
3269
3270fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
3271 field: SettingField<B>,
3272 file: SettingsUiFile,
3273 _metadata: Option<&SettingsFieldMetadata>,
3274 _window: &mut Window,
3275 cx: &mut App,
3276) -> AnyElement {
3277 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3278
3279 let toggle_state = if value.copied().map_or(false, Into::into) {
3280 ToggleState::Selected
3281 } else {
3282 ToggleState::Unselected
3283 };
3284
3285 Switch::new("toggle_button", toggle_state)
3286 .tab_index(0_isize)
3287 .color(SwitchColor::Accent)
3288 .on_click({
3289 move |state, _window, cx| {
3290 telemetry::event!("Settings Change", setting = field.json_path, type = file.setting_type());
3291
3292 let state = *state == ui::ToggleState::Selected;
3293 update_settings_file(file.clone(), field.json_path, cx, move |settings, _cx| {
3294 (field.write)(settings, Some(state.into()));
3295 })
3296 .log_err(); // todo(settings_ui) don't log err
3297 }
3298 })
3299 .into_any_element()
3300}
3301
3302fn render_number_field<T: NumberFieldType + Send + Sync>(
3303 field: SettingField<T>,
3304 file: SettingsUiFile,
3305 _metadata: Option<&SettingsFieldMetadata>,
3306 window: &mut Window,
3307 cx: &mut App,
3308) -> AnyElement {
3309 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3310 let value = value.copied().unwrap_or_else(T::min_value);
3311 NumberField::new("numeric_stepper", value, window, cx)
3312 .on_change({
3313 move |value, _window, cx| {
3314 let value = *value;
3315 update_settings_file(file.clone(), field.json_path, cx, move |settings, _cx| {
3316 (field.write)(settings, Some(value));
3317 })
3318 .log_err(); // todo(settings_ui) don't log err
3319 }
3320 })
3321 .into_any_element()
3322}
3323
3324fn render_dropdown<T>(
3325 field: SettingField<T>,
3326 file: SettingsUiFile,
3327 metadata: Option<&SettingsFieldMetadata>,
3328 window: &mut Window,
3329 cx: &mut App,
3330) -> AnyElement
3331where
3332 T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
3333{
3334 let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
3335 let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
3336 let should_do_titlecase = metadata
3337 .and_then(|metadata| metadata.should_do_titlecase)
3338 .unwrap_or(true);
3339
3340 let (_, current_value) =
3341 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3342 let current_value = current_value.copied().unwrap_or(variants()[0]);
3343
3344 let current_value_label =
3345 labels()[variants().iter().position(|v| *v == current_value).unwrap()];
3346
3347 DropdownMenu::new(
3348 "dropdown",
3349 if should_do_titlecase {
3350 current_value_label.to_title_case()
3351 } else {
3352 current_value_label.to_string()
3353 },
3354 window.use_state(cx, |window, cx| {
3355 ContextMenu::new(window, cx, move |mut menu, _, _| {
3356 for (&value, &label) in std::iter::zip(variants(), labels()) {
3357 let file = file.clone();
3358 menu = menu.toggleable_entry(
3359 if should_do_titlecase {
3360 label.to_title_case()
3361 } else {
3362 label.to_string()
3363 },
3364 value == current_value,
3365 IconPosition::End,
3366 None,
3367 move |_, cx| {
3368 if value == current_value {
3369 return;
3370 }
3371 update_settings_file(
3372 file.clone(),
3373 field.json_path,
3374 cx,
3375 move |settings, _cx| {
3376 (field.write)(settings, Some(value));
3377 },
3378 )
3379 .log_err(); // todo(settings_ui) don't log err
3380 },
3381 );
3382 }
3383 menu
3384 })
3385 }),
3386 )
3387 .tab_index(0)
3388 .trigger_size(ButtonSize::Medium)
3389 .style(DropdownStyle::Outlined)
3390 .offset(gpui::Point {
3391 x: px(0.0),
3392 y: px(2.0),
3393 })
3394 .into_any_element()
3395}
3396
3397fn render_picker_trigger_button(id: SharedString, label: SharedString) -> Button {
3398 Button::new(id, label)
3399 .tab_index(0_isize)
3400 .style(ButtonStyle::Outlined)
3401 .size(ButtonSize::Medium)
3402 .icon(IconName::ChevronUpDown)
3403 .icon_color(Color::Muted)
3404 .icon_size(IconSize::Small)
3405 .icon_position(IconPosition::End)
3406}
3407
3408fn render_font_picker(
3409 field: SettingField<settings::FontFamilyName>,
3410 file: SettingsUiFile,
3411 _metadata: Option<&SettingsFieldMetadata>,
3412 _window: &mut Window,
3413 cx: &mut App,
3414) -> AnyElement {
3415 let current_value = SettingsStore::global(cx)
3416 .get_value_from_file(file.to_settings(), field.pick)
3417 .1
3418 .cloned()
3419 .unwrap_or_else(|| SharedString::default().into());
3420
3421 PopoverMenu::new("font-picker")
3422 .trigger(render_picker_trigger_button(
3423 "font_family_picker_trigger".into(),
3424 current_value.clone().into(),
3425 ))
3426 .menu(move |window, cx| {
3427 let file = file.clone();
3428 let current_value = current_value.clone();
3429
3430 Some(cx.new(move |cx| {
3431 font_picker(
3432 current_value.clone().into(),
3433 move |font_name, cx| {
3434 update_settings_file(
3435 file.clone(),
3436 field.json_path,
3437 cx,
3438 move |settings, _cx| {
3439 (field.write)(settings, Some(font_name.into()));
3440 },
3441 )
3442 .log_err(); // todo(settings_ui) don't log err
3443 },
3444 window,
3445 cx,
3446 )
3447 }))
3448 })
3449 .anchor(gpui::Corner::TopLeft)
3450 .offset(gpui::Point {
3451 x: px(0.0),
3452 y: px(2.0),
3453 })
3454 .with_handle(ui::PopoverMenuHandle::default())
3455 .into_any_element()
3456}
3457
3458fn render_theme_picker(
3459 field: SettingField<settings::ThemeName>,
3460 file: SettingsUiFile,
3461 _metadata: Option<&SettingsFieldMetadata>,
3462 _window: &mut Window,
3463 cx: &mut App,
3464) -> AnyElement {
3465 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3466 let current_value = value
3467 .cloned()
3468 .map(|theme_name| theme_name.0.into())
3469 .unwrap_or_else(|| cx.theme().name.clone());
3470
3471 PopoverMenu::new("theme-picker")
3472 .trigger(render_picker_trigger_button(
3473 "theme_picker_trigger".into(),
3474 current_value.clone(),
3475 ))
3476 .menu(move |window, cx| {
3477 Some(cx.new(|cx| {
3478 let file = file.clone();
3479 let current_value = current_value.clone();
3480 theme_picker(
3481 current_value,
3482 move |theme_name, cx| {
3483 update_settings_file(
3484 file.clone(),
3485 field.json_path,
3486 cx,
3487 move |settings, _cx| {
3488 (field.write)(
3489 settings,
3490 Some(settings::ThemeName(theme_name.into())),
3491 );
3492 },
3493 )
3494 .log_err(); // todo(settings_ui) don't log err
3495 },
3496 window,
3497 cx,
3498 )
3499 }))
3500 })
3501 .anchor(gpui::Corner::TopLeft)
3502 .offset(gpui::Point {
3503 x: px(0.0),
3504 y: px(2.0),
3505 })
3506 .with_handle(ui::PopoverMenuHandle::default())
3507 .into_any_element()
3508}
3509
3510fn render_icon_theme_picker(
3511 field: SettingField<settings::IconThemeName>,
3512 file: SettingsUiFile,
3513 _metadata: Option<&SettingsFieldMetadata>,
3514 _window: &mut Window,
3515 cx: &mut App,
3516) -> AnyElement {
3517 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3518 let current_value = value
3519 .cloned()
3520 .map(|theme_name| theme_name.0.into())
3521 .unwrap_or_else(|| cx.theme().name.clone());
3522
3523 PopoverMenu::new("icon-theme-picker")
3524 .trigger(render_picker_trigger_button(
3525 "icon_theme_picker_trigger".into(),
3526 current_value.clone(),
3527 ))
3528 .menu(move |window, cx| {
3529 Some(cx.new(|cx| {
3530 let file = file.clone();
3531 let current_value = current_value.clone();
3532 icon_theme_picker(
3533 current_value,
3534 move |theme_name, cx| {
3535 update_settings_file(
3536 file.clone(),
3537 field.json_path,
3538 cx,
3539 move |settings, _cx| {
3540 (field.write)(
3541 settings,
3542 Some(settings::IconThemeName(theme_name.into())),
3543 );
3544 },
3545 )
3546 .log_err(); // todo(settings_ui) don't log err
3547 },
3548 window,
3549 cx,
3550 )
3551 }))
3552 })
3553 .anchor(gpui::Corner::TopLeft)
3554 .offset(gpui::Point {
3555 x: px(0.0),
3556 y: px(2.0),
3557 })
3558 .with_handle(ui::PopoverMenuHandle::default())
3559 .into_any_element()
3560}
3561
3562#[cfg(test)]
3563pub mod test {
3564
3565 use super::*;
3566
3567 impl SettingsWindow {
3568 fn navbar_entry(&self) -> usize {
3569 self.navbar_entry
3570 }
3571 }
3572
3573 impl PartialEq for NavBarEntry {
3574 fn eq(&self, other: &Self) -> bool {
3575 self.title == other.title
3576 && self.is_root == other.is_root
3577 && self.expanded == other.expanded
3578 && self.page_index == other.page_index
3579 && self.item_index == other.item_index
3580 // ignoring focus_handle
3581 }
3582 }
3583
3584 pub fn register_settings(cx: &mut App) {
3585 settings::init(cx);
3586 theme::init(theme::LoadThemes::JustBase, cx);
3587 workspace::init_settings(cx);
3588 project::Project::init_settings(cx);
3589 language::init(cx);
3590 editor::init(cx);
3591 menu::init();
3592 }
3593
3594 fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
3595 let mut pages: Vec<SettingsPage> = Vec::new();
3596 let mut expanded_pages = Vec::new();
3597 let mut selected_idx = None;
3598 let mut index = 0;
3599 let mut in_expanded_section = false;
3600
3601 for mut line in input
3602 .lines()
3603 .map(|line| line.trim())
3604 .filter(|line| !line.is_empty())
3605 {
3606 if let Some(pre) = line.strip_suffix('*') {
3607 assert!(selected_idx.is_none(), "Only one selected entry allowed");
3608 selected_idx = Some(index);
3609 line = pre;
3610 }
3611 let (kind, title) = line.split_once(" ").unwrap();
3612 assert_eq!(kind.len(), 1);
3613 let kind = kind.chars().next().unwrap();
3614 if kind == 'v' {
3615 let page_idx = pages.len();
3616 expanded_pages.push(page_idx);
3617 pages.push(SettingsPage {
3618 title,
3619 items: vec![],
3620 });
3621 index += 1;
3622 in_expanded_section = true;
3623 } else if kind == '>' {
3624 pages.push(SettingsPage {
3625 title,
3626 items: vec![],
3627 });
3628 index += 1;
3629 in_expanded_section = false;
3630 } else if kind == '-' {
3631 pages
3632 .last_mut()
3633 .unwrap()
3634 .items
3635 .push(SettingsPageItem::SectionHeader(title));
3636 if selected_idx == Some(index) && !in_expanded_section {
3637 panic!("Items in unexpanded sections cannot be selected");
3638 }
3639 index += 1;
3640 } else {
3641 panic!(
3642 "Entries must start with one of 'v', '>', or '-'\n line: {}",
3643 line
3644 );
3645 }
3646 }
3647
3648 let mut settings_window = SettingsWindow {
3649 title_bar: None,
3650 original_window: None,
3651 worktree_root_dirs: HashMap::default(),
3652 files: Vec::default(),
3653 current_file: crate::SettingsUiFile::User,
3654 pages,
3655 search_bar: cx.new(|cx| Editor::single_line(window, cx)),
3656 navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
3657 navbar_entries: Vec::default(),
3658 navbar_scroll_handle: UniformListScrollHandle::default(),
3659 navbar_focus_subscriptions: vec![],
3660 filter_table: vec![],
3661 has_query: false,
3662 content_handles: vec![],
3663 search_task: None,
3664 sub_page_scroll_handle: ScrollHandle::new(),
3665 focus_handle: cx.focus_handle(),
3666 navbar_focus_handle: NonFocusableHandle::new(
3667 NAVBAR_CONTAINER_TAB_INDEX,
3668 false,
3669 window,
3670 cx,
3671 ),
3672 content_focus_handle: NonFocusableHandle::new(
3673 CONTENT_CONTAINER_TAB_INDEX,
3674 false,
3675 window,
3676 cx,
3677 ),
3678 files_focus_handle: cx.focus_handle(),
3679 search_index: None,
3680 list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
3681 shown_errors: HashSet::default(),
3682 };
3683
3684 settings_window.build_filter_table();
3685 settings_window.build_navbar(cx);
3686 for expanded_page_index in expanded_pages {
3687 for entry in &mut settings_window.navbar_entries {
3688 if entry.page_index == expanded_page_index && entry.is_root {
3689 entry.expanded = true;
3690 }
3691 }
3692 }
3693 settings_window
3694 }
3695
3696 #[track_caller]
3697 fn check_navbar_toggle(
3698 before: &'static str,
3699 toggle_page: &'static str,
3700 after: &'static str,
3701 window: &mut Window,
3702 cx: &mut App,
3703 ) {
3704 let mut settings_window = parse(before, window, cx);
3705 let toggle_page_idx = settings_window
3706 .pages
3707 .iter()
3708 .position(|page| page.title == toggle_page)
3709 .expect("page not found");
3710 let toggle_idx = settings_window
3711 .navbar_entries
3712 .iter()
3713 .position(|entry| entry.page_index == toggle_page_idx)
3714 .expect("page not found");
3715 settings_window.toggle_navbar_entry(toggle_idx);
3716
3717 let expected_settings_window = parse(after, window, cx);
3718
3719 pretty_assertions::assert_eq!(
3720 settings_window
3721 .visible_navbar_entries()
3722 .map(|(_, entry)| entry)
3723 .collect::<Vec<_>>(),
3724 expected_settings_window
3725 .visible_navbar_entries()
3726 .map(|(_, entry)| entry)
3727 .collect::<Vec<_>>(),
3728 );
3729 pretty_assertions::assert_eq!(
3730 settings_window.navbar_entries[settings_window.navbar_entry()],
3731 expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
3732 );
3733 }
3734
3735 macro_rules! check_navbar_toggle {
3736 ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
3737 #[gpui::test]
3738 fn $name(cx: &mut gpui::TestAppContext) {
3739 let window = cx.add_empty_window();
3740 window.update(|window, cx| {
3741 register_settings(cx);
3742 check_navbar_toggle($before, $toggle_page, $after, window, cx);
3743 });
3744 }
3745 };
3746 }
3747
3748 check_navbar_toggle!(
3749 navbar_basic_open,
3750 before: r"
3751 v General
3752 - General
3753 - Privacy*
3754 v Project
3755 - Project Settings
3756 ",
3757 toggle_page: "General",
3758 after: r"
3759 > General*
3760 v Project
3761 - Project Settings
3762 "
3763 );
3764
3765 check_navbar_toggle!(
3766 navbar_basic_close,
3767 before: r"
3768 > General*
3769 - General
3770 - Privacy
3771 v Project
3772 - Project Settings
3773 ",
3774 toggle_page: "General",
3775 after: r"
3776 v General*
3777 - General
3778 - Privacy
3779 v Project
3780 - Project Settings
3781 "
3782 );
3783
3784 check_navbar_toggle!(
3785 navbar_basic_second_root_entry_close,
3786 before: r"
3787 > General
3788 - General
3789 - Privacy
3790 v Project
3791 - Project Settings*
3792 ",
3793 toggle_page: "Project",
3794 after: r"
3795 > General
3796 > Project*
3797 "
3798 );
3799
3800 check_navbar_toggle!(
3801 navbar_toggle_subroot,
3802 before: r"
3803 v General Page
3804 - General
3805 - Privacy
3806 v Project
3807 - Worktree Settings Content*
3808 v AI
3809 - General
3810 > Appearance & Behavior
3811 ",
3812 toggle_page: "Project",
3813 after: r"
3814 v General Page
3815 - General
3816 - Privacy
3817 > Project*
3818 v AI
3819 - General
3820 > Appearance & Behavior
3821 "
3822 );
3823
3824 check_navbar_toggle!(
3825 navbar_toggle_close_propagates_selected_index,
3826 before: r"
3827 v General Page
3828 - General
3829 - Privacy
3830 v Project
3831 - Worktree Settings Content
3832 v AI
3833 - General*
3834 > Appearance & Behavior
3835 ",
3836 toggle_page: "General Page",
3837 after: r"
3838 > General Page*
3839 v Project
3840 - Worktree Settings Content
3841 v AI
3842 - General
3843 > Appearance & Behavior
3844 "
3845 );
3846
3847 check_navbar_toggle!(
3848 navbar_toggle_expand_propagates_selected_index,
3849 before: r"
3850 > General Page
3851 - General
3852 - Privacy
3853 v Project
3854 - Worktree Settings Content
3855 v AI
3856 - General*
3857 > Appearance & Behavior
3858 ",
3859 toggle_page: "General Page",
3860 after: r"
3861 v General Page*
3862 - General
3863 - Privacy
3864 v Project
3865 - Worktree Settings Content
3866 v AI
3867 - General
3868 > Appearance & Behavior
3869 "
3870 );
3871}