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