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