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