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