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