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