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