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