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