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