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