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