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