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