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