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