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