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