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