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