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