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