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