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