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