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