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