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