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