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, |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 h_flex()
1993 .w_full()
1994 .gap_1()
1995 .justify_between()
1996 .track_focus(&self.files_focus_handle)
1997 .tab_group()
1998 .tab_index(HEADER_GROUP_TAB_INDEX)
1999 .child(
2000 h_flex()
2001 .gap_1()
2002 .children(
2003 self.files.iter().enumerate().take(OVERFLOW_LIMIT).map(
2004 |(ix, (file, focus_handle))| file_button(ix, file, focus_handle, cx),
2005 ),
2006 )
2007 .when(self.files.len() > OVERFLOW_LIMIT, |div| {
2008 let selected_file_ix = self
2009 .files
2010 .iter()
2011 .enumerate()
2012 .skip(OVERFLOW_LIMIT)
2013 .find_map(|(ix, (file, _))| {
2014 if file == &self.current_file {
2015 Some(ix)
2016 } else {
2017 None
2018 }
2019 })
2020 .unwrap_or(OVERFLOW_LIMIT);
2021
2022 let (file, focus_handle) = &self.files[selected_file_ix];
2023
2024 div.child(file_button(selected_file_ix, file, focus_handle, cx))
2025 .when(self.files.len() > OVERFLOW_LIMIT + 1, |div| {
2026 div.child(
2027 DropdownMenu::new(
2028 "more-files",
2029 format!("+{}", self.files.len() - (OVERFLOW_LIMIT + 1)),
2030 ContextMenu::build(window, cx, move |mut menu, _, _| {
2031 for (mut ix, (file, focus_handle)) in self
2032 .files
2033 .iter()
2034 .enumerate()
2035 .skip(OVERFLOW_LIMIT + 1)
2036 {
2037 let (display_name, focus_handle) =
2038 if selected_file_ix == ix {
2039 ix = OVERFLOW_LIMIT;
2040 (
2041 self.display_name(&self.files[ix].0),
2042 self.files[ix].1.clone(),
2043 )
2044 } else {
2045 (
2046 self.display_name(&file),
2047 focus_handle.clone(),
2048 )
2049 };
2050
2051 menu = menu.entry(
2052 display_name
2053 .expect("Files should always have a name"),
2054 None,
2055 {
2056 let this = this.clone();
2057 move |window, cx| {
2058 this.update(cx, |this, cx| {
2059 this.change_file(ix, window, cx);
2060 });
2061 focus_handle.focus(window);
2062 }
2063 },
2064 );
2065 }
2066
2067 menu
2068 }),
2069 )
2070 .style(DropdownStyle::Subtle)
2071 .trigger_tooltip(Tooltip::text("View Other Projects"))
2072 .trigger_icon(IconName::ChevronDown)
2073 .attach(gpui::Corner::BottomLeft)
2074 .offset(gpui::Point {
2075 x: px(0.0),
2076 y: px(2.0),
2077 })
2078 .tab_index(0),
2079 )
2080 })
2081 }),
2082 )
2083 .child(
2084 Button::new("edit-in-json", "Edit in settings.json")
2085 .tab_index(0_isize)
2086 .style(ButtonStyle::OutlinedGhost)
2087 .on_click(cx.listener(|this, _, _, cx| {
2088 this.open_current_settings_file(cx);
2089 })),
2090 )
2091 }
2092
2093 pub(crate) fn display_name(&self, file: &SettingsUiFile) -> Option<String> {
2094 match file {
2095 SettingsUiFile::User => Some("User".to_string()),
2096 SettingsUiFile::Project((worktree_id, path)) => self
2097 .worktree_root_dirs
2098 .get(&worktree_id)
2099 .map(|directory_name| {
2100 let path_style = PathStyle::local();
2101 if path.is_empty() {
2102 directory_name.clone()
2103 } else {
2104 format!(
2105 "{}{}{}",
2106 directory_name,
2107 path_style.separator(),
2108 path.display(path_style)
2109 )
2110 }
2111 }),
2112 SettingsUiFile::Server(file) => Some(file.to_string()),
2113 }
2114 }
2115
2116 // TODO:
2117 // Reconsider this after preview launch
2118 // fn file_location_str(&self) -> String {
2119 // match &self.current_file {
2120 // SettingsUiFile::User => "settings.json".to_string(),
2121 // SettingsUiFile::Project((worktree_id, path)) => self
2122 // .worktree_root_dirs
2123 // .get(&worktree_id)
2124 // .map(|directory_name| {
2125 // let path_style = PathStyle::local();
2126 // let file_path = path.join(paths::local_settings_file_relative_path());
2127 // format!(
2128 // "{}{}{}",
2129 // directory_name,
2130 // path_style.separator(),
2131 // file_path.display(path_style)
2132 // )
2133 // })
2134 // .expect("Current file should always be present in root dir map"),
2135 // SettingsUiFile::Server(file) => file.to_string(),
2136 // }
2137 // }
2138
2139 fn render_search(&self, _window: &mut Window, cx: &mut App) -> Div {
2140 h_flex()
2141 .py_1()
2142 .px_1p5()
2143 .mb_3()
2144 .gap_1p5()
2145 .rounded_sm()
2146 .bg(cx.theme().colors().editor_background)
2147 .border_1()
2148 .border_color(cx.theme().colors().border)
2149 .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
2150 .child(self.search_bar.clone())
2151 }
2152
2153 fn render_nav(
2154 &self,
2155 window: &mut Window,
2156 cx: &mut Context<SettingsWindow>,
2157 ) -> impl IntoElement {
2158 let visible_count = self.visible_navbar_entries().count();
2159
2160 let focus_keybind_label = if self
2161 .navbar_focus_handle
2162 .read(cx)
2163 .handle
2164 .contains_focused(window, cx)
2165 || self
2166 .visible_navbar_entries()
2167 .any(|(_, entry)| entry.focus_handle.is_focused(window))
2168 {
2169 "Focus Content"
2170 } else {
2171 "Focus Navbar"
2172 };
2173
2174 let mut key_context = KeyContext::new_with_defaults();
2175 key_context.add("NavigationMenu");
2176 key_context.add("menu");
2177 if self.search_bar.focus_handle(cx).is_focused(window) {
2178 key_context.add("search");
2179 }
2180
2181 v_flex()
2182 .key_context(key_context)
2183 .on_action(cx.listener(|this, _: &CollapseNavEntry, window, cx| {
2184 let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
2185 return;
2186 };
2187 let focused_entry_parent = this.root_entry_containing(focused_entry);
2188 if this.navbar_entries[focused_entry_parent].expanded {
2189 this.toggle_navbar_entry(focused_entry_parent);
2190 window.focus(&this.navbar_entries[focused_entry_parent].focus_handle);
2191 }
2192 cx.notify();
2193 }))
2194 .on_action(cx.listener(|this, _: &ExpandNavEntry, window, cx| {
2195 let Some(focused_entry) = this.focused_nav_entry(window, cx) else {
2196 return;
2197 };
2198 if !this.navbar_entries[focused_entry].is_root {
2199 return;
2200 }
2201 if !this.navbar_entries[focused_entry].expanded {
2202 this.toggle_navbar_entry(focused_entry);
2203 }
2204 cx.notify();
2205 }))
2206 .on_action(
2207 cx.listener(|this, _: &FocusPreviousRootNavEntry, window, cx| {
2208 let entry_index = this
2209 .focused_nav_entry(window, cx)
2210 .unwrap_or(this.navbar_entry);
2211 let mut root_index = None;
2212 for (index, entry) in this.visible_navbar_entries() {
2213 if index >= entry_index {
2214 break;
2215 }
2216 if entry.is_root {
2217 root_index = Some(index);
2218 }
2219 }
2220 let Some(previous_root_index) = root_index else {
2221 return;
2222 };
2223 this.focus_and_scroll_to_nav_entry(previous_root_index, window, cx);
2224 }),
2225 )
2226 .on_action(cx.listener(|this, _: &FocusNextRootNavEntry, window, cx| {
2227 let entry_index = this
2228 .focused_nav_entry(window, cx)
2229 .unwrap_or(this.navbar_entry);
2230 let mut root_index = None;
2231 for (index, entry) in this.visible_navbar_entries() {
2232 if index <= entry_index {
2233 continue;
2234 }
2235 if entry.is_root {
2236 root_index = Some(index);
2237 break;
2238 }
2239 }
2240 let Some(next_root_index) = root_index else {
2241 return;
2242 };
2243 this.focus_and_scroll_to_nav_entry(next_root_index, window, cx);
2244 }))
2245 .on_action(cx.listener(|this, _: &FocusFirstNavEntry, window, cx| {
2246 if let Some((first_entry_index, _)) = this.visible_navbar_entries().next() {
2247 this.focus_and_scroll_to_nav_entry(first_entry_index, window, cx);
2248 }
2249 }))
2250 .on_action(cx.listener(|this, _: &FocusLastNavEntry, window, cx| {
2251 if let Some((last_entry_index, _)) = this.visible_navbar_entries().last() {
2252 this.focus_and_scroll_to_nav_entry(last_entry_index, window, cx);
2253 }
2254 }))
2255 .on_action(cx.listener(|this, _: &FocusNextNavEntry, window, cx| {
2256 let entry_index = this
2257 .focused_nav_entry(window, cx)
2258 .unwrap_or(this.navbar_entry);
2259 let mut next_index = None;
2260 for (index, _) in this.visible_navbar_entries() {
2261 if index > entry_index {
2262 next_index = Some(index);
2263 break;
2264 }
2265 }
2266 let Some(next_entry_index) = next_index else {
2267 return;
2268 };
2269 this.open_and_scroll_to_navbar_entry(
2270 next_entry_index,
2271 Some(gpui::ScrollStrategy::Bottom),
2272 false,
2273 window,
2274 cx,
2275 );
2276 }))
2277 .on_action(cx.listener(|this, _: &FocusPreviousNavEntry, window, cx| {
2278 let entry_index = this
2279 .focused_nav_entry(window, cx)
2280 .unwrap_or(this.navbar_entry);
2281 let mut prev_index = None;
2282 for (index, _) in this.visible_navbar_entries() {
2283 if index >= entry_index {
2284 break;
2285 }
2286 prev_index = Some(index);
2287 }
2288 let Some(prev_entry_index) = prev_index else {
2289 return;
2290 };
2291 this.open_and_scroll_to_navbar_entry(
2292 prev_entry_index,
2293 Some(gpui::ScrollStrategy::Top),
2294 false,
2295 window,
2296 cx,
2297 );
2298 }))
2299 .w_56()
2300 .h_full()
2301 .p_2p5()
2302 .when(cfg!(target_os = "macos"), |this| this.pt_10())
2303 .flex_none()
2304 .border_r_1()
2305 .border_color(cx.theme().colors().border)
2306 .bg(cx.theme().colors().panel_background)
2307 .child(self.render_search(window, cx))
2308 .child(
2309 v_flex()
2310 .flex_1()
2311 .overflow_hidden()
2312 .track_focus(&self.navbar_focus_handle.focus_handle(cx))
2313 .tab_group()
2314 .tab_index(NAVBAR_GROUP_TAB_INDEX)
2315 .child(
2316 uniform_list(
2317 "settings-ui-nav-bar",
2318 visible_count + 1,
2319 cx.processor(move |this, range: Range<usize>, _, cx| {
2320 this.visible_navbar_entries()
2321 .skip(range.start.saturating_sub(1))
2322 .take(range.len())
2323 .map(|(entry_index, entry)| {
2324 TreeViewItem::new(
2325 ("settings-ui-navbar-entry", entry_index),
2326 entry.title,
2327 )
2328 .track_focus(&entry.focus_handle)
2329 .root_item(entry.is_root)
2330 .toggle_state(this.is_navbar_entry_selected(entry_index))
2331 .when(entry.is_root, |item| {
2332 item.expanded(entry.expanded || this.has_query)
2333 .on_toggle(cx.listener(
2334 move |this, _, window, cx| {
2335 this.toggle_navbar_entry(entry_index);
2336 window.focus(
2337 &this.navbar_entries[entry_index]
2338 .focus_handle,
2339 );
2340 cx.notify();
2341 },
2342 ))
2343 })
2344 .on_click({
2345 let category = this.pages[entry.page_index].title;
2346 let subcategory =
2347 (!entry.is_root).then_some(entry.title);
2348
2349 cx.listener(move |this, _, window, cx| {
2350 telemetry::event!(
2351 "Settings Navigation Clicked",
2352 category = category,
2353 subcategory = subcategory
2354 );
2355
2356 this.open_and_scroll_to_navbar_entry(
2357 entry_index,
2358 None,
2359 true,
2360 window,
2361 cx,
2362 );
2363 })
2364 })
2365 })
2366 .collect()
2367 }),
2368 )
2369 .size_full()
2370 .track_scroll(self.navbar_scroll_handle.clone()),
2371 )
2372 .vertical_scrollbar_for(self.navbar_scroll_handle.clone(), window, cx),
2373 )
2374 .child(
2375 h_flex()
2376 .w_full()
2377 .h_8()
2378 .p_2()
2379 .pb_0p5()
2380 .flex_shrink_0()
2381 .border_t_1()
2382 .border_color(cx.theme().colors().border_variant)
2383 .child(
2384 KeybindingHint::new(
2385 KeyBinding::for_action_in(
2386 &ToggleFocusNav,
2387 &self.navbar_focus_handle.focus_handle(cx),
2388 cx,
2389 ),
2390 cx.theme().colors().surface_background.opacity(0.5),
2391 )
2392 .suffix(focus_keybind_label),
2393 ),
2394 )
2395 }
2396
2397 fn open_and_scroll_to_navbar_entry(
2398 &mut self,
2399 navbar_entry_index: usize,
2400 scroll_strategy: Option<gpui::ScrollStrategy>,
2401 focus_content: bool,
2402 window: &mut Window,
2403 cx: &mut Context<Self>,
2404 ) {
2405 self.open_navbar_entry_page(navbar_entry_index);
2406 cx.notify();
2407
2408 let mut handle_to_focus = None;
2409
2410 if self.navbar_entries[navbar_entry_index].is_root
2411 || !self.is_nav_entry_visible(navbar_entry_index)
2412 {
2413 self.sub_page_scroll_handle
2414 .set_offset(point(px(0.), px(0.)));
2415 if focus_content {
2416 let Some(first_item_index) =
2417 self.visible_page_items().next().map(|(index, _)| index)
2418 else {
2419 return;
2420 };
2421 handle_to_focus = Some(self.focus_handle_for_content_element(first_item_index, cx));
2422 } else if !self.is_nav_entry_visible(navbar_entry_index) {
2423 let Some(first_visible_nav_entry_index) =
2424 self.visible_navbar_entries().next().map(|(index, _)| index)
2425 else {
2426 return;
2427 };
2428 self.focus_and_scroll_to_nav_entry(first_visible_nav_entry_index, window, cx);
2429 } else {
2430 handle_to_focus =
2431 Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2432 }
2433 } else {
2434 let entry_item_index = self.navbar_entries[navbar_entry_index]
2435 .item_index
2436 .expect("Non-root items should have an item index");
2437 self.scroll_to_content_item(entry_item_index, window, cx);
2438 if focus_content {
2439 handle_to_focus = Some(self.focus_handle_for_content_element(entry_item_index, cx));
2440 } else {
2441 handle_to_focus =
2442 Some(self.navbar_entries[navbar_entry_index].focus_handle.clone());
2443 }
2444 }
2445
2446 if let Some(scroll_strategy) = scroll_strategy
2447 && let Some(logical_entry_index) = self
2448 .visible_navbar_entries()
2449 .into_iter()
2450 .position(|(index, _)| index == navbar_entry_index)
2451 {
2452 self.navbar_scroll_handle
2453 .scroll_to_item(logical_entry_index + 1, scroll_strategy);
2454 }
2455
2456 // Page scroll handle updates the active item index
2457 // in it's next paint call after using scroll_handle.scroll_to_top_of_item
2458 // The call after that updates the offset of the scroll handle. So to
2459 // ensure the scroll handle doesn't lag behind we need to render three frames
2460 // back to back.
2461 cx.on_next_frame(window, move |_, window, cx| {
2462 if let Some(handle) = handle_to_focus.as_ref() {
2463 window.focus(handle);
2464 }
2465
2466 cx.on_next_frame(window, |_, _, cx| {
2467 cx.notify();
2468 });
2469 cx.notify();
2470 });
2471 cx.notify();
2472 }
2473
2474 fn scroll_to_content_item(
2475 &self,
2476 content_item_index: usize,
2477 _window: &mut Window,
2478 cx: &mut Context<Self>,
2479 ) {
2480 let index = self
2481 .visible_page_items()
2482 .position(|(index, _)| index == content_item_index)
2483 .unwrap_or(0);
2484 if index == 0 {
2485 self.sub_page_scroll_handle
2486 .set_offset(point(px(0.), px(0.)));
2487 self.list_state.scroll_to(gpui::ListOffset {
2488 item_ix: 0,
2489 offset_in_item: px(0.),
2490 });
2491 return;
2492 }
2493 self.list_state.scroll_to(gpui::ListOffset {
2494 item_ix: index + 1,
2495 offset_in_item: px(0.),
2496 });
2497 cx.notify();
2498 }
2499
2500 fn is_nav_entry_visible(&self, nav_entry_index: usize) -> bool {
2501 self.visible_navbar_entries()
2502 .any(|(index, _)| index == nav_entry_index)
2503 }
2504
2505 fn focus_and_scroll_to_first_visible_nav_entry(
2506 &self,
2507 window: &mut Window,
2508 cx: &mut Context<Self>,
2509 ) {
2510 if let Some(nav_entry_index) = self.visible_navbar_entries().next().map(|(index, _)| index)
2511 {
2512 self.focus_and_scroll_to_nav_entry(nav_entry_index, window, cx);
2513 }
2514 }
2515
2516 fn focus_and_scroll_to_nav_entry(
2517 &self,
2518 nav_entry_index: usize,
2519 window: &mut Window,
2520 cx: &mut Context<Self>,
2521 ) {
2522 let Some(position) = self
2523 .visible_navbar_entries()
2524 .position(|(index, _)| index == nav_entry_index)
2525 else {
2526 return;
2527 };
2528 self.navbar_scroll_handle
2529 .scroll_to_item(position, gpui::ScrollStrategy::Top);
2530 window.focus(&self.navbar_entries[nav_entry_index].focus_handle);
2531 cx.notify();
2532 }
2533
2534 fn visible_page_items(&self) -> impl Iterator<Item = (usize, &SettingsPageItem)> {
2535 let page_idx = self.current_page_index();
2536
2537 self.current_page()
2538 .items
2539 .iter()
2540 .enumerate()
2541 .filter_map(move |(item_index, item)| {
2542 self.filter_table[page_idx][item_index].then_some((item_index, item))
2543 })
2544 }
2545
2546 fn render_sub_page_breadcrumbs(&self) -> impl IntoElement {
2547 let mut items = vec![];
2548 items.push(self.current_page().title.into());
2549 items.extend(
2550 sub_page_stack()
2551 .iter()
2552 .flat_map(|page| [page.section_header.into(), page.link.title.clone()]),
2553 );
2554
2555 let last = items.pop().unwrap();
2556 h_flex()
2557 .gap_1()
2558 .children(
2559 items
2560 .into_iter()
2561 .flat_map(|item| [item, "/".into()])
2562 .map(|item| Label::new(item).color(Color::Muted)),
2563 )
2564 .child(Label::new(last))
2565 }
2566
2567 fn render_empty_state(&self, search_query: SharedString) -> impl IntoElement {
2568 v_flex()
2569 .size_full()
2570 .items_center()
2571 .justify_center()
2572 .gap_1()
2573 .child(Label::new("No Results"))
2574 .child(
2575 Label::new(search_query)
2576 .size(LabelSize::Small)
2577 .color(Color::Muted),
2578 )
2579 }
2580
2581 fn render_page_items(
2582 &mut self,
2583 page_index: usize,
2584 _window: &mut Window,
2585 cx: &mut Context<SettingsWindow>,
2586 ) -> impl IntoElement {
2587 let mut page_content = v_flex().id("settings-ui-page").size_full();
2588
2589 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2590 let has_no_results = self.visible_page_items().next().is_none() && has_active_search;
2591
2592 if has_no_results {
2593 let search_query = self.search_bar.read(cx).text(cx);
2594 page_content = page_content.child(
2595 self.render_empty_state(format!("No settings match \"{}\"", search_query).into()),
2596 )
2597 } else {
2598 let last_non_header_index = self
2599 .visible_page_items()
2600 .filter_map(|(index, item)| {
2601 (!matches!(item, SettingsPageItem::SectionHeader(_))).then_some(index)
2602 })
2603 .last();
2604
2605 let root_nav_label = self
2606 .navbar_entries
2607 .iter()
2608 .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2609 .map(|entry| entry.title);
2610
2611 let list_content = list(
2612 self.list_state.clone(),
2613 cx.processor(move |this, index, window, cx| {
2614 if index == 0 {
2615 return div()
2616 .px_8()
2617 .when(sub_page_stack().is_empty(), |this| {
2618 this.when_some(root_nav_label, |this, title| {
2619 this.child(
2620 Label::new(title).size(LabelSize::Large).mt_2().mb_3(),
2621 )
2622 })
2623 })
2624 .into_any_element();
2625 }
2626
2627 let mut visible_items = this.visible_page_items();
2628 let Some((actual_item_index, item)) = visible_items.nth(index - 1) else {
2629 return gpui::Empty.into_any_element();
2630 };
2631
2632 let no_bottom_border = visible_items
2633 .next()
2634 .map(|(_, item)| matches!(item, SettingsPageItem::SectionHeader(_)))
2635 .unwrap_or(false);
2636
2637 let is_last = Some(actual_item_index) == last_non_header_index;
2638
2639 let item_focus_handle =
2640 this.content_handles[page_index][actual_item_index].focus_handle(cx);
2641
2642 v_flex()
2643 .id(("settings-page-item", actual_item_index))
2644 .track_focus(&item_focus_handle)
2645 .w_full()
2646 .min_w_0()
2647 .child(item.render(
2648 this,
2649 actual_item_index,
2650 no_bottom_border || is_last,
2651 window,
2652 cx,
2653 ))
2654 .into_any_element()
2655 }),
2656 );
2657
2658 page_content = page_content.child(list_content.size_full())
2659 }
2660 page_content
2661 }
2662
2663 fn render_sub_page_items<'a, Items: Iterator<Item = (usize, &'a SettingsPageItem)>>(
2664 &self,
2665 items: Items,
2666 page_index: Option<usize>,
2667 window: &mut Window,
2668 cx: &mut Context<SettingsWindow>,
2669 ) -> impl IntoElement {
2670 let mut page_content = v_flex()
2671 .id("settings-ui-page")
2672 .size_full()
2673 .overflow_y_scroll()
2674 .track_scroll(&self.sub_page_scroll_handle);
2675
2676 let items: Vec<_> = items.collect();
2677 let items_len = items.len();
2678 let mut section_header = None;
2679
2680 let has_active_search = !self.search_bar.read(cx).is_empty(cx);
2681 let has_no_results = items_len == 0 && has_active_search;
2682
2683 if has_no_results {
2684 let search_query = self.search_bar.read(cx).text(cx);
2685 page_content = page_content.child(
2686 self.render_empty_state(format!("No settings match \"{}\"", search_query).into()),
2687 )
2688 } else {
2689 let last_non_header_index = items
2690 .iter()
2691 .enumerate()
2692 .rev()
2693 .find(|(_, (_, item))| !matches!(item, SettingsPageItem::SectionHeader(_)))
2694 .map(|(index, _)| index);
2695
2696 let root_nav_label = self
2697 .navbar_entries
2698 .iter()
2699 .find(|entry| entry.is_root && entry.page_index == self.current_page_index())
2700 .map(|entry| entry.title);
2701
2702 page_content = page_content
2703 .when(sub_page_stack().is_empty(), |this| {
2704 this.when_some(root_nav_label, |this, title| {
2705 this.child(Label::new(title).size(LabelSize::Large).mt_2().mb_3())
2706 })
2707 })
2708 .children(items.clone().into_iter().enumerate().map(
2709 |(index, (actual_item_index, item))| {
2710 let no_bottom_border = items
2711 .get(index + 1)
2712 .map(|(_, next_item)| {
2713 matches!(next_item, SettingsPageItem::SectionHeader(_))
2714 })
2715 .unwrap_or(false);
2716 let is_last = Some(index) == last_non_header_index;
2717
2718 if let SettingsPageItem::SectionHeader(header) = item {
2719 section_header = Some(*header);
2720 }
2721 v_flex()
2722 .w_full()
2723 .min_w_0()
2724 .id(("settings-page-item", actual_item_index))
2725 .when_some(page_index, |element, page_index| {
2726 element.track_focus(
2727 &self.content_handles[page_index][actual_item_index]
2728 .focus_handle(cx),
2729 )
2730 })
2731 .child(item.render(
2732 self,
2733 actual_item_index,
2734 no_bottom_border || is_last,
2735 window,
2736 cx,
2737 ))
2738 },
2739 ))
2740 }
2741 page_content
2742 }
2743
2744 fn render_page(
2745 &mut self,
2746 window: &mut Window,
2747 cx: &mut Context<SettingsWindow>,
2748 ) -> impl IntoElement {
2749 let page_header;
2750 let page_content;
2751
2752 if sub_page_stack().is_empty() {
2753 page_header = self.render_files_header(window, cx).into_any_element();
2754
2755 page_content = self
2756 .render_page_items(self.current_page_index(), window, cx)
2757 .into_any_element();
2758 } else {
2759 page_header = h_flex()
2760 .ml_neg_1p5()
2761 .gap_1()
2762 .child(
2763 IconButton::new("back-btn", IconName::ArrowLeft)
2764 .icon_size(IconSize::Small)
2765 .shape(IconButtonShape::Square)
2766 .on_click(cx.listener(|this, _, _, cx| {
2767 this.pop_sub_page(cx);
2768 })),
2769 )
2770 .child(self.render_sub_page_breadcrumbs())
2771 .into_any_element();
2772
2773 let active_page_render_fn = sub_page_stack().last().unwrap().link.render.clone();
2774 page_content = (active_page_render_fn)(self, window, cx);
2775 }
2776
2777 let mut warning_banner = gpui::Empty.into_any_element();
2778 if let Some(error) =
2779 SettingsStore::global(cx).error_for_file(self.current_file.to_settings())
2780 {
2781 fn banner(
2782 label: &'static str,
2783 error: String,
2784 shown_errors: &mut HashSet<String>,
2785 cx: &mut Context<SettingsWindow>,
2786 ) -> impl IntoElement {
2787 if shown_errors.insert(error.clone()) {
2788 telemetry::event!("Settings Error Shown", label = label, error = &error);
2789 }
2790 Banner::new()
2791 .severity(Severity::Warning)
2792 .child(
2793 v_flex()
2794 .my_0p5()
2795 .gap_0p5()
2796 .child(Label::new(label))
2797 .child(Label::new(error).size(LabelSize::Small).color(Color::Muted)),
2798 )
2799 .action_slot(
2800 div().pr_1().pb_1().child(
2801 Button::new("fix-in-json", "Fix in settings.json")
2802 .tab_index(0_isize)
2803 .style(ButtonStyle::Tinted(ui::TintColor::Warning))
2804 .on_click(cx.listener(|this, _, _, cx| {
2805 this.open_current_settings_file(cx);
2806 })),
2807 ),
2808 )
2809 }
2810
2811 let parse_error = error.parse_error();
2812 let parse_failed = parse_error.is_some();
2813
2814 warning_banner = v_flex()
2815 .gap_2()
2816 .when_some(parse_error, |this, err| {
2817 this.child(banner(
2818 "Failed to load your settings. Some values may be incorrect and changes may be lost.",
2819 err,
2820 &mut self.shown_errors,
2821 cx,
2822 ))
2823 })
2824 .map(|this| match &error.migration_status {
2825 settings::MigrationStatus::Succeeded => this.child(banner(
2826 "Your settings are out of date, and need to be updated.",
2827 match &self.current_file {
2828 SettingsUiFile::User => "They can be automatically migrated to the latest version.",
2829 SettingsUiFile::Server(_) | SettingsUiFile::Project(_) => "They must be manually migrated to the latest version."
2830 }.to_string(),
2831 &mut self.shown_errors,
2832 cx,
2833 )),
2834 settings::MigrationStatus::Failed { error: err } if !parse_failed => this
2835 .child(banner(
2836 "Your settings file is out of date, automatic migration failed",
2837 err.clone(),
2838 &mut self.shown_errors,
2839 cx,
2840 )),
2841 _ => this,
2842 })
2843 .into_any_element()
2844 }
2845
2846 return v_flex()
2847 .id("settings-ui-page")
2848 .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
2849 if !sub_page_stack().is_empty() {
2850 window.focus_next();
2851 return;
2852 }
2853 for (logical_index, (actual_index, _)) in this.visible_page_items().enumerate() {
2854 let handle = this.content_handles[this.current_page_index()][actual_index]
2855 .focus_handle(cx);
2856 let mut offset = 1; // for page header
2857
2858 if let Some((_, next_item)) = this.visible_page_items().nth(logical_index + 1)
2859 && matches!(next_item, SettingsPageItem::SectionHeader(_))
2860 {
2861 offset += 1;
2862 }
2863 if handle.contains_focused(window, cx) {
2864 let next_logical_index = logical_index + offset + 1;
2865 this.list_state.scroll_to_reveal_item(next_logical_index);
2866 // We need to render the next item to ensure it's focus handle is in the element tree
2867 cx.on_next_frame(window, |_, window, cx| {
2868 cx.notify();
2869 cx.on_next_frame(window, |_, window, cx| {
2870 window.focus_next();
2871 cx.notify();
2872 });
2873 });
2874 cx.notify();
2875 return;
2876 }
2877 }
2878 window.focus_next();
2879 }))
2880 .on_action(cx.listener(|this, _: &menu::SelectPrevious, window, cx| {
2881 if !sub_page_stack().is_empty() {
2882 window.focus_prev();
2883 return;
2884 }
2885 let mut prev_was_header = false;
2886 for (logical_index, (actual_index, item)) in this.visible_page_items().enumerate() {
2887 let is_header = matches!(item, SettingsPageItem::SectionHeader(_));
2888 let handle = this.content_handles[this.current_page_index()][actual_index]
2889 .focus_handle(cx);
2890 let mut offset = 1; // for page header
2891
2892 if prev_was_header {
2893 offset -= 1;
2894 }
2895 if handle.contains_focused(window, cx) {
2896 let next_logical_index = logical_index + offset - 1;
2897 this.list_state.scroll_to_reveal_item(next_logical_index);
2898 // We need to render the next item to ensure it's focus handle is in the element tree
2899 cx.on_next_frame(window, |_, window, cx| {
2900 cx.notify();
2901 cx.on_next_frame(window, |_, window, cx| {
2902 window.focus_prev();
2903 cx.notify();
2904 });
2905 });
2906 cx.notify();
2907 return;
2908 }
2909 prev_was_header = is_header;
2910 }
2911 window.focus_prev();
2912 }))
2913 .when(sub_page_stack().is_empty(), |this| {
2914 this.vertical_scrollbar_for(self.list_state.clone(), window, cx)
2915 })
2916 .when(!sub_page_stack().is_empty(), |this| {
2917 this.vertical_scrollbar_for(self.sub_page_scroll_handle.clone(), window, cx)
2918 })
2919 .track_focus(&self.content_focus_handle.focus_handle(cx))
2920 .pt_6()
2921 .gap_4()
2922 .flex_1()
2923 .bg(cx.theme().colors().editor_background)
2924 .child(
2925 v_flex()
2926 .px_8()
2927 .gap_2()
2928 .child(page_header)
2929 .child(warning_banner),
2930 )
2931 .child(
2932 div()
2933 .flex_1()
2934 .size_full()
2935 .tab_group()
2936 .tab_index(CONTENT_GROUP_TAB_INDEX)
2937 .child(page_content),
2938 );
2939 }
2940
2941 /// This function will create a new settings file if one doesn't exist
2942 /// if the current file is a project settings with a valid worktree id
2943 /// We do this because the settings ui allows initializing project settings
2944 fn open_current_settings_file(&mut self, cx: &mut Context<Self>) {
2945 match &self.current_file {
2946 SettingsUiFile::User => {
2947 let Some(original_window) = self.original_window else {
2948 return;
2949 };
2950 original_window
2951 .update(cx, |workspace, window, cx| {
2952 workspace
2953 .with_local_workspace(window, cx, |workspace, window, cx| {
2954 let create_task = workspace.project().update(cx, |project, cx| {
2955 project.find_or_create_worktree(
2956 paths::config_dir().as_path(),
2957 false,
2958 cx,
2959 )
2960 });
2961 let open_task = workspace.open_paths(
2962 vec![paths::settings_file().to_path_buf()],
2963 OpenOptions {
2964 visible: Some(OpenVisible::None),
2965 ..Default::default()
2966 },
2967 None,
2968 window,
2969 cx,
2970 );
2971
2972 cx.spawn_in(window, async move |workspace, cx| {
2973 create_task.await.ok();
2974 open_task.await;
2975
2976 workspace.update_in(cx, |_, window, cx| {
2977 window.activate_window();
2978 cx.notify();
2979 })
2980 })
2981 .detach();
2982 })
2983 .detach();
2984 })
2985 .ok();
2986 }
2987 SettingsUiFile::Project((worktree_id, path)) => {
2988 let settings_path = path.join(paths::local_settings_file_relative_path());
2989 let Some(app_state) = workspace::AppState::global(cx).upgrade() else {
2990 return;
2991 };
2992
2993 let Some((worktree, corresponding_workspace)) = app_state
2994 .workspace_store
2995 .read(cx)
2996 .workspaces()
2997 .iter()
2998 .find_map(|workspace| {
2999 workspace
3000 .read_with(cx, |workspace, cx| {
3001 workspace
3002 .project()
3003 .read(cx)
3004 .worktree_for_id(*worktree_id, cx)
3005 })
3006 .ok()
3007 .flatten()
3008 .zip(Some(*workspace))
3009 })
3010 else {
3011 log::error!(
3012 "No corresponding workspace contains worktree id: {}",
3013 worktree_id
3014 );
3015
3016 return;
3017 };
3018
3019 let create_task = if worktree.read(cx).entry_for_path(&settings_path).is_some() {
3020 None
3021 } else {
3022 Some(worktree.update(cx, |tree, cx| {
3023 tree.create_entry(
3024 settings_path.clone(),
3025 false,
3026 Some("{\n\n}".as_bytes().to_vec()),
3027 cx,
3028 )
3029 }))
3030 };
3031
3032 let worktree_id = *worktree_id;
3033
3034 // TODO: move zed::open_local_file() APIs to this crate, and
3035 // re-implement the "initial_contents" behavior
3036 corresponding_workspace
3037 .update(cx, |_, window, cx| {
3038 cx.spawn_in(window, async move |workspace, cx| {
3039 if let Some(create_task) = create_task {
3040 create_task.await.ok()?;
3041 };
3042
3043 workspace
3044 .update_in(cx, |workspace, window, cx| {
3045 workspace.open_path(
3046 (worktree_id, settings_path.clone()),
3047 None,
3048 true,
3049 window,
3050 cx,
3051 )
3052 })
3053 .ok()?
3054 .await
3055 .log_err()?;
3056
3057 workspace
3058 .update_in(cx, |_, window, cx| {
3059 window.activate_window();
3060 cx.notify();
3061 })
3062 .ok();
3063
3064 Some(())
3065 })
3066 .detach();
3067 })
3068 .ok();
3069 }
3070 SettingsUiFile::Server(_) => {
3071 return;
3072 }
3073 };
3074 }
3075
3076 fn current_page_index(&self) -> usize {
3077 self.page_index_from_navbar_index(self.navbar_entry)
3078 }
3079
3080 fn current_page(&self) -> &SettingsPage {
3081 &self.pages[self.current_page_index()]
3082 }
3083
3084 fn page_index_from_navbar_index(&self, index: usize) -> usize {
3085 if self.navbar_entries.is_empty() {
3086 return 0;
3087 }
3088
3089 self.navbar_entries[index].page_index
3090 }
3091
3092 fn is_navbar_entry_selected(&self, ix: usize) -> bool {
3093 ix == self.navbar_entry
3094 }
3095
3096 fn push_sub_page(
3097 &mut self,
3098 sub_page_link: SubPageLink,
3099 section_header: &'static str,
3100 cx: &mut Context<SettingsWindow>,
3101 ) {
3102 sub_page_stack_mut().push(SubPage {
3103 link: sub_page_link,
3104 section_header,
3105 });
3106 cx.notify();
3107 }
3108
3109 fn pop_sub_page(&mut self, cx: &mut Context<SettingsWindow>) {
3110 sub_page_stack_mut().pop();
3111 cx.notify();
3112 }
3113
3114 fn focus_file_at_index(&mut self, index: usize, window: &mut Window) {
3115 if let Some((_, handle)) = self.files.get(index) {
3116 handle.focus(window);
3117 }
3118 }
3119
3120 fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
3121 if self.files_focus_handle.contains_focused(window, cx)
3122 && let Some(index) = self
3123 .files
3124 .iter()
3125 .position(|(_, handle)| handle.is_focused(window))
3126 {
3127 return index;
3128 }
3129 if let Some(current_file_index) = self
3130 .files
3131 .iter()
3132 .position(|(file, _)| file == &self.current_file)
3133 {
3134 return current_file_index;
3135 }
3136 0
3137 }
3138
3139 fn focus_handle_for_content_element(
3140 &self,
3141 actual_item_index: usize,
3142 cx: &Context<Self>,
3143 ) -> FocusHandle {
3144 let page_index = self.current_page_index();
3145 self.content_handles[page_index][actual_item_index].focus_handle(cx)
3146 }
3147
3148 fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
3149 if !self
3150 .navbar_focus_handle
3151 .focus_handle(cx)
3152 .contains_focused(window, cx)
3153 {
3154 return None;
3155 }
3156 for (index, entry) in self.navbar_entries.iter().enumerate() {
3157 if entry.focus_handle.is_focused(window) {
3158 return Some(index);
3159 }
3160 }
3161 None
3162 }
3163
3164 fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
3165 let mut index = Some(nav_entry_index);
3166 while let Some(prev_index) = index
3167 && !self.navbar_entries[prev_index].is_root
3168 {
3169 index = prev_index.checked_sub(1);
3170 }
3171 return index.expect("No root entry found");
3172 }
3173}
3174
3175impl Render for SettingsWindow {
3176 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3177 let ui_font = theme::setup_ui_font(window, cx);
3178
3179 client_side_decorations(
3180 v_flex()
3181 .text_color(cx.theme().colors().text)
3182 .size_full()
3183 .children(self.title_bar.clone())
3184 .child(
3185 div()
3186 .id("settings-window")
3187 .key_context("SettingsWindow")
3188 .track_focus(&self.focus_handle)
3189 .on_action(cx.listener(|this, _: &OpenCurrentFile, _, cx| {
3190 this.open_current_settings_file(cx);
3191 }))
3192 .on_action(|_: &Minimize, window, _cx| {
3193 window.minimize_window();
3194 })
3195 .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
3196 this.search_bar.focus_handle(cx).focus(window);
3197 }))
3198 .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
3199 if this
3200 .navbar_focus_handle
3201 .focus_handle(cx)
3202 .contains_focused(window, cx)
3203 {
3204 this.open_and_scroll_to_navbar_entry(
3205 this.navbar_entry,
3206 None,
3207 true,
3208 window,
3209 cx,
3210 );
3211 } else {
3212 this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
3213 }
3214 }))
3215 .on_action(cx.listener(
3216 |this, FocusFile(file_index): &FocusFile, window, _| {
3217 this.focus_file_at_index(*file_index as usize, window);
3218 },
3219 ))
3220 .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
3221 let next_index = usize::min(
3222 this.focused_file_index(window, cx) + 1,
3223 this.files.len().saturating_sub(1),
3224 );
3225 this.focus_file_at_index(next_index, window);
3226 }))
3227 .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
3228 let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
3229 this.focus_file_at_index(prev_index, window);
3230 }))
3231 .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
3232 if this
3233 .search_bar
3234 .focus_handle(cx)
3235 .contains_focused(window, cx)
3236 {
3237 this.focus_and_scroll_to_first_visible_nav_entry(window, cx);
3238 } else {
3239 window.focus_next();
3240 }
3241 }))
3242 .on_action(|_: &menu::SelectPrevious, window, _| {
3243 window.focus_prev();
3244 })
3245 .flex()
3246 .flex_row()
3247 .flex_1()
3248 .min_h_0()
3249 .font(ui_font)
3250 .bg(cx.theme().colors().background)
3251 .text_color(cx.theme().colors().text)
3252 .when(!cfg!(target_os = "macos"), |this| {
3253 this.border_t_1().border_color(cx.theme().colors().border)
3254 })
3255 .child(self.render_nav(window, cx))
3256 .child(self.render_page(window, cx)),
3257 ),
3258 window,
3259 cx,
3260 )
3261 }
3262}
3263
3264fn all_projects(cx: &App) -> impl Iterator<Item = Entity<project::Project>> {
3265 workspace::AppState::global(cx)
3266 .upgrade()
3267 .map(|app_state| {
3268 app_state
3269 .workspace_store
3270 .read(cx)
3271 .workspaces()
3272 .iter()
3273 .filter_map(|workspace| Some(workspace.read(cx).ok()?.project().clone()))
3274 })
3275 .into_iter()
3276 .flatten()
3277}
3278
3279fn update_settings_file(
3280 file: SettingsUiFile,
3281 file_name: Option<&'static str>,
3282 cx: &mut App,
3283 update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
3284) -> Result<()> {
3285 telemetry::event!("Settings Change", setting = file_name, type = file.setting_type());
3286
3287 match file {
3288 SettingsUiFile::Project((worktree_id, rel_path)) => {
3289 let rel_path = rel_path.join(paths::local_settings_file_relative_path());
3290 let Some((worktree, project)) = all_projects(cx).find_map(|project| {
3291 project
3292 .read(cx)
3293 .worktree_for_id(worktree_id, cx)
3294 .zip(Some(project))
3295 }) else {
3296 anyhow::bail!("Could not find project with worktree id: {}", worktree_id);
3297 };
3298
3299 project.update(cx, |project, cx| {
3300 let task = if project.contains_local_settings_file(worktree_id, &rel_path, cx) {
3301 None
3302 } else {
3303 Some(worktree.update(cx, |worktree, cx| {
3304 worktree.create_entry(rel_path.clone(), false, None, cx)
3305 }))
3306 };
3307
3308 cx.spawn(async move |project, cx| {
3309 if let Some(task) = task
3310 && task.await.is_err()
3311 {
3312 return;
3313 };
3314
3315 project
3316 .update(cx, |project, cx| {
3317 project.update_local_settings_file(worktree_id, rel_path, cx, update);
3318 })
3319 .ok();
3320 })
3321 .detach();
3322 });
3323
3324 return Ok(());
3325 }
3326 SettingsUiFile::User => {
3327 // todo(settings_ui) error?
3328 SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
3329 Ok(())
3330 }
3331 SettingsUiFile::Server(_) => unimplemented!(),
3332 }
3333}
3334
3335fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
3336 field: SettingField<T>,
3337 file: SettingsUiFile,
3338 metadata: Option<&SettingsFieldMetadata>,
3339 _window: &mut Window,
3340 cx: &mut App,
3341) -> AnyElement {
3342 let (_, initial_text) =
3343 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3344 let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
3345
3346 SettingsInputField::new()
3347 .tab_index(0)
3348 .when_some(initial_text, |editor, text| {
3349 editor.with_initial_text(text.as_ref().to_string())
3350 })
3351 .when_some(
3352 metadata.and_then(|metadata| metadata.placeholder),
3353 |editor, placeholder| editor.with_placeholder(placeholder),
3354 )
3355 .on_confirm({
3356 move |new_text, cx| {
3357 update_settings_file(file.clone(), field.json_path, cx, move |settings, _cx| {
3358 (field.write)(settings, new_text.map(Into::into));
3359 })
3360 .log_err(); // todo(settings_ui) don't log err
3361 }
3362 })
3363 .into_any_element()
3364}
3365
3366fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
3367 field: SettingField<B>,
3368 file: SettingsUiFile,
3369 _metadata: Option<&SettingsFieldMetadata>,
3370 _window: &mut Window,
3371 cx: &mut App,
3372) -> AnyElement {
3373 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3374
3375 let toggle_state = if value.copied().map_or(false, Into::into) {
3376 ToggleState::Selected
3377 } else {
3378 ToggleState::Unselected
3379 };
3380
3381 Switch::new("toggle_button", toggle_state)
3382 .tab_index(0_isize)
3383 .color(SwitchColor::Accent)
3384 .on_click({
3385 move |state, _window, cx| {
3386 telemetry::event!("Settings Change", setting = field.json_path, type = file.setting_type());
3387
3388 let state = *state == ui::ToggleState::Selected;
3389 update_settings_file(file.clone(), field.json_path, cx, move |settings, _cx| {
3390 (field.write)(settings, Some(state.into()));
3391 })
3392 .log_err(); // todo(settings_ui) don't log err
3393 }
3394 })
3395 .into_any_element()
3396}
3397
3398fn render_number_field<T: NumberFieldType + Send + Sync>(
3399 field: SettingField<T>,
3400 file: SettingsUiFile,
3401 _metadata: Option<&SettingsFieldMetadata>,
3402 window: &mut Window,
3403 cx: &mut App,
3404) -> AnyElement {
3405 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3406 let value = value.copied().unwrap_or_else(T::min_value);
3407 NumberField::new("numeric_stepper", value, window, cx)
3408 .on_change({
3409 move |value, _window, cx| {
3410 let value = *value;
3411 update_settings_file(file.clone(), field.json_path, cx, move |settings, _cx| {
3412 (field.write)(settings, Some(value));
3413 })
3414 .log_err(); // todo(settings_ui) don't log err
3415 }
3416 })
3417 .into_any_element()
3418}
3419
3420fn render_dropdown<T>(
3421 field: SettingField<T>,
3422 file: SettingsUiFile,
3423 metadata: Option<&SettingsFieldMetadata>,
3424 window: &mut Window,
3425 cx: &mut App,
3426) -> AnyElement
3427where
3428 T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
3429{
3430 let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
3431 let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
3432 let should_do_titlecase = metadata
3433 .and_then(|metadata| metadata.should_do_titlecase)
3434 .unwrap_or(true);
3435
3436 let (_, current_value) =
3437 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3438 let current_value = current_value.copied().unwrap_or(variants()[0]);
3439
3440 let current_value_label =
3441 labels()[variants().iter().position(|v| *v == current_value).unwrap()];
3442
3443 DropdownMenu::new(
3444 "dropdown",
3445 if should_do_titlecase {
3446 current_value_label.to_title_case()
3447 } else {
3448 current_value_label.to_string()
3449 },
3450 window.use_state(cx, |window, cx| {
3451 ContextMenu::new(window, cx, move |mut menu, _, _| {
3452 for (&value, &label) in std::iter::zip(variants(), labels()) {
3453 let file = file.clone();
3454 menu = menu.toggleable_entry(
3455 if should_do_titlecase {
3456 label.to_title_case()
3457 } else {
3458 label.to_string()
3459 },
3460 value == current_value,
3461 IconPosition::End,
3462 None,
3463 move |_, cx| {
3464 if value == current_value {
3465 return;
3466 }
3467 update_settings_file(
3468 file.clone(),
3469 field.json_path,
3470 cx,
3471 move |settings, _cx| {
3472 (field.write)(settings, Some(value));
3473 },
3474 )
3475 .log_err(); // todo(settings_ui) don't log err
3476 },
3477 );
3478 }
3479 menu
3480 })
3481 }),
3482 )
3483 .tab_index(0)
3484 .trigger_size(ButtonSize::Medium)
3485 .style(DropdownStyle::Outlined)
3486 .offset(gpui::Point {
3487 x: px(0.0),
3488 y: px(2.0),
3489 })
3490 .into_any_element()
3491}
3492
3493fn render_picker_trigger_button(id: SharedString, label: SharedString) -> Button {
3494 Button::new(id, label)
3495 .tab_index(0_isize)
3496 .style(ButtonStyle::Outlined)
3497 .size(ButtonSize::Medium)
3498 .icon(IconName::ChevronUpDown)
3499 .icon_color(Color::Muted)
3500 .icon_size(IconSize::Small)
3501 .icon_position(IconPosition::End)
3502}
3503
3504fn render_font_picker(
3505 field: SettingField<settings::FontFamilyName>,
3506 file: SettingsUiFile,
3507 _metadata: Option<&SettingsFieldMetadata>,
3508 _window: &mut Window,
3509 cx: &mut App,
3510) -> AnyElement {
3511 let current_value = SettingsStore::global(cx)
3512 .get_value_from_file(file.to_settings(), field.pick)
3513 .1
3514 .cloned()
3515 .unwrap_or_else(|| SharedString::default().into());
3516
3517 PopoverMenu::new("font-picker")
3518 .trigger(render_picker_trigger_button(
3519 "font_family_picker_trigger".into(),
3520 current_value.clone().into(),
3521 ))
3522 .menu(move |window, cx| {
3523 let file = file.clone();
3524 let current_value = current_value.clone();
3525
3526 Some(cx.new(move |cx| {
3527 font_picker(
3528 current_value.clone().into(),
3529 move |font_name, cx| {
3530 update_settings_file(
3531 file.clone(),
3532 field.json_path,
3533 cx,
3534 move |settings, _cx| {
3535 (field.write)(settings, Some(font_name.into()));
3536 },
3537 )
3538 .log_err(); // todo(settings_ui) don't log err
3539 },
3540 window,
3541 cx,
3542 )
3543 }))
3544 })
3545 .anchor(gpui::Corner::TopLeft)
3546 .offset(gpui::Point {
3547 x: px(0.0),
3548 y: px(2.0),
3549 })
3550 .with_handle(ui::PopoverMenuHandle::default())
3551 .into_any_element()
3552}
3553
3554fn render_theme_picker(
3555 field: SettingField<settings::ThemeName>,
3556 file: SettingsUiFile,
3557 _metadata: Option<&SettingsFieldMetadata>,
3558 _window: &mut Window,
3559 cx: &mut App,
3560) -> AnyElement {
3561 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3562 let current_value = value
3563 .cloned()
3564 .map(|theme_name| theme_name.0.into())
3565 .unwrap_or_else(|| cx.theme().name.clone());
3566
3567 PopoverMenu::new("theme-picker")
3568 .trigger(render_picker_trigger_button(
3569 "theme_picker_trigger".into(),
3570 current_value.clone(),
3571 ))
3572 .menu(move |window, cx| {
3573 Some(cx.new(|cx| {
3574 let file = file.clone();
3575 let current_value = current_value.clone();
3576 theme_picker(
3577 current_value,
3578 move |theme_name, cx| {
3579 update_settings_file(
3580 file.clone(),
3581 field.json_path,
3582 cx,
3583 move |settings, _cx| {
3584 (field.write)(
3585 settings,
3586 Some(settings::ThemeName(theme_name.into())),
3587 );
3588 },
3589 )
3590 .log_err(); // todo(settings_ui) don't log err
3591 },
3592 window,
3593 cx,
3594 )
3595 }))
3596 })
3597 .anchor(gpui::Corner::TopLeft)
3598 .offset(gpui::Point {
3599 x: px(0.0),
3600 y: px(2.0),
3601 })
3602 .with_handle(ui::PopoverMenuHandle::default())
3603 .into_any_element()
3604}
3605
3606fn render_icon_theme_picker(
3607 field: SettingField<settings::IconThemeName>,
3608 file: SettingsUiFile,
3609 _metadata: Option<&SettingsFieldMetadata>,
3610 _window: &mut Window,
3611 cx: &mut App,
3612) -> AnyElement {
3613 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
3614 let current_value = value
3615 .cloned()
3616 .map(|theme_name| theme_name.0.into())
3617 .unwrap_or_else(|| cx.theme().name.clone());
3618
3619 PopoverMenu::new("icon-theme-picker")
3620 .trigger(render_picker_trigger_button(
3621 "icon_theme_picker_trigger".into(),
3622 current_value.clone(),
3623 ))
3624 .menu(move |window, cx| {
3625 Some(cx.new(|cx| {
3626 let file = file.clone();
3627 let current_value = current_value.clone();
3628 icon_theme_picker(
3629 current_value,
3630 move |theme_name, cx| {
3631 update_settings_file(
3632 file.clone(),
3633 field.json_path,
3634 cx,
3635 move |settings, _cx| {
3636 (field.write)(
3637 settings,
3638 Some(settings::IconThemeName(theme_name.into())),
3639 );
3640 },
3641 )
3642 .log_err(); // todo(settings_ui) don't log err
3643 },
3644 window,
3645 cx,
3646 )
3647 }))
3648 })
3649 .anchor(gpui::Corner::TopLeft)
3650 .offset(gpui::Point {
3651 x: px(0.0),
3652 y: px(2.0),
3653 })
3654 .with_handle(ui::PopoverMenuHandle::default())
3655 .into_any_element()
3656}
3657
3658#[cfg(test)]
3659pub mod test {
3660
3661 use super::*;
3662
3663 impl SettingsWindow {
3664 fn navbar_entry(&self) -> usize {
3665 self.navbar_entry
3666 }
3667 }
3668
3669 impl PartialEq for NavBarEntry {
3670 fn eq(&self, other: &Self) -> bool {
3671 self.title == other.title
3672 && self.is_root == other.is_root
3673 && self.expanded == other.expanded
3674 && self.page_index == other.page_index
3675 && self.item_index == other.item_index
3676 // ignoring focus_handle
3677 }
3678 }
3679
3680 pub fn register_settings(cx: &mut App) {
3681 settings::init(cx);
3682 theme::init(theme::LoadThemes::JustBase, cx);
3683 workspace::init_settings(cx);
3684 project::Project::init_settings(cx);
3685 language::init(cx);
3686 editor::init(cx);
3687 menu::init();
3688 }
3689
3690 fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
3691 let mut pages: Vec<SettingsPage> = Vec::new();
3692 let mut expanded_pages = Vec::new();
3693 let mut selected_idx = None;
3694 let mut index = 0;
3695 let mut in_expanded_section = false;
3696
3697 for mut line in input
3698 .lines()
3699 .map(|line| line.trim())
3700 .filter(|line| !line.is_empty())
3701 {
3702 if let Some(pre) = line.strip_suffix('*') {
3703 assert!(selected_idx.is_none(), "Only one selected entry allowed");
3704 selected_idx = Some(index);
3705 line = pre;
3706 }
3707 let (kind, title) = line.split_once(" ").unwrap();
3708 assert_eq!(kind.len(), 1);
3709 let kind = kind.chars().next().unwrap();
3710 if kind == 'v' {
3711 let page_idx = pages.len();
3712 expanded_pages.push(page_idx);
3713 pages.push(SettingsPage {
3714 title,
3715 items: vec![],
3716 });
3717 index += 1;
3718 in_expanded_section = true;
3719 } else if kind == '>' {
3720 pages.push(SettingsPage {
3721 title,
3722 items: vec![],
3723 });
3724 index += 1;
3725 in_expanded_section = false;
3726 } else if kind == '-' {
3727 pages
3728 .last_mut()
3729 .unwrap()
3730 .items
3731 .push(SettingsPageItem::SectionHeader(title));
3732 if selected_idx == Some(index) && !in_expanded_section {
3733 panic!("Items in unexpanded sections cannot be selected");
3734 }
3735 index += 1;
3736 } else {
3737 panic!(
3738 "Entries must start with one of 'v', '>', or '-'\n line: {}",
3739 line
3740 );
3741 }
3742 }
3743
3744 let mut settings_window = SettingsWindow {
3745 title_bar: None,
3746 original_window: None,
3747 worktree_root_dirs: HashMap::default(),
3748 files: Vec::default(),
3749 current_file: crate::SettingsUiFile::User,
3750 pages,
3751 search_bar: cx.new(|cx| Editor::single_line(window, cx)),
3752 navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
3753 navbar_entries: Vec::default(),
3754 navbar_scroll_handle: UniformListScrollHandle::default(),
3755 navbar_focus_subscriptions: vec![],
3756 filter_table: vec![],
3757 has_query: false,
3758 content_handles: vec![],
3759 search_task: None,
3760 sub_page_scroll_handle: ScrollHandle::new(),
3761 focus_handle: cx.focus_handle(),
3762 navbar_focus_handle: NonFocusableHandle::new(
3763 NAVBAR_CONTAINER_TAB_INDEX,
3764 false,
3765 window,
3766 cx,
3767 ),
3768 content_focus_handle: NonFocusableHandle::new(
3769 CONTENT_CONTAINER_TAB_INDEX,
3770 false,
3771 window,
3772 cx,
3773 ),
3774 files_focus_handle: cx.focus_handle(),
3775 search_index: None,
3776 list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
3777 shown_errors: HashSet::default(),
3778 };
3779
3780 settings_window.build_filter_table();
3781 settings_window.build_navbar(cx);
3782 for expanded_page_index in expanded_pages {
3783 for entry in &mut settings_window.navbar_entries {
3784 if entry.page_index == expanded_page_index && entry.is_root {
3785 entry.expanded = true;
3786 }
3787 }
3788 }
3789 settings_window
3790 }
3791
3792 #[track_caller]
3793 fn check_navbar_toggle(
3794 before: &'static str,
3795 toggle_page: &'static str,
3796 after: &'static str,
3797 window: &mut Window,
3798 cx: &mut App,
3799 ) {
3800 let mut settings_window = parse(before, window, cx);
3801 let toggle_page_idx = settings_window
3802 .pages
3803 .iter()
3804 .position(|page| page.title == toggle_page)
3805 .expect("page not found");
3806 let toggle_idx = settings_window
3807 .navbar_entries
3808 .iter()
3809 .position(|entry| entry.page_index == toggle_page_idx)
3810 .expect("page not found");
3811 settings_window.toggle_navbar_entry(toggle_idx);
3812
3813 let expected_settings_window = parse(after, window, cx);
3814
3815 pretty_assertions::assert_eq!(
3816 settings_window
3817 .visible_navbar_entries()
3818 .map(|(_, entry)| entry)
3819 .collect::<Vec<_>>(),
3820 expected_settings_window
3821 .visible_navbar_entries()
3822 .map(|(_, entry)| entry)
3823 .collect::<Vec<_>>(),
3824 );
3825 pretty_assertions::assert_eq!(
3826 settings_window.navbar_entries[settings_window.navbar_entry()],
3827 expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
3828 );
3829 }
3830
3831 macro_rules! check_navbar_toggle {
3832 ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
3833 #[gpui::test]
3834 fn $name(cx: &mut gpui::TestAppContext) {
3835 let window = cx.add_empty_window();
3836 window.update(|window, cx| {
3837 register_settings(cx);
3838 check_navbar_toggle($before, $toggle_page, $after, window, cx);
3839 });
3840 }
3841 };
3842 }
3843
3844 check_navbar_toggle!(
3845 navbar_basic_open,
3846 before: r"
3847 v General
3848 - General
3849 - Privacy*
3850 v Project
3851 - Project Settings
3852 ",
3853 toggle_page: "General",
3854 after: r"
3855 > General*
3856 v Project
3857 - Project Settings
3858 "
3859 );
3860
3861 check_navbar_toggle!(
3862 navbar_basic_close,
3863 before: r"
3864 > General*
3865 - General
3866 - Privacy
3867 v Project
3868 - Project Settings
3869 ",
3870 toggle_page: "General",
3871 after: r"
3872 v General*
3873 - General
3874 - Privacy
3875 v Project
3876 - Project Settings
3877 "
3878 );
3879
3880 check_navbar_toggle!(
3881 navbar_basic_second_root_entry_close,
3882 before: r"
3883 > General
3884 - General
3885 - Privacy
3886 v Project
3887 - Project Settings*
3888 ",
3889 toggle_page: "Project",
3890 after: r"
3891 > General
3892 > Project*
3893 "
3894 );
3895
3896 check_navbar_toggle!(
3897 navbar_toggle_subroot,
3898 before: r"
3899 v General Page
3900 - General
3901 - Privacy
3902 v Project
3903 - Worktree Settings Content*
3904 v AI
3905 - General
3906 > Appearance & Behavior
3907 ",
3908 toggle_page: "Project",
3909 after: r"
3910 v General Page
3911 - General
3912 - Privacy
3913 > Project*
3914 v AI
3915 - General
3916 > Appearance & Behavior
3917 "
3918 );
3919
3920 check_navbar_toggle!(
3921 navbar_toggle_close_propagates_selected_index,
3922 before: r"
3923 v General Page
3924 - General
3925 - Privacy
3926 v Project
3927 - Worktree Settings Content
3928 v AI
3929 - General*
3930 > Appearance & Behavior
3931 ",
3932 toggle_page: "General Page",
3933 after: r"
3934 > General Page*
3935 v Project
3936 - Worktree Settings Content
3937 v AI
3938 - General
3939 > Appearance & Behavior
3940 "
3941 );
3942
3943 check_navbar_toggle!(
3944 navbar_toggle_expand_propagates_selected_index,
3945 before: r"
3946 > General Page
3947 - General
3948 - Privacy
3949 v Project
3950 - Worktree Settings Content
3951 v AI
3952 - General*
3953 > Appearance & Behavior
3954 ",
3955 toggle_page: "General Page",
3956 after: r"
3957 v General Page*
3958 - General
3959 - Privacy
3960 v Project
3961 - Worktree Settings Content
3962 v AI
3963 - General
3964 > Appearance & Behavior
3965 "
3966 );
3967}