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