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