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, Div, Entity, FocusHandle, Focusable, Global, ListState, ReadGlobal as _,
10 ScrollHandle, Stateful, Subscription, Task, TitlebarOptions, UniformListScrollHandle, Window,
11 WindowBounds, WindowHandle, WindowOptions, actions, div, list, point, prelude::*, px, size,
12 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 = size(px(900.), px(750.)); // 4:3 Aspect Ratio
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, window, false, 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 window: &mut Window,
1739 drop_down_file: bool,
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, window, false, 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 (ix, (file, focus_handle)) in self
1838 .files
1839 .iter()
1840 .enumerate()
1841 .skip(OVERFLOW_LIMIT + 1)
1842 {
1843 menu = menu.entry(
1844 self.display_name(file)
1845 .expect("Files should always have a name"),
1846 None,
1847 {
1848 let this = this.clone();
1849 let focus_handle = focus_handle.clone();
1850 move |window, cx| {
1851 this.update(cx, |this, cx| {
1852 this.change_file(
1853 ix, window, true, cx,
1854 );
1855 });
1856 focus_handle.focus(window);
1857 }
1858 },
1859 );
1860 }
1861
1862 menu
1863 }),
1864 )
1865 .style(DropdownStyle::Subtle)
1866 .trigger_tooltip(Tooltip::text("View Other Projects"))
1867 .trigger_icon(IconName::ChevronDown)
1868 .attach(gpui::Corner::BottomLeft)
1869 .offset(gpui::Point {
1870 x: px(0.0),
1871 y: px(2.0),
1872 })
1873 .tab_index(0),
1874 )
1875 },
1876 )
1877 }),
1878 )
1879 .child(
1880 Button::new("edit-in-json", "Edit in settings.json")
1881 .tab_index(0_isize)
1882 .style(ButtonStyle::OutlinedGhost)
1883 .on_click(cx.listener(|this, _, _, cx| {
1884 this.open_current_settings_file(cx);
1885 })),
1886 )
1887 }
1888
1889 pub(crate) fn display_name(&self, file: &SettingsUiFile) -> Option<String> {
1890 match file {
1891 SettingsUiFile::User => Some("User".to_string()),
1892 SettingsUiFile::Project((worktree_id, path)) => self
1893 .worktree_root_dirs
1894 .get(&worktree_id)
1895 .map(|directory_name| {
1896 let path_style = PathStyle::local();
1897 if path.is_empty() {
1898 directory_name.clone()
1899 } else {
1900 format!(
1901 "{}{}{}",
1902 directory_name,
1903 path_style.separator(),
1904 path.display(path_style)
1905 )
1906 }
1907 }),
1908 SettingsUiFile::Server(file) => Some(file.to_string()),
1909 }
1910 }
1911
1912 // TODO:
1913 // Reconsider this after preview launch
1914 // fn file_location_str(&self) -> String {
1915 // match &self.current_file {
1916 // SettingsUiFile::User => "settings.json".to_string(),
1917 // SettingsUiFile::Project((worktree_id, path)) => self
1918 // .worktree_root_dirs
1919 // .get(&worktree_id)
1920 // .map(|directory_name| {
1921 // let path_style = PathStyle::local();
1922 // let file_path = path.join(paths::local_settings_file_relative_path());
1923 // format!(
1924 // "{}{}{}",
1925 // directory_name,
1926 // path_style.separator(),
1927 // file_path.display(path_style)
1928 // )
1929 // })
1930 // .expect("Current file should always be present in root dir map"),
1931 // SettingsUiFile::Server(file) => file.to_string(),
1932 // }
1933 // }
1934
1935 fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
1936 h_flex()
1937 .py_1()
1938 .px_1p5()
1939 .mb_3()
1940 .gap_1p5()
1941 .rounded_sm()
1942 .bg(cx.theme().colors().editor_background)
1943 .border_1()
1944 .border_color(cx.theme().colors().border)
1945 .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
1946 .child(self.search_bar.clone())
1947 }
1948
1949 fn render_nav(
1950 &self,
1951 window: &mut Window,
1952 cx: &mut Context<SettingsWindow>,
1953 ) -> impl IntoElement {
1954 let visible_count = self.visible_navbar_entries().count();
1955
1956 let focus_keybind_label = if self
1957 .navbar_focus_handle
1958 .read(cx)
1959 .handle
1960 .contains_focused(window, cx)
1961 || self
1962 .visible_navbar_entries()
1963 .any(|(_, entry)| entry.focus_handle.is_focused(window))
1964 {
1965 "Focus Content"
1966 } else {
1967 "Focus Navbar"
1968 };
1969
1970 v_flex()
1971 .key_context("NavigationMenu")
1972 .on_action(cx.listener(|this, _: &CollapseNavEntry, window, cx| {
1973 let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1974 return;
1975 };
1976 let focused_entry_parent = this.root_entry_containing(focused_entry);
1977 if this.navbar_entries[focused_entry_parent].expanded {
1978 this.toggle_navbar_entry(focused_entry_parent);
1979 window.focus(&this.navbar_entries[focused_entry_parent].focus_handle);
1980 }
1981 cx.notify();
1982 }))
1983 .on_action(cx.listener(|this, _: &ExpandNavEntry, window, cx| {
1984 let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
1985 return;
1986 };
1987 if !this.navbar_entries[focused_entry].is_root {
1988 return;
1989 }
1990 if !this.navbar_entries[focused_entry].expanded {
1991 this.toggle_navbar_entry(focused_entry);
1992 }
1993 cx.notify();
1994 }))
1995 .on_action(
1996 cx.listener(|this, _: &FocusPreviousRootNavEntry, window, cx| {
1997 let entry_index = this
1998 .focused_nav_entry(window, cx)
1999 .unwrap_or(this.navbar_entry);
2000 let mut root_index = None;
2001 for (index, entry) in this.visible_navbar_entries() {
2002 if index >= entry_index {
2003 break;
2004 }
2005 if entry.is_root {
2006 root_index = Some(index);
2007 }
2008 }
2009 let Some(previous_root_index) = root_index else {
2010 return;
2011 };
2012 this.focus_and_scroll_to_nav_entry(previous_root_index, window, cx);
2013 }),
2014 )
2015 .on_action(cx.listener(|this, _: &FocusNextRootNavEntry, window, cx| {
2016 let entry_index = this
2017 .focused_nav_entry(window, cx)
2018 .unwrap_or(this.navbar_entry);
2019 let mut root_index = None;
2020 for (index, entry) in this.visible_navbar_entries() {
2021 if index <= entry_index {
2022 continue;
2023 }
2024 if entry.is_root {
2025 root_index = Some(index);
2026 break;
2027 }
2028 }
2029 let Some(next_root_index) = root_index else {
2030 return;
2031 };
2032 this.focus_and_scroll_to_nav_entry(next_root_index, window, cx);
2033 }))
2034 .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, cx| {
2035 if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
2036 this.focus_and_scroll_to_nav_entry(first_entry_index, window, cx);
2037 }
2038 }))
2039 .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, cx| {
2040 if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
2041 this.focus_and_scroll_to_nav_entry(last_entry_index, window, cx);
2042 }
2043 }))
2044 .on_action(cx.listener(|this, _: &FocusNextNavEntry, window, cx| {
2045 let entry_index = this
2046 .focused_nav_entry(window, cx)
2047 .unwrap_or(this.navbar_entry);
2048 let mut next_index = None;
2049 for (index, _) in this.visible_navbar_entries() {
2050 if index > entry_index {
2051 next_index = Some(index);
2052 break;
2053 }
2054 }
2055 let Some(next_entry_index) = next_index else {
2056 return;
2057 };
2058 this.open_and_scroll_to_navbar_entry(
2059 next_entry_index,
2060 Some(gpui::ScrollStrategy::Bottom),
2061 false,
2062 window,
2063 cx,
2064 );
2065 }))
2066 .on_action(cx.listener(|this, _: &FocusPreviousNavEntry, window, cx| {
2067 let entry_index = this
2068 .focused_nav_entry(window, cx)
2069 .unwrap_or(this.navbar_entry);
2070 let mut prev_index = None;
2071 for (index, _) in this.visible_navbar_entries() {
2072 if index >= entry_index {
2073 break;
2074 }
2075 prev_index = Some(index);
2076 }
2077 let Some(prev_entry_index) = prev_index else {
2078 return;
2079 };
2080 this.open_and_scroll_to_navbar_entry(
2081 prev_entry_index,
2082 Some(gpui::ScrollStrategy::Top),
2083 false,
2084 window,
2085 cx,
2086 );
2087 }))
2088 .w_56()
2089 .h_full()
2090 .p_2p5()
2091 .when(cfg!(target_os = "macos"), |this| this.pt_10())
2092 .flex_none()
2093 .border_r_1()
2094 .border_color(cx.theme().colors().border)
2095 .bg(cx.theme().colors().panel_background)
2096 .child(self.render_search(window, cx))
2097 .child(
2098 v_flex()
2099 .flex_1()
2100 .overflow_hidden()
2101 .track_focus(&self.navbar_focus_handle.focus_handle(cx))
2102 .tab_group()
2103 .tab_index(NAVBAR_GROUP_TAB_INDEX)
2104 .child(
2105 uniform_list(
2106 "settings-ui-nav-bar",
2107 visible_count + 1,
2108 cx.processor(move |this, range: Range<usize>, _, cx| {
2109 this.visible_navbar_entries()
2110 .skip(range.start.saturating_sub(1))
2111 .take(range.len())
2112 .map(|(entry_index, entry)| {
2113 TreeViewItem::new(
2114 ("settings-ui-navbar-entry", entry_index),
2115 entry.title,
2116 )
2117 .track_focus(&entry.focus_handle)
2118 .root_item(entry.is_root)
2119 .toggle_state(this.is_navbar_entry_selected(entry_index))
2120 .when(entry.is_root, |item| {
2121 item.expanded(entry.expanded || this.has_query)
2122 .on_toggle(cx.listener(
2123 move |this, _, window, cx| {
2124 this.toggle_navbar_entry(entry_index);
2125 window.focus(
2126 &this.navbar_entries[entry_index]
2127 .focus_handle,
2128 );
2129 cx.notify();
2130 },
2131 ))
2132 })
2133 .on_click(
2134 cx.listener(move |this, _, window, cx| {
2135 this.open_and_scroll_to_navbar_entry(
2136 entry_index,
2137 None,
2138 true,
2139 window,
2140 cx,
2141 );
2142 }),
2143 )
2144 })
2145 .collect()
2146 }),
2147 )
2148 .size_full()
2149 .track_scroll(self.navbar_scroll_handle.clone()),
2150 )
2151 .vertical_scrollbar_for(self.navbar_scroll_handle.clone(), window, cx),
2152 )
2153 .child(
2154 h_flex()
2155 .w_full()
2156 .h_8()
2157 .p_2()
2158 .pb_0p5()
2159 .flex_shrink_0()
2160 .border_t_1()
2161 .border_color(cx.theme().colors().border_variant)
2162 .child(
2163 KeybindingHint::new(
2164 KeyBinding::for_action_in(
2165 &ToggleFocusNav,
2166 &self.navbar_focus_handle.focus_handle(cx),
2167 cx,
2168 ),
2169 cx.theme().colors().surface_background.opacity(0.5),
2170 )
2171 .suffix(focus_keybind_label),
2172 ),
2173 )
2174 }
2175
2176 fn open_and_scroll_to_navbar_entry(
2177 &mut self,
2178 navbar_entry_index: usize,
2179 scroll_strategy: Option<gpui::ScrollStrategy>,
2180 focus_content: bool,
2181 window: &mut Window,
2182 cx: &mut Context<Self>,
2183 ) {
2184 self.open_navbar_entry_page(navbar_entry_index);
2185 cx.notify();
2186
2187 let mut handle_to_focus = None;
2188
2189 if self.navbar_entries[navbar_entry_index].is_root
2190 || !self.is_nav_entry_visible(navbar_entry_index)
2191 {
2192 self.sub_page_scroll_handle
2193 .set_offset(point(px(0.), px(0.)));
2194 if focus_content {
2195 let Some(first_item_index) =
2196 self.visible_page_items().next().map(|(index, _)| index)
2197 else {
2198 return;
2199 };
2200 handle_to_focus = Some(self.focus_handle_for_content_element(first_item_index, cx));
2201 } else if !self.is_nav_entry_visible(navbar_entry_index) {
2202 let Some(first_visible_nav_entry_index) =
2203 self.visible_navbar_entries().next().map(|(index, _)| index)
2204 else {
2205 return;
2206 };
2207 self.focus_and_scroll_to_nav_entry(first_visible_nav_entry_index, window, cx);
2208 } else {
2209 handle_to_focus =
2210 Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2211 }
2212 } else {
2213 let entry_item_index = self.navbar_entries[navbar_entry_index]
2214 .item_index
2215 .expect("Non-root items should have an item index");
2216 self.scroll_to_content_item(entry_item_index, window, cx);
2217 if focus_content {
2218 handle_to_focus = Some(self.focus_handle_for_content_element(entry_item_index, cx));
2219 } else {
2220 handle_to_focus =
2221 Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2222 }
2223 }
2224
2225 if let Some(scroll_strategy) = scroll_strategy
2226 && let Some(logical_entry_index) = self
2227 .visible_navbar_entries()
2228 .into_iter()
2229 .position(|(index, _)| index == navbar_entry_index)
2230 {
2231 self.navbar_scroll_handle
2232 .scroll_to_item(logical_entry_index + 1, scroll_strategy);
2233 }
2234
2235 // Page scroll handle updates the active item index
2236 // in it's next paint call after using scroll_handle.scroll_to_top_of_item
2237 // The call after that updates the offset of the scroll handle. So to
2238 // ensure the scroll handle doesn't lag behind we need to render three frames
2239 // back to back.
2240 cx.on_next_frame(window, move |_, window, cx| {
2241 if let Some(handle) = handle_to_focus.as_ref() {
2242 window.focus(handle);
2243 }
2244
2245 cx.on_next_frame(window, |_, _, cx| {
2246 cx.notify();
2247 });
2248 cx.notify();
2249 });
2250 cx.notify();
2251 }
2252
2253 fn scroll_to_content_item(
2254 &self,
2255 content_item_index: usize,
2256 _window: &mut Window,
2257 cx: &mut Context<Self>,
2258 ) {
2259 let index = self
2260 .visible_page_items()
2261 .position(|(index, _)| index == content_item_index)
2262 .unwrap_or(0);
2263 if index == 0 {
2264 self.sub_page_scroll_handle
2265 .set_offset(point(px(0.), px(0.)));
2266 self.list_state.scroll_to(gpui::ListOffset {
2267 item_ix: 0,
2268 offset_in_item: px(0.),
2269 });
2270 return;
2271 }
2272 self.list_state.scroll_to(gpui::ListOffset {
2273 item_ix: index + 1,
2274 offset_in_item: px(0.),
2275 });
2276 cx.notify();
2277 }
2278
2279 fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
2280 self.visible_navbar_entries()
2281 .any(|(index, _)| index == nav_entry_index)
2282 }
2283
2284 fn focus_and_scroll_to_first_visible_nav_entry(
2285 &self,
2286 window: &mut Window,
2287 cx: &mut Context<Self>,
2288 ) {
2289 if let Some(nav_entry_index) = self.visible_navbar_entries().next().map(|(index, _)| index)
2290 {
2291 self.focus_and_scroll_to_nav_entry(nav_entry_index, window, cx);
2292 }
2293 }
2294
2295 fn focus_and_scroll_to_nav_entry(
2296 &self,
2297 nav_entry_index: usize,
2298 window: &mut Window,
2299 cx: &mut Context<Self>,
2300 ) {
2301 let Some(position) = self
2302 .visible_navbar_entries()
2303 .position(|(index, _)| index == nav_entry_index)
2304 else {
2305 return;
2306 };
2307 self.navbar_scroll_handle
2308 .scroll_to_item(position, gpui::ScrollStrategy::Top);
2309 window.focus(&self.navbar_entries[nav_entry_index].focus_handle);
2310 cx.notify();
2311 }
2312
2313 fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
2314 let page_idx = self.current_page_index();
2315
2316 self.current_page()
2317 .items
2318 .iter()
2319 .enumerate()
2320 .filter_map(move |(item_index, item)| {
2321 self.filter_table[page_idx][item_index].then_some((item_index, item))
2322 })
2323 }
2324
2325 fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
2326 let mut items = vec![];
2327 items.push(self.current_page().title.into());
2328 items.extend(
2329 sub_page_stack()
2330 .iter()
2331 .flat_map(|page| [page.section_header.into(), page.link.title.clone()]),
2332 );
2333
2334 let last = items.pop().unwrap();
2335 h_flex()
2336 .gap_1()
2337 .children(
2338 items
2339 .into_iter()
2340 .flat_map(|item| [item, "/".into()])
2341 .map(|item| Label::new(item).color(Color::Muted)),
2342 )
2343 .child(Label::new(last))
2344 }
2345
2346 fn render_empty_state(&self, search_query: SharedString) -> impl IntoElement {
2347 v_flex()
2348 .size_full()
2349 .items_center()
2350 .justify_center()
2351 .gap_1()
2352 .child(Label::new("No Results"))
2353 .child(
2354 Label::new(search_query)
2355 .size(LabelSize::Small)
2356 .color(Color::Muted),
2357 )
2358 }
2359
2360 fn render_page_items(
2361 &mut self,
2362 page_index: usize,
2363 _window: &mut Window,
2364 cx: &mut Context<SettingsWindow>,
2365 ) -> impl IntoElement {
2366 let mut page_content = v_flex().id("settings-ui-page").size_full();
2367
2368 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2369 let has_no_results = self.visible_page_items().next().is_none() && has_active_search;
2370
2371 if has_no_results {
2372 let search_query = self.search_bar.read(cx).text(cx);
2373 page_content = page_content.child(
2374 self.render_empty_state(format!("No settings match \"{}\"", search_query).into()),
2375 )
2376 } else {
2377 let last_non_header_index = self
2378 .visible_page_items()
2379 .filter_map(|(index, item)| {
2380 (!matches!(item, SettingsPageItem::SectionHeader(_))).then_some(index)
2381 })
2382 .last();
2383
2384 let root_nav_label = self
2385 .navbar_entries
2386 .iter()
2387 .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2388 .map(|entry| entry.title);
2389
2390 let list_content = list(
2391 self.list_state.clone(),
2392 cx.processor(move |this, index, window, cx| {
2393 if index == 0 {
2394 return div()
2395 .when(sub_page_stack().is_empty(), |this| {
2396 this.when_some(root_nav_label, |this, title| {
2397 this.child(
2398 Label::new(title).size(LabelSize::Large).mt_2().mb_3(),
2399 )
2400 })
2401 })
2402 .into_any_element();
2403 }
2404
2405 let mut visible_items = this.visible_page_items();
2406 let Some((actual_item_index, item)) = visible_items.nth(index - 1) else {
2407 return gpui::Empty.into_any_element();
2408 };
2409
2410 let no_bottom_border = visible_items
2411 .next()
2412 .map(|(_, item)| matches!(item, SettingsPageItem::SectionHeader(_)))
2413 .unwrap_or(false);
2414
2415 let is_last = Some(actual_item_index) == last_non_header_index;
2416
2417 let item_focus_handle =
2418 this.content_handles[page_index][actual_item_index].focus_handle(cx);
2419
2420 v_flex()
2421 .id(("settings-page-item", actual_item_index))
2422 .w_full()
2423 .min_w_0()
2424 .track_focus(&item_focus_handle)
2425 .child(item.render(
2426 this,
2427 actual_item_index,
2428 no_bottom_border || is_last,
2429 window,
2430 cx,
2431 ))
2432 .into_any_element()
2433 }),
2434 );
2435
2436 page_content = page_content.child(list_content.size_full())
2437 }
2438 page_content
2439 }
2440
2441 fn render_sub_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
2442 &self,
2443 items: Items,
2444 page_index: Option<usize>,
2445 window: &mut Window,
2446 cx: &mut Context<SettingsWindow>,
2447 ) -> impl IntoElement {
2448 let mut page_content = v_flex()
2449 .id("settings-ui-page")
2450 .size_full()
2451 .overflow_y_scroll()
2452 .track_scroll(&self.sub_page_scroll_handle);
2453
2454 let items: Vec<_> = items.collect();
2455 let items_len = items.len();
2456 let mut section_header = None;
2457
2458 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2459 let has_no_results = items_len == 0 && has_active_search;
2460
2461 if has_no_results {
2462 let search_query = self.search_bar.read(cx).text(cx);
2463 page_content = page_content.child(
2464 self.render_empty_state(format!("No settings match \"{}\"", search_query).into()),
2465 )
2466 } else {
2467 let last_non_header_index = items
2468 .iter()
2469 .enumerate()
2470 .rev()
2471 .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
2472 .map(|(index, _)| index);
2473
2474 let root_nav_label = self
2475 .navbar_entries
2476 .iter()
2477 .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2478 .map(|entry| entry.title);
2479
2480 page_content = page_content
2481 .when(sub_page_stack().is_empty(), |this| {
2482 this.when_some(root_nav_label, |this, title| {
2483 this.child(Label::new(title).size(LabelSize::Large).mt_2().mb_3())
2484 })
2485 })
2486 .children(items.clone().into_iter().enumerate().map(
2487 |(index, (actual_item_index, item))| {
2488 let no_bottom_border = items
2489 .get(index + 1)
2490 .map(|(_, next_item)| {
2491 matches!(next_item, SettingsPageItem::SectionHeader(_))
2492 })
2493 .unwrap_or(false);
2494 let is_last = Some(index) == last_non_header_index;
2495
2496 if let SettingsPageItem::SectionHeader(header) = item {
2497 section_header = Some(*header);
2498 }
2499 v_flex()
2500 .w_full()
2501 .min_w_0()
2502 .id(("settings-page-item", actual_item_index))
2503 .when_some(page_index, |element, page_index| {
2504 element.track_focus(
2505 &self.content_handles[page_index][actual_item_index]
2506 .focus_handle(cx),
2507 )
2508 })
2509 .child(item.render(
2510 self,
2511 actual_item_index,
2512 no_bottom_border || is_last,
2513 window,
2514 cx,
2515 ))
2516 },
2517 ))
2518 }
2519 page_content
2520 }
2521
2522 fn render_page(
2523 &mut self,
2524 window: &mut Window,
2525 cx: &mut Context<SettingsWindow>,
2526 ) -> impl IntoElement {
2527 let page_header;
2528 let page_content;
2529
2530 if sub_page_stack().is_empty() {
2531 page_header = self.render_files_header(window, cx).into_any_element();
2532
2533 page_content = self
2534 .render_page_items(self.current_page_index(), window, cx)
2535 .into_any_element();
2536 } else {
2537 page_header = h_flex()
2538 .ml_neg_1p5()
2539 .pb_4()
2540 .gap_1()
2541 .child(
2542 IconButton::new("back-btn", IconName::ArrowLeft)
2543 .icon_size(IconSize::Small)
2544 .shape(IconButtonShape::Square)
2545 .on_click(cx.listener(|this, _, _, cx| {
2546 this.pop_sub_page(cx);
2547 })),
2548 )
2549 .child(self.render_sub_page_breadcrumbs())
2550 .into_any_element();
2551
2552 let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
2553 page_content = (active_page_render_fn)(self, window, cx);
2554 }
2555
2556 let mut warning_banner = gpui::Empty.into_any_element();
2557 if let Some(error) =
2558 SettingsStore::global(cx).error_for_file(self.current_file.to_settings())
2559 {
2560 warning_banner = v_flex()
2561 .pb_4()
2562 .child(
2563 Banner::new()
2564 .severity(Severity::Warning)
2565 .child(
2566 Label::new("Your Settings File is in an Invalid State. Setting Values May Be Incorrect, and Changes May Be Lost")
2567 .size(LabelSize::Large),
2568 )
2569 .child(Label::new(error).size(LabelSize::Small).color(Color::Muted))
2570 .action_slot(
2571 Button::new("fix-in-json", "Fix in settings.json")
2572 .tab_index(0_isize)
2573 .style(ButtonStyle::OutlinedGhost)
2574 .on_click(cx.listener(|this, _, _, cx| {
2575 this.open_current_settings_file(cx);
2576 })),
2577 ),
2578 )
2579 .into_any_element()
2580 }
2581
2582 return v_flex()
2583 .id("Settings-ui-page")
2584 .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
2585 if !sub_page_stack().is_empty() {
2586 window.focus_next();
2587 return;
2588 }
2589 for (logical_index, (actual_index, _)) in this.visible_page_items().enumerate() {
2590 let handle = this.content_handles[this.current_page_index()][actual_index]
2591 .focus_handle(cx);
2592 let mut offset = 1; // for page header
2593
2594 if let Some((_, next_item)) = this.visible_page_items().nth(logical_index + 1)
2595 && matches!(next_item, SettingsPageItem::SectionHeader(_))
2596 {
2597 offset += 1;
2598 }
2599 if handle.contains_focused(window, cx) {
2600 let next_logical_index = logical_index + offset + 1;
2601 this.list_state.scroll_to_reveal_item(next_logical_index);
2602 // We need to render the next item to ensure it's focus handle is in the element tree
2603 cx.on_next_frame(window, |_, window, cx| {
2604 window.focus_next();
2605 cx.notify();
2606 });
2607 cx.notify();
2608 return;
2609 }
2610 }
2611 window.focus_next();
2612 }))
2613 .on_action(cx.listener(|this, _: &menu::SelectPrevious, window, cx| {
2614 if !sub_page_stack().is_empty() {
2615 window.focus_prev();
2616 return;
2617 }
2618 let mut prev_was_header = false;
2619 for (logical_index, (actual_index, item)) in this.visible_page_items().enumerate() {
2620 let is_header = matches!(item, SettingsPageItem::SectionHeader(_));
2621 let handle = this.content_handles[this.current_page_index()][actual_index]
2622 .focus_handle(cx);
2623 let mut offset = 1; // for page header
2624
2625 if prev_was_header {
2626 offset -= 1;
2627 }
2628 if handle.contains_focused(window, cx) {
2629 let next_logical_index = logical_index + offset - 1;
2630 this.list_state.scroll_to_reveal_item(next_logical_index);
2631 // We need to render the next item to ensure it's focus handle is in the element tree
2632 cx.on_next_frame(window, |_, window, cx| {
2633 window.focus_prev();
2634 cx.notify();
2635 });
2636 cx.notify();
2637 return;
2638 }
2639 prev_was_header = is_header;
2640 }
2641 window.focus_prev();
2642 }))
2643 .child(warning_banner)
2644 .child(page_header)
2645 .when(sub_page_stack().is_empty(), |this| {
2646 this.vertical_scrollbar_for(self.list_state.clone(), window, cx)
2647 })
2648 .when(!sub_page_stack().is_empty(), |this| {
2649 this.vertical_scrollbar_for(self.sub_page_scroll_handle.clone(), window, cx)
2650 })
2651 .track_focus(&self.content_focus_handle.focus_handle(cx))
2652 .flex_1()
2653 .pt_6()
2654 .px_8()
2655 .bg(cx.theme().colors().editor_background)
2656 .child(
2657 div()
2658 .size_full()
2659 .tab_group()
2660 .tab_index(CONTENT_GROUP_TAB_INDEX)
2661 .child(page_content),
2662 );
2663 }
2664
2665 fn open_current_settings_file(&mut self, cx: &mut Context<Self>) {
2666 match &self.current_file {
2667 SettingsUiFile::User => {
2668 let Some(original_window) = self.original_window else {
2669 return;
2670 };
2671 original_window
2672 .update(cx, |workspace, window, cx| {
2673 workspace
2674 .with_local_workspace(window, cx, |workspace, window, cx| {
2675 let create_task = workspace.project().update(cx, |project, cx| {
2676 project.find_or_create_worktree(
2677 paths::config_dir().as_path(),
2678 false,
2679 cx,
2680 )
2681 });
2682 let open_task = workspace.open_paths(
2683 vec![paths::settings_file().to_path_buf()],
2684 OpenOptions {
2685 visible: Some(OpenVisible::None),
2686 ..Default::default()
2687 },
2688 None,
2689 window,
2690 cx,
2691 );
2692
2693 cx.spawn_in(window, async move |workspace, cx| {
2694 create_task.await.ok();
2695 open_task.await;
2696
2697 workspace.update_in(cx, |_, window, cx| {
2698 window.activate_window();
2699 cx.notify();
2700 })
2701 })
2702 .detach();
2703 })
2704 .detach();
2705 })
2706 .ok();
2707 }
2708 SettingsUiFile::Project((worktree_id, path)) => {
2709 let mut corresponding_workspace: Option<WindowHandle<Workspace>> = None;
2710 let settings_path = path.join(paths::local_settings_file_relative_path());
2711 let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
2712 return;
2713 };
2714 for workspace in app_state.workspace_store.read(cx).workspaces() {
2715 let contains_settings_file = workspace
2716 .read_with(cx, |workspace, cx| {
2717 workspace.project().read(cx).contains_local_settings_file(
2718 *worktree_id,
2719 settings_path.as_ref(),
2720 cx,
2721 )
2722 })
2723 .ok();
2724 if Some(true) == contains_settings_file {
2725 corresponding_workspace = Some(*workspace);
2726
2727 break;
2728 }
2729 }
2730
2731 let Some(corresponding_workspace) = corresponding_workspace else {
2732 log::error!(
2733 "No corresponding workspace found for settings file {}",
2734 settings_path.as_std_path().display()
2735 );
2736
2737 return;
2738 };
2739
2740 // TODO: move zed::open_local_file() APIs to this crate, and
2741 // re-implement the "initial_contents" behavior
2742 corresponding_workspace
2743 .update(cx, |workspace, window, cx| {
2744 let open_task = workspace.open_path(
2745 (*worktree_id, settings_path.clone()),
2746 None,
2747 true,
2748 window,
2749 cx,
2750 );
2751
2752 cx.spawn_in(window, async move |workspace, cx| {
2753 if open_task.await.log_err().is_some() {
2754 workspace
2755 .update_in(cx, |_, window, cx| {
2756 window.activate_window();
2757 cx.notify();
2758 })
2759 .ok();
2760 }
2761 })
2762 .detach();
2763 })
2764 .ok();
2765 }
2766 SettingsUiFile::Server(_) => {
2767 return;
2768 }
2769 };
2770 }
2771
2772 fn current_page_index(&self) -> usize {
2773 self.page_index_from_navbar_index(self.navbar_entry)
2774 }
2775
2776 fn current_page(&self) -> &SettingsPage {
2777 &self.pages[self.current_page_index()]
2778 }
2779
2780 fn page_index_from_navbar_index(&self, index: usize) -> usize {
2781 if self.navbar_entries.is_empty() {
2782 return 0;
2783 }
2784
2785 self.navbar_entries[index].page_index
2786 }
2787
2788 fn is_navbar_entry_selected(&self, ix: usize) -> bool {
2789 ix == self.navbar_entry
2790 }
2791
2792 fn push_sub_page(
2793 &mut self,
2794 sub_page_link: SubPageLink,
2795 section_header: &'static str,
2796 cx: &mut Context<SettingsWindow>,
2797 ) {
2798 sub_page_stack_mut().push(SubPage {
2799 link: sub_page_link,
2800 section_header,
2801 });
2802 cx.notify();
2803 }
2804
2805 fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
2806 sub_page_stack_mut().pop();
2807 cx.notify();
2808 }
2809
2810 fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
2811 if let Some((_, handle)) = self.files.get(index) {
2812 handle.focus(window);
2813 }
2814 }
2815
2816 fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
2817 if self.files_focus_handle.contains_focused(window, cx)
2818 && let Some(index) = self
2819 .files
2820 .iter()
2821 .position(|(_, handle)| handle.is_focused(window))
2822 {
2823 return index;
2824 }
2825 if let Some(current_file_index) = self
2826 .files
2827 .iter()
2828 .position(|(file, _)| file == &self.current_file)
2829 {
2830 return current_file_index;
2831 }
2832 0
2833 }
2834
2835 fn focus_handle_for_content_element(
2836 &self,
2837 actual_item_index: usize,
2838 cx: &Context<Self>,
2839 ) -> FocusHandle {
2840 let page_index = self.current_page_index();
2841 self.content_handles[page_index][actual_item_index].focus_handle(cx)
2842 }
2843
2844 fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
2845 if !self
2846 .navbar_focus_handle
2847 .focus_handle(cx)
2848 .contains_focused(window, cx)
2849 {
2850 return None;
2851 }
2852 for (index, entry) in self.navbar_entries.iter().enumerate() {
2853 if entry.focus_handle.is_focused(window) {
2854 return Some(index);
2855 }
2856 }
2857 None
2858 }
2859
2860 fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
2861 let mut index = Some(nav_entry_index);
2862 while let Some(prev_index) = index
2863 && !self.navbar_entries[prev_index].is_root
2864 {
2865 index = prev_index.checked_sub(1);
2866 }
2867 return index.expect("No root entry found");
2868 }
2869}
2870
2871impl Render for SettingsWindow {
2872 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2873 let ui_font = theme::setup_ui_font(window, cx);
2874
2875 client_side_decorations(
2876 v_flex()
2877 .text_color(cx.theme().colors().text)
2878 .size_full()
2879 .children(self.title_bar.clone())
2880 .child(
2881 div()
2882 .id("settings-window")
2883 .key_context("SettingsWindow")
2884 .track_focus(&self.focus_handle)
2885 .on_action(cx.listener(|this, _: &OpenCurrentFile, _, cx| {
2886 this.open_current_settings_file(cx);
2887 }))
2888 .on_action(|_: &Minimize, window, _cx| {
2889 window.minimize_window();
2890 })
2891 .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
2892 this.search_bar.focus_handle(cx).focus(window);
2893 }))
2894 .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
2895 if this
2896 .navbar_focus_handle
2897 .focus_handle(cx)
2898 .contains_focused(window, cx)
2899 {
2900 this.open_and_scroll_to_navbar_entry(
2901 this.navbar_entry,
2902 None,
2903 true,
2904 window,
2905 cx,
2906 );
2907 } else {
2908 this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
2909 }
2910 }))
2911 .on_action(cx.listener(
2912 |this, FocusFile(file_index): &FocusFile, window, _| {
2913 this.focus_file_at_index(*file_index as usize, window);
2914 },
2915 ))
2916 .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
2917 let next_index = usize::min(
2918 this.focused_file_index(window, cx) + 1,
2919 this.files.len().saturating_sub(1),
2920 );
2921 this.focus_file_at_index(next_index, window);
2922 }))
2923 .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
2924 let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
2925 this.focus_file_at_index(prev_index, window);
2926 }))
2927 .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
2928 if this
2929 .search_bar
2930 .focus_handle(cx)
2931 .contains_focused(window, cx)
2932 {
2933 this.focus_and_scroll_to_first_visible_nav_entry(window, cx);
2934 } else {
2935 window.focus_next();
2936 }
2937 }))
2938 .on_action(|_: &menu::SelectPrevious, window, _| {
2939 window.focus_prev();
2940 })
2941 .flex()
2942 .flex_row()
2943 .flex_1()
2944 .min_h_0()
2945 .font(ui_font)
2946 .bg(cx.theme().colors().background)
2947 .text_color(cx.theme().colors().text)
2948 .child(self.render_nav(window, cx))
2949 .child(self.render_page(window, cx)),
2950 ),
2951 window,
2952 cx,
2953 )
2954 }
2955}
2956
2957fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
2958 workspace::AppState::global(cx)
2959 .upgrade()
2960 .map(|app_state| {
2961 app_state
2962 .workspace_store
2963 .read(cx)
2964 .workspaces()
2965 .iter()
2966 .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
2967 })
2968 .into_iter()
2969 .flatten()
2970}
2971
2972fn update_settings_file(
2973 file: SettingsUiFile,
2974 cx: &mut App,
2975 update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
2976) -> Result<()> {
2977 match file {
2978 SettingsUiFile::Project((worktree_id, rel_path)) => {
2979 let rel_path = rel_path.join(paths::local_settings_file_relative_path());
2980 let project = all_projects(cx).find(|project| {
2981 project.read_with(cx, |project, cx| {
2982 project.contains_local_settings_file(worktree_id, &rel_path, cx)
2983 })
2984 });
2985 let Some(project) = project else {
2986 anyhow::bail!(
2987 "Could not find worktree containing settings file: {}",
2988 &rel_path.display(PathStyle::local())
2989 );
2990 };
2991 project.update(cx, |project, cx| {
2992 project.update_local_settings_file(worktree_id, rel_path, cx, update);
2993 });
2994 return Ok(());
2995 }
2996 SettingsUiFile::User => {
2997 // todo(settings_ui) error?
2998 SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
2999 Ok(())
3000 }
3001 SettingsUiFile::Server(_) => unimplemented!(),
3002 }
3003}
3004
3005fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
3006 field: SettingField<T>,
3007 file: SettingsUiFile,
3008 metadata: Option<&SettingsFieldMetadata>,
3009 _window: &mut Window,
3010 cx: &mut App,
3011) -> AnyElement {
3012 let (_, initial_text) =
3013 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3014 let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
3015
3016 SettingsInputField::new()
3017 .tab_index(0)
3018 .when_some(initial_text, |editor, text| {
3019 editor.with_initial_text(text.as_ref().to_string())
3020 })
3021 .when_some(
3022 metadata.and_then(|metadata| metadata.placeholder),
3023 |editor, placeholder| editor.with_placeholder(placeholder),
3024 )
3025 .on_confirm({
3026 move |new_text, cx| {
3027 update_settings_file(file.clone(), cx, move |settings, _cx| {
3028 (field.write)(settings, new_text.map(Into::into));
3029 })
3030 .log_err(); // todo(settings_ui) don't log err
3031 }
3032 })
3033 .into_any_element()
3034}
3035
3036fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
3037 field: SettingField<B>,
3038 file: SettingsUiFile,
3039 _metadata: Option<&SettingsFieldMetadata>,
3040 _window: &mut Window,
3041 cx: &mut App,
3042) -> AnyElement {
3043 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3044
3045 let toggle_state = if value.copied().map_or(false, Into::into) {
3046 ToggleState::Selected
3047 } else {
3048 ToggleState::Unselected
3049 };
3050
3051 Switch::new("toggle_button", toggle_state)
3052 .color(ui::SwitchColor::Accent)
3053 .on_click({
3054 move |state, _window, cx| {
3055 let state = *state == ui::ToggleState::Selected;
3056 update_settings_file(file.clone(), cx, move |settings, _cx| {
3057 (field.write)(settings, Some(state.into()));
3058 })
3059 .log_err(); // todo(settings_ui) don't log err
3060 }
3061 })
3062 .tab_index(0_isize)
3063 .color(SwitchColor::Accent)
3064 .into_any_element()
3065}
3066
3067fn render_number_field<T: NumberFieldType + Send + Sync>(
3068 field: SettingField<T>,
3069 file: SettingsUiFile,
3070 _metadata: Option<&SettingsFieldMetadata>,
3071 window: &mut Window,
3072 cx: &mut App,
3073) -> AnyElement {
3074 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3075 let value = value.copied().unwrap_or_else(T::min_value);
3076 NumberField::new("numeric_stepper", value, window, cx)
3077 .on_change({
3078 move |value, _window, cx| {
3079 let value = *value;
3080 update_settings_file(file.clone(), cx, move |settings, _cx| {
3081 (field.write)(settings, Some(value));
3082 })
3083 .log_err(); // todo(settings_ui) don't log err
3084 }
3085 })
3086 .into_any_element()
3087}
3088
3089fn render_dropdown<T>(
3090 field: SettingField<T>,
3091 file: SettingsUiFile,
3092 metadata: Option<&SettingsFieldMetadata>,
3093 window: &mut Window,
3094 cx: &mut App,
3095) -> AnyElement
3096where
3097 T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
3098{
3099 let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
3100 let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
3101 let should_do_titlecase = metadata
3102 .and_then(|metadata| metadata.should_do_titlecase)
3103 .unwrap_or(true);
3104
3105 let (_, current_value) =
3106 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3107 let current_value = current_value.copied().unwrap_or(variants()[0]);
3108
3109 let current_value_label =
3110 labels()[variants().iter().position(|v| *v == current_value).unwrap()];
3111
3112 DropdownMenu::new(
3113 "dropdown",
3114 if should_do_titlecase {
3115 current_value_label.to_title_case()
3116 } else {
3117 current_value_label.to_string()
3118 },
3119 ContextMenu::build(window, cx, move |mut menu, _, _| {
3120 for (&value, &label) in std::iter::zip(variants(), labels()) {
3121 let file = file.clone();
3122 menu = menu.toggleable_entry(
3123 if should_do_titlecase {
3124 label.to_title_case()
3125 } else {
3126 label.to_string()
3127 },
3128 value == current_value,
3129 IconPosition::End,
3130 None,
3131 move |_, cx| {
3132 if value == current_value {
3133 return;
3134 }
3135 update_settings_file(file.clone(), cx, move |settings, _cx| {
3136 (field.write)(settings, Some(value));
3137 })
3138 .log_err(); // todo(settings_ui) don't log err
3139 },
3140 );
3141 }
3142 menu
3143 }),
3144 )
3145 .trigger_size(ButtonSize::Medium)
3146 .style(DropdownStyle::Outlined)
3147 .offset(gpui::Point {
3148 x: px(0.0),
3149 y: px(2.0),
3150 })
3151 .tab_index(0)
3152 .into_any_element()
3153}
3154
3155fn render_picker_trigger_button(id: SharedString, label: SharedString) -> Button {
3156 Button::new(id, label)
3157 .tab_index(0_isize)
3158 .style(ButtonStyle::Outlined)
3159 .size(ButtonSize::Medium)
3160 .icon(IconName::ChevronUpDown)
3161 .icon_color(Color::Muted)
3162 .icon_size(IconSize::Small)
3163 .icon_position(IconPosition::End)
3164}
3165
3166fn render_font_picker(
3167 field: SettingField<settings::FontFamilyName>,
3168 file: SettingsUiFile,
3169 _metadata: Option<&SettingsFieldMetadata>,
3170 window: &mut Window,
3171 cx: &mut App,
3172) -> AnyElement {
3173 let current_value = SettingsStore::global(cx)
3174 .get_value_from_file(file.to_settings(), field.pick)
3175 .1
3176 .cloned()
3177 .unwrap_or_else(|| SharedString::default().into());
3178
3179 let font_picker = cx.new(|cx| {
3180 font_picker(
3181 current_value.clone().into(),
3182 move |font_name, cx| {
3183 update_settings_file(file.clone(), cx, move |settings, _cx| {
3184 (field.write)(settings, Some(font_name.into()));
3185 })
3186 .log_err(); // todo(settings_ui) don't log err
3187 },
3188 window,
3189 cx,
3190 )
3191 });
3192
3193 PopoverMenu::new("font-picker")
3194 .menu(move |_window, _cx| Some(font_picker.clone()))
3195 .trigger(render_picker_trigger_button(
3196 "font_family_picker_trigger".into(),
3197 current_value.into(),
3198 ))
3199 .anchor(gpui::Corner::TopLeft)
3200 .offset(gpui::Point {
3201 x: px(0.0),
3202 y: px(2.0),
3203 })
3204 .with_handle(ui::PopoverMenuHandle::default())
3205 .into_any_element()
3206}
3207
3208fn render_theme_picker(
3209 field: SettingField<settings::ThemeName>,
3210 file: SettingsUiFile,
3211 _metadata: Option<&SettingsFieldMetadata>,
3212 window: &mut Window,
3213 cx: &mut App,
3214) -> AnyElement {
3215 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3216 let current_value = value
3217 .cloned()
3218 .map(|theme_name| theme_name.0.into())
3219 .unwrap_or_else(|| cx.theme().name.clone());
3220
3221 let theme_picker = cx.new(|cx| {
3222 theme_picker(
3223 current_value.clone(),
3224 move |theme_name, cx| {
3225 update_settings_file(file.clone(), cx, move |settings, _cx| {
3226 (field.write)(settings, Some(settings::ThemeName(theme_name.into())));
3227 })
3228 .log_err(); // todo(settings_ui) don't log err
3229 },
3230 window,
3231 cx,
3232 )
3233 });
3234
3235 PopoverMenu::new("theme-picker")
3236 .menu(move |_window, _cx| Some(theme_picker.clone()))
3237 .trigger(render_picker_trigger_button(
3238 "theme_picker_trigger".into(),
3239 current_value,
3240 ))
3241 .anchor(gpui::Corner::TopLeft)
3242 .offset(gpui::Point {
3243 x: px(0.0),
3244 y: px(2.0),
3245 })
3246 .with_handle(ui::PopoverMenuHandle::default())
3247 .into_any_element()
3248}
3249
3250fn render_icon_theme_picker(
3251 field: SettingField<settings::IconThemeName>,
3252 file: SettingsUiFile,
3253 _metadata: Option<&SettingsFieldMetadata>,
3254 window: &mut Window,
3255 cx: &mut App,
3256) -> AnyElement {
3257 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3258 let current_value = value
3259 .cloned()
3260 .map(|theme_name| theme_name.0.into())
3261 .unwrap_or_else(|| cx.theme().name.clone());
3262
3263 let icon_theme_picker = cx.new(|cx| {
3264 icon_theme_picker(
3265 current_value.clone(),
3266 move |theme_name, cx| {
3267 update_settings_file(file.clone(), cx, move |settings, _cx| {
3268 (field.write)(settings, Some(settings::IconThemeName(theme_name.into())));
3269 })
3270 .log_err(); // todo(settings_ui) don't log err
3271 },
3272 window,
3273 cx,
3274 )
3275 });
3276
3277 PopoverMenu::new("icon-theme-picker")
3278 .menu(move |_window, _cx| Some(icon_theme_picker.clone()))
3279 .trigger(render_picker_trigger_button(
3280 "icon_theme_picker_trigger".into(),
3281 current_value,
3282 ))
3283 .anchor(gpui::Corner::TopLeft)
3284 .offset(gpui::Point {
3285 x: px(0.0),
3286 y: px(2.0),
3287 })
3288 .with_handle(ui::PopoverMenuHandle::default())
3289 .into_any_element()
3290}
3291
3292#[cfg(test)]
3293pub mod test {
3294
3295 use super::*;
3296
3297 impl SettingsWindow {
3298 fn navbar_entry(&self) -> usize {
3299 self.navbar_entry
3300 }
3301 }
3302
3303 impl PartialEq for NavBarEntry {
3304 fn eq(&self, other: &Self) -> bool {
3305 self.title == other.title
3306 && self.is_root == other.is_root
3307 && self.expanded == other.expanded
3308 && self.page_index == other.page_index
3309 && self.item_index == other.item_index
3310 // ignoring focus_handle
3311 }
3312 }
3313
3314 pub fn register_settings(cx: &mut App) {
3315 settings::init(cx);
3316 theme::init(theme::LoadThemes::JustBase, cx);
3317 workspace::init_settings(cx);
3318 project::Project::init_settings(cx);
3319 language::init(cx);
3320 editor::init(cx);
3321 menu::init();
3322 }
3323
3324 fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
3325 let mut pages: Vec<SettingsPage> = Vec::new();
3326 let mut expanded_pages = Vec::new();
3327 let mut selected_idx = None;
3328 let mut index = 0;
3329 let mut in_expanded_section = false;
3330
3331 for mut line in input
3332 .lines()
3333 .map(|line| line.trim())
3334 .filter(|line| !line.is_empty())
3335 {
3336 if let Some(pre) = line.strip_suffix('*') {
3337 assert!(selected_idx.is_none(), "Only one selected entry allowed");
3338 selected_idx = Some(index);
3339 line = pre;
3340 }
3341 let (kind, title) = line.split_once(" ").unwrap();
3342 assert_eq!(kind.len(), 1);
3343 let kind = kind.chars().next().unwrap();
3344 if kind == 'v' {
3345 let page_idx = pages.len();
3346 expanded_pages.push(page_idx);
3347 pages.push(SettingsPage {
3348 title,
3349 items: vec![],
3350 });
3351 index += 1;
3352 in_expanded_section = true;
3353 } else if kind == '>' {
3354 pages.push(SettingsPage {
3355 title,
3356 items: vec![],
3357 });
3358 index += 1;
3359 in_expanded_section = false;
3360 } else if kind == '-' {
3361 pages
3362 .last_mut()
3363 .unwrap()
3364 .items
3365 .push(SettingsPageItem::SectionHeader(title));
3366 if selected_idx == Some(index) && !in_expanded_section {
3367 panic!("Items in unexpanded sections cannot be selected");
3368 }
3369 index += 1;
3370 } else {
3371 panic!(
3372 "Entries must start with one of 'v', '>', or '-'\n line: {}",
3373 line
3374 );
3375 }
3376 }
3377
3378 let mut settings_window = SettingsWindow {
3379 title_bar: None,
3380 original_window: None,
3381 worktree_root_dirs: HashMap::default(),
3382 files: Vec::default(),
3383 current_file: crate::SettingsUiFile::User,
3384 drop_down_file: None,
3385 pages,
3386 search_bar: cx.new(|cx| Editor::single_line(window, cx)),
3387 navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
3388 navbar_entries: Vec::default(),
3389 navbar_scroll_handle: UniformListScrollHandle::default(),
3390 navbar_focus_subscriptions: vec![],
3391 filter_table: vec![],
3392 has_query: false,
3393 content_handles: vec![],
3394 search_task: None,
3395 sub_page_scroll_handle: ScrollHandle::new(),
3396 focus_handle: cx.focus_handle(),
3397 navbar_focus_handle: NonFocusableHandle::new(
3398 NAVBAR_CONTAINER_TAB_INDEX,
3399 false,
3400 window,
3401 cx,
3402 ),
3403 content_focus_handle: NonFocusableHandle::new(
3404 CONTENT_CONTAINER_TAB_INDEX,
3405 false,
3406 window,
3407 cx,
3408 ),
3409 files_focus_handle: cx.focus_handle(),
3410 search_index: None,
3411 list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
3412 };
3413
3414 settings_window.build_filter_table();
3415 settings_window.build_navbar(cx);
3416 for expanded_page_index in expanded_pages {
3417 for entry in &mut settings_window.navbar_entries {
3418 if entry.page_index == expanded_page_index && entry.is_root {
3419 entry.expanded = true;
3420 }
3421 }
3422 }
3423 settings_window
3424 }
3425
3426 #[track_caller]
3427 fn check_navbar_toggle(
3428 before: &'static str,
3429 toggle_page: &'static str,
3430 after: &'static str,
3431 window: &mut Window,
3432 cx: &mut App,
3433 ) {
3434 let mut settings_window = parse(before, window, cx);
3435 let toggle_page_idx = settings_window
3436 .pages
3437 .iter()
3438 .position(|page| page.title == toggle_page)
3439 .expect("page not found");
3440 let toggle_idx = settings_window
3441 .navbar_entries
3442 .iter()
3443 .position(|entry| entry.page_index == toggle_page_idx)
3444 .expect("page not found");
3445 settings_window.toggle_navbar_entry(toggle_idx);
3446
3447 let expected_settings_window = parse(after, window, cx);
3448
3449 pretty_assertions::assert_eq!(
3450 settings_window
3451 .visible_navbar_entries()
3452 .map(|(_, entry)| entry)
3453 .collect::<Vec<_>>(),
3454 expected_settings_window
3455 .visible_navbar_entries()
3456 .map(|(_, entry)| entry)
3457 .collect::<Vec<_>>(),
3458 );
3459 pretty_assertions::assert_eq!(
3460 settings_window.navbar_entries[settings_window.navbar_entry()],
3461 expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
3462 );
3463 }
3464
3465 macro_rules! check_navbar_toggle {
3466 ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
3467 #[gpui::test]
3468 fn $name(cx: &mut gpui::TestAppContext) {
3469 let window = cx.add_empty_window();
3470 window.update(|window, cx| {
3471 register_settings(cx);
3472 check_navbar_toggle($before, $toggle_page, $after, window, cx);
3473 });
3474 }
3475 };
3476 }
3477
3478 check_navbar_toggle!(
3479 navbar_basic_open,
3480 before: r"
3481 v General
3482 - General
3483 - Privacy*
3484 v Project
3485 - Project Settings
3486 ",
3487 toggle_page: "General",
3488 after: r"
3489 > General*
3490 v Project
3491 - Project Settings
3492 "
3493 );
3494
3495 check_navbar_toggle!(
3496 navbar_basic_close,
3497 before: r"
3498 > General*
3499 - General
3500 - Privacy
3501 v Project
3502 - Project Settings
3503 ",
3504 toggle_page: "General",
3505 after: r"
3506 v General*
3507 - General
3508 - Privacy
3509 v Project
3510 - Project Settings
3511 "
3512 );
3513
3514 check_navbar_toggle!(
3515 navbar_basic_second_root_entry_close,
3516 before: r"
3517 > General
3518 - General
3519 - Privacy
3520 v Project
3521 - Project Settings*
3522 ",
3523 toggle_page: "Project",
3524 after: r"
3525 > General
3526 > Project*
3527 "
3528 );
3529
3530 check_navbar_toggle!(
3531 navbar_toggle_subroot,
3532 before: r"
3533 v General Page
3534 - General
3535 - Privacy
3536 v Project
3537 - Worktree Settings Content*
3538 v AI
3539 - General
3540 > Appearance & Behavior
3541 ",
3542 toggle_page: "Project",
3543 after: r"
3544 v General Page
3545 - General
3546 - Privacy
3547 > Project*
3548 v AI
3549 - General
3550 > Appearance & Behavior
3551 "
3552 );
3553
3554 check_navbar_toggle!(
3555 navbar_toggle_close_propagates_selected_index,
3556 before: r"
3557 v General Page
3558 - General
3559 - Privacy
3560 v Project
3561 - Worktree Settings Content
3562 v AI
3563 - General*
3564 > Appearance & Behavior
3565 ",
3566 toggle_page: "General Page",
3567 after: r"
3568 > General Page*
3569 v Project
3570 - Worktree Settings Content
3571 v AI
3572 - General
3573 > Appearance & Behavior
3574 "
3575 );
3576
3577 check_navbar_toggle!(
3578 navbar_toggle_expand_propagates_selected_index,
3579 before: r"
3580 > General Page
3581 - General
3582 - Privacy
3583 v Project
3584 - Worktree Settings Content
3585 v AI
3586 - General*
3587 > Appearance & Behavior
3588 ",
3589 toggle_page: "General Page",
3590 after: r"
3591 v General Page*
3592 - General
3593 - Privacy
3594 v Project
3595 - Worktree Settings Content
3596 v AI
3597 - General
3598 > Appearance & Behavior
3599 "
3600 );
3601}