1mod components;
2mod page_data;
3pub mod pages;
4
5use anyhow::{Context as _, Result};
6use editor::{Editor, EditorEvent};
7use futures::{StreamExt, channel::mpsc};
8use fuzzy::StringMatchCandidate;
9use gpui::{
10 Action, App, AsyncApp, ClipboardItem, DEFAULT_ADDITIONAL_WINDOW_SIZE, Div, Entity, FocusHandle,
11 Focusable, Global, KeyContext, ListState, ReadGlobal as _, ScrollHandle, Stateful,
12 Subscription, Task, Tiling, TitlebarOptions, UniformListScrollHandle, WeakEntity, Window,
13 WindowBounds, WindowHandle, WindowOptions, actions, div, list, point, prelude::*, px,
14 uniform_list,
15};
16
17use language::Buffer;
18use platform_title_bar::PlatformTitleBar;
19use project::{Project, ProjectPath, Worktree, WorktreeId};
20use release_channel::ReleaseChannel;
21use schemars::JsonSchema;
22use serde::Deserialize;
23use settings::{
24 IntoGpui, Settings, SettingsContent, SettingsStore, initial_project_settings_content,
25};
26use std::{
27 any::{Any, TypeId, type_name},
28 cell::RefCell,
29 collections::{HashMap, HashSet},
30 num::{NonZero, NonZeroU32},
31 ops::Range,
32 rc::Rc,
33 sync::{Arc, LazyLock, RwLock},
34 time::Duration,
35};
36use theme::ThemeSettings;
37use ui::{
38 Banner, ContextMenu, Divider, DropdownMenu, DropdownStyle, IconButtonShape, KeyBinding,
39 KeybindingHint, PopoverMenu, Scrollbars, Switch, Tooltip, TreeViewItem, WithScrollbar,
40 prelude::*,
41};
42
43use util::{ResultExt as _, paths::PathStyle, rel_path::RelPath};
44use workspace::{
45 AppState, MultiWorkspace, OpenOptions, OpenVisible, Workspace, client_side_decorations,
46};
47use zed_actions::{OpenProjectSettings, OpenSettings, OpenSettingsAt};
48
49use crate::components::{
50 EnumVariantDropdown, NumberField, NumberFieldMode, NumberFieldType, SettingsInputField,
51 SettingsSectionHeader, font_picker, icon_theme_picker, render_ollama_model_picker,
52 theme_picker,
53};
54use crate::pages::{render_input_audio_device_dropdown, render_output_audio_device_dropdown};
55
56const NAVBAR_CONTAINER_TAB_INDEX: isize = 0;
57const NAVBAR_GROUP_TAB_INDEX: isize = 1;
58
59const HEADER_CONTAINER_TAB_INDEX: isize = 2;
60const HEADER_GROUP_TAB_INDEX: isize = 3;
61
62const CONTENT_CONTAINER_TAB_INDEX: isize = 4;
63const CONTENT_GROUP_TAB_INDEX: isize = 5;
64
65actions!(
66 settings_editor,
67 [
68 /// Minimizes the settings UI window.
69 Minimize,
70 /// Toggles focus between the navbar and the main content.
71 ToggleFocusNav,
72 /// Expands the navigation entry.
73 ExpandNavEntry,
74 /// Collapses the navigation entry.
75 CollapseNavEntry,
76 /// Focuses the next file in the file list.
77 FocusNextFile,
78 /// Focuses the previous file in the file list.
79 FocusPreviousFile,
80 /// Opens an editor for the current file
81 OpenCurrentFile,
82 /// Focuses the previous root navigation entry.
83 FocusPreviousRootNavEntry,
84 /// Focuses the next root navigation entry.
85 FocusNextRootNavEntry,
86 /// Focuses the first navigation entry.
87 FocusFirstNavEntry,
88 /// Focuses the last navigation entry.
89 FocusLastNavEntry,
90 /// Focuses and opens the next navigation entry without moving focus to content.
91 FocusNextNavEntry,
92 /// Focuses and opens the previous navigation entry without moving focus to content.
93 FocusPreviousNavEntry
94 ]
95);
96
97#[derive(Action, PartialEq, Eq, Clone, Copy, Debug, JsonSchema, Deserialize)]
98#[action(namespace = settings_editor)]
99struct FocusFile(pub u32);
100
101struct SettingField<T: 'static> {
102 pick: fn(&SettingsContent) -> Option<&T>,
103 write: fn(&mut SettingsContent, Option<T>),
104
105 /// A json-path-like string that gives a unique-ish string that identifies
106 /// where in the JSON the setting is defined.
107 ///
108 /// The syntax is `jq`-like, but modified slightly to be URL-safe (and
109 /// without the leading dot), e.g. `foo.bar`.
110 ///
111 /// They are URL-safe (this is important since links are the main use-case
112 /// for these paths).
113 ///
114 /// There are a couple of special cases:
115 /// - discrimminants are represented with a trailing `$`, for example
116 /// `terminal.working_directory$`. This is to distinguish the discrimminant
117 /// setting (i.e. the setting that changes whether the value is a string or
118 /// an object) from the setting in the case that it is a string.
119 /// - language-specific settings begin `languages.$(language)`. Links
120 /// targeting these settings should take the form `languages/Rust/...`, for
121 /// example, but are not currently supported.
122 json_path: Option<&'static str>,
123}
124
125impl<T: 'static> Clone for SettingField<T> {
126 fn clone(&self) -> Self {
127 *self
128 }
129}
130
131// manual impl because derive puts a Copy bound on T, which is inaccurate in our case
132impl<T: 'static> Copy for SettingField<T> {}
133
134/// Helper for unimplemented settings, used in combination with `SettingField::unimplemented`
135/// to keep the setting around in the UI with valid pick and write implementations, but don't actually try to render it.
136/// TODO(settings_ui): In non-dev builds (`#[cfg(not(debug_assertions))]`) make this render as edit-in-json
137#[derive(Clone, Copy)]
138struct UnimplementedSettingField;
139
140impl PartialEq for UnimplementedSettingField {
141 fn eq(&self, _other: &Self) -> bool {
142 true
143 }
144}
145
146impl<T: 'static> SettingField<T> {
147 /// Helper for settings with types that are not yet implemented.
148 #[allow(unused)]
149 fn unimplemented(self) -> SettingField<UnimplementedSettingField> {
150 SettingField {
151 pick: |_| Some(&UnimplementedSettingField),
152 write: |_, _| unreachable!(),
153 json_path: self.json_path,
154 }
155 }
156}
157
158trait AnySettingField {
159 fn as_any(&self) -> &dyn Any;
160 fn type_name(&self) -> &'static str;
161 fn type_id(&self) -> TypeId;
162 // Returns the file this value was set in and true, or File::Default and false to indicate it was not found in any file (missing default)
163 fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool);
164 fn reset_to_default_fn(
165 &self,
166 current_file: &SettingsUiFile,
167 file_set_in: &settings::SettingsFile,
168 cx: &App,
169 ) -> Option<Box<dyn Fn(&mut Window, &mut App)>>;
170
171 fn json_path(&self) -> Option<&'static str>;
172}
173
174impl<T: PartialEq + Clone + Send + Sync + 'static> AnySettingField for SettingField<T> {
175 fn as_any(&self) -> &dyn Any {
176 self
177 }
178
179 fn type_name(&self) -> &'static str {
180 type_name::<T>()
181 }
182
183 fn type_id(&self) -> TypeId {
184 TypeId::of::<T>()
185 }
186
187 fn file_set_in(&self, file: SettingsUiFile, cx: &App) -> (settings::SettingsFile, bool) {
188 let (file, value) = cx
189 .global::<SettingsStore>()
190 .get_value_from_file(file.to_settings(), self.pick);
191 return (file, value.is_some());
192 }
193
194 fn reset_to_default_fn(
195 &self,
196 current_file: &SettingsUiFile,
197 file_set_in: &settings::SettingsFile,
198 cx: &App,
199 ) -> Option<Box<dyn Fn(&mut Window, &mut App)>> {
200 if file_set_in == &settings::SettingsFile::Default {
201 return None;
202 }
203 if file_set_in != ¤t_file.to_settings() {
204 return None;
205 }
206 let this = *self;
207 let store = SettingsStore::global(cx);
208 let default_value = (this.pick)(store.raw_default_settings());
209 let is_default = store
210 .get_content_for_file(file_set_in.clone())
211 .map_or(None, this.pick)
212 == default_value;
213 if is_default {
214 return None;
215 }
216 let current_file = current_file.clone();
217
218 return Some(Box::new(move |window, cx| {
219 let store = SettingsStore::global(cx);
220 let default_value = (this.pick)(store.raw_default_settings());
221 let is_set_somewhere_other_than_default = store
222 .get_value_up_to_file(current_file.to_settings(), this.pick)
223 .0
224 != settings::SettingsFile::Default;
225 let value_to_set = if is_set_somewhere_other_than_default {
226 default_value.cloned()
227 } else {
228 None
229 };
230 update_settings_file(
231 current_file.clone(),
232 None,
233 window,
234 cx,
235 move |settings, _| {
236 (this.write)(settings, value_to_set);
237 },
238 )
239 // todo(settings_ui): Don't log err
240 .log_err();
241 }));
242 }
243
244 fn json_path(&self) -> Option<&'static str> {
245 self.json_path
246 }
247}
248
249#[derive(Default, Clone)]
250struct SettingFieldRenderer {
251 renderers: Rc<
252 RefCell<
253 HashMap<
254 TypeId,
255 Box<
256 dyn Fn(
257 &SettingsWindow,
258 &SettingItem,
259 SettingsUiFile,
260 Option<&SettingsFieldMetadata>,
261 bool,
262 &mut Window,
263 &mut Context<SettingsWindow>,
264 ) -> Stateful<Div>,
265 >,
266 >,
267 >,
268 >,
269}
270
271impl Global for SettingFieldRenderer {}
272
273impl SettingFieldRenderer {
274 fn add_basic_renderer<T: 'static>(
275 &mut self,
276 render_control: impl Fn(
277 SettingField<T>,
278 SettingsUiFile,
279 Option<&SettingsFieldMetadata>,
280 &mut Window,
281 &mut App,
282 ) -> AnyElement
283 + 'static,
284 ) -> &mut Self {
285 self.add_renderer(
286 move |settings_window: &SettingsWindow,
287 item: &SettingItem,
288 field: SettingField<T>,
289 settings_file: SettingsUiFile,
290 metadata: Option<&SettingsFieldMetadata>,
291 sub_field: bool,
292 window: &mut Window,
293 cx: &mut Context<SettingsWindow>| {
294 render_settings_item(
295 settings_window,
296 item,
297 settings_file.clone(),
298 render_control(field, settings_file, metadata, window, cx),
299 sub_field,
300 cx,
301 )
302 },
303 )
304 }
305
306 fn add_renderer<T: 'static>(
307 &mut self,
308 renderer: impl Fn(
309 &SettingsWindow,
310 &SettingItem,
311 SettingField<T>,
312 SettingsUiFile,
313 Option<&SettingsFieldMetadata>,
314 bool,
315 &mut Window,
316 &mut Context<SettingsWindow>,
317 ) -> Stateful<Div>
318 + 'static,
319 ) -> &mut Self {
320 let key = TypeId::of::<T>();
321 let renderer = Box::new(
322 move |settings_window: &SettingsWindow,
323 item: &SettingItem,
324 settings_file: SettingsUiFile,
325 metadata: Option<&SettingsFieldMetadata>,
326 sub_field: bool,
327 window: &mut Window,
328 cx: &mut Context<SettingsWindow>| {
329 let field = *item
330 .field
331 .as_ref()
332 .as_any()
333 .downcast_ref::<SettingField<T>>()
334 .unwrap();
335 renderer(
336 settings_window,
337 item,
338 field,
339 settings_file,
340 metadata,
341 sub_field,
342 window,
343 cx,
344 )
345 },
346 );
347 self.renderers.borrow_mut().insert(key, renderer);
348 self
349 }
350}
351
352struct NonFocusableHandle {
353 handle: FocusHandle,
354 _subscription: Subscription,
355}
356
357impl NonFocusableHandle {
358 fn new(tab_index: isize, tab_stop: bool, window: &mut Window, cx: &mut App) -> Entity<Self> {
359 let handle = cx.focus_handle().tab_index(tab_index).tab_stop(tab_stop);
360 Self::from_handle(handle, window, cx)
361 }
362
363 fn from_handle(handle: FocusHandle, window: &mut Window, cx: &mut App) -> Entity<Self> {
364 cx.new(|cx| {
365 let _subscription = cx.on_focus(&handle, window, {
366 move |_, window, cx| {
367 window.focus_next(cx);
368 }
369 });
370 Self {
371 handle,
372 _subscription,
373 }
374 })
375 }
376}
377
378impl Focusable for NonFocusableHandle {
379 fn focus_handle(&self, _: &App) -> FocusHandle {
380 self.handle.clone()
381 }
382}
383
384#[derive(Default)]
385struct SettingsFieldMetadata {
386 placeholder: Option<&'static str>,
387 should_do_titlecase: Option<bool>,
388}
389
390pub fn init(cx: &mut App) {
391 init_renderers(cx);
392 let queue = ProjectSettingsUpdateQueue::new(cx);
393 cx.set_global(queue);
394
395 cx.on_action(|_: &OpenSettings, cx| {
396 open_settings_editor(None, None, None, cx);
397 });
398
399 cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
400 workspace
401 .register_action(|_, OpenSettingsAt { path }: &OpenSettingsAt, window, cx| {
402 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
403 open_settings_editor(Some(&path), None, window_handle, cx);
404 })
405 .register_action(|_, _: &OpenSettings, window, cx| {
406 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
407 open_settings_editor(None, None, window_handle, cx);
408 })
409 .register_action(|workspace, _: &OpenProjectSettings, window, cx| {
410 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
411 let target_worktree_id = workspace
412 .project()
413 .read(cx)
414 .visible_worktrees(cx)
415 .find_map(|tree| {
416 tree.read(cx)
417 .root_entry()?
418 .is_dir()
419 .then_some(tree.read(cx).id())
420 });
421 open_settings_editor(None, target_worktree_id, window_handle, cx);
422 });
423 })
424 .detach();
425}
426
427fn init_renderers(cx: &mut App) {
428 cx.default_global::<SettingFieldRenderer>()
429 .add_renderer::<UnimplementedSettingField>(
430 |settings_window, item, _, settings_file, _, sub_field, _, cx| {
431 render_settings_item(
432 settings_window,
433 item,
434 settings_file,
435 Button::new("open-in-settings-file", "Edit in settings.json")
436 .style(ButtonStyle::Outlined)
437 .size(ButtonSize::Medium)
438 .tab_index(0_isize)
439 .tooltip(Tooltip::for_action_title_in(
440 "Edit in settings.json",
441 &OpenCurrentFile,
442 &settings_window.focus_handle,
443 ))
444 .on_click(cx.listener(|this, _, window, cx| {
445 this.open_current_settings_file(window, cx);
446 }))
447 .into_any_element(),
448 sub_field,
449 cx,
450 )
451 },
452 )
453 .add_basic_renderer::<bool>(render_toggle_button)
454 .add_basic_renderer::<String>(render_text_field)
455 .add_basic_renderer::<SharedString>(render_text_field)
456 .add_basic_renderer::<settings::SaturatingBool>(render_toggle_button)
457 .add_basic_renderer::<settings::CursorShape>(render_dropdown)
458 .add_basic_renderer::<settings::RestoreOnStartupBehavior>(render_dropdown)
459 .add_basic_renderer::<settings::BottomDockLayout>(render_dropdown)
460 .add_basic_renderer::<settings::OnLastWindowClosed>(render_dropdown)
461 .add_basic_renderer::<settings::CloseWindowWhenNoItems>(render_dropdown)
462 .add_basic_renderer::<settings::TextRenderingMode>(render_dropdown)
463 .add_basic_renderer::<settings::FontFamilyName>(render_font_picker)
464 .add_basic_renderer::<settings::BaseKeymapContent>(render_dropdown)
465 .add_basic_renderer::<settings::MultiCursorModifier>(render_dropdown)
466 .add_basic_renderer::<settings::HideMouseMode>(render_dropdown)
467 .add_basic_renderer::<settings::CurrentLineHighlight>(render_dropdown)
468 .add_basic_renderer::<settings::ShowWhitespaceSetting>(render_dropdown)
469 .add_basic_renderer::<settings::SoftWrap>(render_dropdown)
470 .add_basic_renderer::<settings::AutoIndentMode>(render_dropdown)
471 .add_basic_renderer::<settings::ScrollBeyondLastLine>(render_dropdown)
472 .add_basic_renderer::<settings::SnippetSortOrder>(render_dropdown)
473 .add_basic_renderer::<settings::ClosePosition>(render_dropdown)
474 .add_basic_renderer::<settings::DockSide>(render_dropdown)
475 .add_basic_renderer::<settings::TerminalDockPosition>(render_dropdown)
476 .add_basic_renderer::<settings::DockPosition>(render_dropdown)
477 .add_basic_renderer::<settings::GitGutterSetting>(render_dropdown)
478 .add_basic_renderer::<settings::GitHunkStyleSetting>(render_dropdown)
479 .add_basic_renderer::<settings::GitPathStyle>(render_dropdown)
480 .add_basic_renderer::<settings::DiagnosticSeverityContent>(render_dropdown)
481 .add_basic_renderer::<settings::SeedQuerySetting>(render_dropdown)
482 .add_basic_renderer::<settings::DoubleClickInMultibuffer>(render_dropdown)
483 .add_basic_renderer::<settings::GoToDefinitionFallback>(render_dropdown)
484 .add_basic_renderer::<settings::ActivateOnClose>(render_dropdown)
485 .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
486 .add_basic_renderer::<settings::ShowCloseButton>(render_dropdown)
487 .add_basic_renderer::<settings::ProjectPanelEntrySpacing>(render_dropdown)
488 .add_basic_renderer::<settings::ProjectPanelSortMode>(render_dropdown)
489 .add_basic_renderer::<settings::RewrapBehavior>(render_dropdown)
490 .add_basic_renderer::<settings::FormatOnSave>(render_dropdown)
491 .add_basic_renderer::<settings::IndentGuideColoring>(render_dropdown)
492 .add_basic_renderer::<settings::IndentGuideBackgroundColoring>(render_dropdown)
493 .add_basic_renderer::<settings::FileFinderWidthContent>(render_dropdown)
494 .add_basic_renderer::<settings::ShowDiagnostics>(render_dropdown)
495 .add_basic_renderer::<settings::WordsCompletionMode>(render_dropdown)
496 .add_basic_renderer::<settings::LspInsertMode>(render_dropdown)
497 .add_basic_renderer::<settings::CompletionDetailAlignment>(render_dropdown)
498 .add_basic_renderer::<settings::DiffViewStyle>(render_dropdown)
499 .add_basic_renderer::<settings::AlternateScroll>(render_dropdown)
500 .add_basic_renderer::<settings::TerminalBlink>(render_dropdown)
501 .add_basic_renderer::<settings::CursorShapeContent>(render_dropdown)
502 .add_basic_renderer::<settings::EditPredictionPromptFormat>(render_dropdown)
503 .add_basic_renderer::<f32>(render_number_field)
504 .add_basic_renderer::<u32>(render_number_field)
505 .add_basic_renderer::<u64>(render_number_field)
506 .add_basic_renderer::<usize>(render_number_field)
507 .add_basic_renderer::<NonZero<usize>>(render_number_field)
508 .add_basic_renderer::<NonZeroU32>(render_number_field)
509 .add_basic_renderer::<settings::CodeFade>(render_number_field)
510 .add_basic_renderer::<settings::DelayMs>(render_number_field)
511 .add_basic_renderer::<settings::FontWeightContent>(render_number_field)
512 .add_basic_renderer::<settings::CenteredPaddingSettings>(render_number_field)
513 .add_basic_renderer::<settings::InactiveOpacity>(render_number_field)
514 .add_basic_renderer::<settings::MinimumContrast>(render_number_field)
515 .add_basic_renderer::<settings::ShowScrollbar>(render_dropdown)
516 .add_basic_renderer::<settings::ScrollbarDiagnostics>(render_dropdown)
517 .add_basic_renderer::<settings::ShowMinimap>(render_dropdown)
518 .add_basic_renderer::<settings::DisplayIn>(render_dropdown)
519 .add_basic_renderer::<settings::MinimapThumb>(render_dropdown)
520 .add_basic_renderer::<settings::MinimapThumbBorder>(render_dropdown)
521 .add_basic_renderer::<settings::ModeContent>(render_dropdown)
522 .add_basic_renderer::<settings::UseSystemClipboard>(render_dropdown)
523 .add_basic_renderer::<settings::VimInsertModeCursorShape>(render_dropdown)
524 .add_basic_renderer::<settings::SteppingGranularity>(render_dropdown)
525 .add_basic_renderer::<settings::NotifyWhenAgentWaiting>(render_dropdown)
526 .add_basic_renderer::<settings::NewThreadLocation>(render_dropdown)
527 .add_basic_renderer::<settings::ImageFileSizeUnit>(render_dropdown)
528 .add_basic_renderer::<settings::StatusStyle>(render_dropdown)
529 .add_basic_renderer::<settings::EncodingDisplayOptions>(render_dropdown)
530 .add_basic_renderer::<settings::PaneSplitDirectionHorizontal>(render_dropdown)
531 .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
532 .add_basic_renderer::<settings::PaneSplitDirectionVertical>(render_dropdown)
533 .add_basic_renderer::<settings::DocumentColorsRenderMode>(render_dropdown)
534 .add_basic_renderer::<settings::ThemeSelectionDiscriminants>(render_dropdown)
535 .add_basic_renderer::<settings::ThemeAppearanceMode>(render_dropdown)
536 .add_basic_renderer::<settings::ThemeName>(render_theme_picker)
537 .add_basic_renderer::<settings::IconThemeSelectionDiscriminants>(render_dropdown)
538 .add_basic_renderer::<settings::IconThemeName>(render_icon_theme_picker)
539 .add_basic_renderer::<settings::BufferLineHeightDiscriminants>(render_dropdown)
540 .add_basic_renderer::<settings::AutosaveSettingDiscriminants>(render_dropdown)
541 .add_basic_renderer::<settings::WorkingDirectoryDiscriminants>(render_dropdown)
542 .add_basic_renderer::<settings::IncludeIgnoredContent>(render_dropdown)
543 .add_basic_renderer::<settings::ShowIndentGuides>(render_dropdown)
544 .add_basic_renderer::<settings::ShellDiscriminants>(render_dropdown)
545 .add_basic_renderer::<settings::EditPredictionsMode>(render_dropdown)
546 .add_basic_renderer::<settings::RelativeLineNumbers>(render_dropdown)
547 .add_basic_renderer::<settings::WindowDecorations>(render_dropdown)
548 .add_basic_renderer::<settings::WindowButtonLayoutContentDiscriminants>(render_dropdown)
549 .add_basic_renderer::<settings::FontSize>(render_editable_number_field)
550 .add_basic_renderer::<settings::OllamaModelName>(render_ollama_model_picker)
551 .add_basic_renderer::<settings::SemanticTokens>(render_dropdown)
552 .add_basic_renderer::<settings::DocumentFoldingRanges>(render_dropdown)
553 .add_basic_renderer::<settings::DocumentSymbols>(render_dropdown)
554 .add_basic_renderer::<settings::AudioInputDeviceName>(render_input_audio_device_dropdown)
555 .add_basic_renderer::<settings::AudioOutputDeviceName>(render_output_audio_device_dropdown)
556 // please semicolon stay on next line
557 ;
558}
559
560pub fn open_settings_editor(
561 path: Option<&str>,
562 target_worktree_id: Option<WorktreeId>,
563 workspace_handle: Option<WindowHandle<MultiWorkspace>>,
564 cx: &mut App,
565) {
566 telemetry::event!("Settings Viewed");
567
568 /// Assumes a settings GUI window is already open
569 fn open_path(
570 path: &str,
571 settings_window: &mut SettingsWindow,
572 window: &mut Window,
573 cx: &mut Context<SettingsWindow>,
574 ) {
575 if path.starts_with("languages.$(language)") {
576 log::error!("language-specific settings links are not currently supported");
577 return;
578 }
579
580 let query = format!("#{path}");
581 let indices = settings_window.filter_by_json_path(&query);
582
583 settings_window.opening_link = true;
584 settings_window.search_bar.update(cx, |editor, cx| {
585 editor.set_text(query, window, cx);
586 });
587 settings_window.apply_match_indices(indices.iter().copied());
588
589 if indices.len() == 1
590 && let Some(search_index) = settings_window.search_index.as_ref()
591 {
592 let SearchKeyLUTEntry {
593 page_index,
594 item_index,
595 header_index,
596 ..
597 } = search_index.key_lut[indices[0]];
598 let page = &settings_window.pages[page_index];
599 let item = &page.items[item_index];
600
601 if settings_window.filter_table[page_index][item_index]
602 && let SettingsPageItem::SubPageLink(link) = item
603 && let SettingsPageItem::SectionHeader(header) = page.items[header_index]
604 {
605 settings_window.push_sub_page(link.clone(), SharedString::from(header), window, cx);
606 }
607 }
608
609 cx.notify();
610 }
611
612 let existing_window = cx
613 .windows()
614 .into_iter()
615 .find_map(|window| window.downcast::<SettingsWindow>());
616
617 if let Some(existing_window) = existing_window {
618 existing_window
619 .update(cx, |settings_window, window, cx| {
620 settings_window.original_window = workspace_handle;
621
622 window.activate_window();
623 if let Some(path) = path {
624 open_path(path, settings_window, window, cx);
625 } else if let Some(target_id) = target_worktree_id
626 && let Some(file_index) = settings_window
627 .files
628 .iter()
629 .position(|(file, _)| file.worktree_id() == Some(target_id))
630 {
631 settings_window.change_file(file_index, window, cx);
632 cx.notify();
633 }
634 })
635 .ok();
636 return;
637 }
638
639 // We have to defer this to get the workspace off the stack.
640 let path = path.map(ToOwned::to_owned);
641 cx.defer(move |cx| {
642 let current_rem_size: f32 = theme::ThemeSettings::get_global(cx).ui_font_size(cx).into();
643
644 let default_bounds = DEFAULT_ADDITIONAL_WINDOW_SIZE;
645 let default_rem_size = 16.0;
646 let scale_factor = current_rem_size / default_rem_size;
647 let scaled_bounds: gpui::Size<Pixels> = default_bounds.map(|axis| axis * scale_factor);
648
649 let app_id = ReleaseChannel::global(cx).app_id();
650 let window_decorations = match std::env::var("ZED_WINDOW_DECORATIONS") {
651 Ok(val) if val == "server" => gpui::WindowDecorations::Server,
652 Ok(val) if val == "client" => gpui::WindowDecorations::Client,
653 _ => gpui::WindowDecorations::Client,
654 };
655
656 cx.open_window(
657 WindowOptions {
658 titlebar: Some(TitlebarOptions {
659 title: Some("Zed — Settings".into()),
660 appears_transparent: true,
661 traffic_light_position: Some(point(px(12.0), px(12.0))),
662 }),
663 focus: true,
664 show: true,
665 is_movable: true,
666 kind: gpui::WindowKind::Normal,
667 window_background: cx.theme().window_background_appearance(),
668 app_id: Some(app_id.to_owned()),
669 window_decorations: Some(window_decorations),
670 window_min_size: Some(gpui::Size {
671 // Don't make the settings window thinner than this,
672 // otherwise, it gets unusable. Users with smaller res monitors
673 // can customize the height, but not the width.
674 width: px(900.0),
675 height: px(240.0),
676 }),
677 window_bounds: Some(WindowBounds::centered(scaled_bounds, cx)),
678 ..Default::default()
679 },
680 |window, cx| {
681 let settings_window =
682 cx.new(|cx| SettingsWindow::new(workspace_handle, window, cx));
683 settings_window.update(cx, |settings_window, cx| {
684 if let Some(path) = path {
685 open_path(&path, settings_window, window, cx);
686 } else if let Some(target_id) = target_worktree_id
687 && let Some(file_index) = settings_window
688 .files
689 .iter()
690 .position(|(file, _)| file.worktree_id() == Some(target_id))
691 {
692 settings_window.change_file(file_index, window, cx);
693 }
694 });
695
696 settings_window
697 },
698 )
699 .log_err();
700 });
701}
702
703/// The current sub page path that is selected.
704/// If this is empty the selected page is rendered,
705/// otherwise the last sub page gets rendered.
706///
707/// Global so that `pick` and `write` callbacks can access it
708/// and use it to dynamically render sub pages (e.g. for language settings)
709static ACTIVE_LANGUAGE: LazyLock<RwLock<Option<SharedString>>> =
710 LazyLock::new(|| RwLock::new(Option::None));
711
712fn active_language() -> Option<SharedString> {
713 ACTIVE_LANGUAGE
714 .read()
715 .ok()
716 .and_then(|language| language.clone())
717}
718
719fn active_language_mut() -> Option<std::sync::RwLockWriteGuard<'static, Option<SharedString>>> {
720 ACTIVE_LANGUAGE.write().ok()
721}
722
723pub struct SettingsWindow {
724 title_bar: Option<Entity<PlatformTitleBar>>,
725 original_window: Option<WindowHandle<MultiWorkspace>>,
726 files: Vec<(SettingsUiFile, FocusHandle)>,
727 worktree_root_dirs: HashMap<WorktreeId, String>,
728 current_file: SettingsUiFile,
729 pages: Vec<SettingsPage>,
730 sub_page_stack: Vec<SubPage>,
731 opening_link: bool,
732 search_bar: Entity<Editor>,
733 search_task: Option<Task<()>>,
734 /// Cached settings file buffers to avoid repeated disk I/O on each settings change
735 project_setting_file_buffers: HashMap<ProjectPath, Entity<Buffer>>,
736 /// Index into navbar_entries
737 navbar_entry: usize,
738 navbar_entries: Vec<NavBarEntry>,
739 navbar_scroll_handle: UniformListScrollHandle,
740 /// [page_index][page_item_index] will be false
741 /// when the item is filtered out either by searches
742 /// or by the current file
743 navbar_focus_subscriptions: Vec<gpui::Subscription>,
744 filter_table: Vec<Vec<bool>>,
745 has_query: bool,
746 content_handles: Vec<Vec<Entity<NonFocusableHandle>>>,
747 focus_handle: FocusHandle,
748 navbar_focus_handle: Entity<NonFocusableHandle>,
749 content_focus_handle: Entity<NonFocusableHandle>,
750 files_focus_handle: FocusHandle,
751 search_index: Option<Arc<SearchIndex>>,
752 list_state: ListState,
753 shown_errors: HashSet<String>,
754 pub(crate) regex_validation_error: Option<String>,
755}
756
757struct SearchDocument {
758 id: usize,
759 words: Vec<String>,
760}
761
762struct SearchIndex {
763 documents: Vec<SearchDocument>,
764 fuzzy_match_candidates: Vec<StringMatchCandidate>,
765 key_lut: Vec<SearchKeyLUTEntry>,
766}
767
768struct SearchKeyLUTEntry {
769 page_index: usize,
770 header_index: usize,
771 item_index: usize,
772 json_path: Option<&'static str>,
773}
774
775struct SubPage {
776 link: SubPageLink,
777 section_header: SharedString,
778 scroll_handle: ScrollHandle,
779}
780
781impl SubPage {
782 fn new(link: SubPageLink, section_header: SharedString) -> Self {
783 if link.r#type == SubPageType::Language
784 && let Some(mut active_language_global) = active_language_mut()
785 {
786 active_language_global.replace(link.title.clone());
787 }
788
789 SubPage {
790 link,
791 section_header,
792 scroll_handle: ScrollHandle::new(),
793 }
794 }
795}
796
797impl Drop for SubPage {
798 fn drop(&mut self) {
799 if self.link.r#type == SubPageType::Language
800 && let Some(mut active_language_global) = active_language_mut()
801 && active_language_global
802 .as_ref()
803 .is_some_and(|language_name| language_name == &self.link.title)
804 {
805 active_language_global.take();
806 }
807 }
808}
809
810#[derive(Debug)]
811struct NavBarEntry {
812 title: &'static str,
813 is_root: bool,
814 expanded: bool,
815 page_index: usize,
816 item_index: Option<usize>,
817 focus_handle: FocusHandle,
818}
819
820struct SettingsPage {
821 title: &'static str,
822 items: Box<[SettingsPageItem]>,
823}
824
825#[derive(PartialEq)]
826enum SettingsPageItem {
827 SectionHeader(&'static str),
828 SettingItem(SettingItem),
829 SubPageLink(SubPageLink),
830 DynamicItem(DynamicItem),
831 ActionLink(ActionLink),
832}
833
834impl std::fmt::Debug for SettingsPageItem {
835 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
836 match self {
837 SettingsPageItem::SectionHeader(header) => write!(f, "SectionHeader({})", header),
838 SettingsPageItem::SettingItem(setting_item) => {
839 write!(f, "SettingItem({})", setting_item.title)
840 }
841 SettingsPageItem::SubPageLink(sub_page_link) => {
842 write!(f, "SubPageLink({})", sub_page_link.title)
843 }
844 SettingsPageItem::DynamicItem(dynamic_item) => {
845 write!(f, "DynamicItem({})", dynamic_item.discriminant.title)
846 }
847 SettingsPageItem::ActionLink(action_link) => {
848 write!(f, "ActionLink({})", action_link.title)
849 }
850 }
851 }
852}
853
854impl SettingsPageItem {
855 fn header_text(&self) -> Option<&'static str> {
856 match self {
857 SettingsPageItem::SectionHeader(header) => Some(header),
858 _ => None,
859 }
860 }
861
862 fn render(
863 &self,
864 settings_window: &SettingsWindow,
865 item_index: usize,
866 bottom_border: bool,
867 extra_bottom_padding: bool,
868 window: &mut Window,
869 cx: &mut Context<SettingsWindow>,
870 ) -> AnyElement {
871 let file = settings_window.current_file.clone();
872
873 let apply_padding = |element: Stateful<Div>| -> Stateful<Div> {
874 let element = element.pt_4();
875 if extra_bottom_padding {
876 element.pb_10()
877 } else {
878 element.pb_4()
879 }
880 };
881
882 let mut render_setting_item_inner =
883 |setting_item: &SettingItem,
884 padding: bool,
885 sub_field: bool,
886 cx: &mut Context<SettingsWindow>| {
887 let renderer = cx.default_global::<SettingFieldRenderer>().clone();
888 let (_, found) = setting_item.field.file_set_in(file.clone(), cx);
889
890 let renderers = renderer.renderers.borrow();
891
892 let field_renderer =
893 renderers.get(&AnySettingField::type_id(setting_item.field.as_ref()));
894 let field_renderer_or_warning =
895 field_renderer.ok_or("NO RENDERER").and_then(|renderer| {
896 if cfg!(debug_assertions) && !found {
897 Err("NO DEFAULT")
898 } else {
899 Ok(renderer)
900 }
901 });
902
903 let field = match field_renderer_or_warning {
904 Ok(field_renderer) => window.with_id(item_index, |window| {
905 field_renderer(
906 settings_window,
907 setting_item,
908 file.clone(),
909 setting_item.metadata.as_deref(),
910 sub_field,
911 window,
912 cx,
913 )
914 }),
915 Err(warning) => render_settings_item(
916 settings_window,
917 setting_item,
918 file.clone(),
919 Button::new("error-warning", warning)
920 .style(ButtonStyle::Outlined)
921 .size(ButtonSize::Medium)
922 .start_icon(Icon::new(IconName::Debug).color(Color::Error))
923 .tab_index(0_isize)
924 .tooltip(Tooltip::text(setting_item.field.type_name()))
925 .into_any_element(),
926 sub_field,
927 cx,
928 ),
929 };
930
931 let field = if padding {
932 field.map(apply_padding)
933 } else {
934 field
935 };
936
937 (field, field_renderer_or_warning.is_ok())
938 };
939
940 match self {
941 SettingsPageItem::SectionHeader(header) => {
942 SettingsSectionHeader::new(SharedString::new_static(header)).into_any_element()
943 }
944 SettingsPageItem::SettingItem(setting_item) => {
945 let (field_with_padding, _) =
946 render_setting_item_inner(setting_item, true, false, cx);
947
948 v_flex()
949 .group("setting-item")
950 .px_8()
951 .child(field_with_padding)
952 .when(bottom_border, |this| this.child(Divider::horizontal()))
953 .into_any_element()
954 }
955 SettingsPageItem::SubPageLink(sub_page_link) => v_flex()
956 .group("setting-item")
957 .px_8()
958 .child(
959 h_flex()
960 .id(sub_page_link.title.clone())
961 .w_full()
962 .min_w_0()
963 .justify_between()
964 .map(apply_padding)
965 .child(
966 v_flex()
967 .relative()
968 .w_full()
969 .max_w_1_2()
970 .child(Label::new(sub_page_link.title.clone()))
971 .when_some(
972 sub_page_link.description.as_ref(),
973 |this, description| {
974 this.child(
975 Label::new(description.clone())
976 .size(LabelSize::Small)
977 .color(Color::Muted),
978 )
979 },
980 ),
981 )
982 .child(
983 Button::new(
984 ("sub-page".into(), sub_page_link.title.clone()),
985 "Configure",
986 )
987 .tab_index(0_isize)
988 .end_icon(
989 Icon::new(IconName::ChevronRight)
990 .size(IconSize::Small)
991 .color(Color::Muted),
992 )
993 .style(ButtonStyle::OutlinedGhost)
994 .size(ButtonSize::Medium)
995 .on_click({
996 let sub_page_link = sub_page_link.clone();
997 cx.listener(move |this, _, window, cx| {
998 let header_text = this
999 .sub_page_stack
1000 .last()
1001 .map(|sub_page| sub_page.link.title.clone())
1002 .or_else(|| {
1003 this.current_page()
1004 .items
1005 .iter()
1006 .take(item_index)
1007 .rev()
1008 .find_map(|item| {
1009 item.header_text().map(SharedString::new_static)
1010 })
1011 });
1012
1013 let Some(header) = header_text else {
1014 unreachable!(
1015 "All items always have a section header above them"
1016 )
1017 };
1018
1019 this.push_sub_page(sub_page_link.clone(), header, window, cx)
1020 })
1021 }),
1022 )
1023 .child(render_settings_item_link(
1024 sub_page_link.title.clone(),
1025 sub_page_link.json_path,
1026 false,
1027 cx,
1028 )),
1029 )
1030 .when(bottom_border, |this| this.child(Divider::horizontal()))
1031 .into_any_element(),
1032 SettingsPageItem::DynamicItem(DynamicItem {
1033 discriminant: discriminant_setting_item,
1034 pick_discriminant,
1035 fields,
1036 }) => {
1037 let file = file.to_settings();
1038 let discriminant = SettingsStore::global(cx)
1039 .get_value_from_file(file, *pick_discriminant)
1040 .1;
1041
1042 let (discriminant_element, rendered_ok) =
1043 render_setting_item_inner(discriminant_setting_item, true, false, cx);
1044
1045 let has_sub_fields =
1046 rendered_ok && discriminant.is_some_and(|d| !fields[d].is_empty());
1047
1048 let mut content = v_flex()
1049 .id("dynamic-item")
1050 .child(
1051 div()
1052 .group("setting-item")
1053 .px_8()
1054 .child(discriminant_element.when(has_sub_fields, |this| this.pb_4())),
1055 )
1056 .when(!has_sub_fields && bottom_border, |this| {
1057 this.child(h_flex().px_8().child(Divider::horizontal()))
1058 });
1059
1060 if rendered_ok {
1061 let discriminant =
1062 discriminant.expect("This should be Some if rendered_ok is true");
1063 let sub_fields = &fields[discriminant];
1064 let sub_field_count = sub_fields.len();
1065
1066 for (index, field) in sub_fields.iter().enumerate() {
1067 let is_last_sub_field = index == sub_field_count - 1;
1068 let (raw_field, _) = render_setting_item_inner(field, false, true, cx);
1069
1070 content = content.child(
1071 raw_field
1072 .group("setting-sub-item")
1073 .mx_8()
1074 .p_4()
1075 .border_t_1()
1076 .when(is_last_sub_field, |this| this.border_b_1())
1077 .when(is_last_sub_field && extra_bottom_padding, |this| {
1078 this.mb_8()
1079 })
1080 .border_dashed()
1081 .border_color(cx.theme().colors().border_variant)
1082 .bg(cx.theme().colors().element_background.opacity(0.2)),
1083 );
1084 }
1085 }
1086
1087 return content.into_any_element();
1088 }
1089 SettingsPageItem::ActionLink(action_link) => v_flex()
1090 .group("setting-item")
1091 .px_8()
1092 .child(
1093 h_flex()
1094 .id(action_link.title.clone())
1095 .w_full()
1096 .min_w_0()
1097 .justify_between()
1098 .map(apply_padding)
1099 .child(
1100 v_flex()
1101 .relative()
1102 .w_full()
1103 .max_w_1_2()
1104 .child(Label::new(action_link.title.clone()))
1105 .when_some(
1106 action_link.description.as_ref(),
1107 |this, description| {
1108 this.child(
1109 Label::new(description.clone())
1110 .size(LabelSize::Small)
1111 .color(Color::Muted),
1112 )
1113 },
1114 ),
1115 )
1116 .child(
1117 Button::new(
1118 ("action-link".into(), action_link.title.clone()),
1119 action_link.button_text.clone(),
1120 )
1121 .tab_index(0_isize)
1122 .end_icon(
1123 Icon::new(IconName::ArrowUpRight)
1124 .size(IconSize::Small)
1125 .color(Color::Muted),
1126 )
1127 .style(ButtonStyle::OutlinedGhost)
1128 .size(ButtonSize::Medium)
1129 .on_click({
1130 let on_click = action_link.on_click.clone();
1131 cx.listener(move |this, _, window, cx| {
1132 on_click(this, window, cx);
1133 })
1134 }),
1135 ),
1136 )
1137 .when(bottom_border, |this| this.child(Divider::horizontal()))
1138 .into_any_element(),
1139 }
1140 }
1141}
1142
1143fn render_settings_item(
1144 settings_window: &SettingsWindow,
1145 setting_item: &SettingItem,
1146 file: SettingsUiFile,
1147 control: AnyElement,
1148 sub_field: bool,
1149 cx: &mut Context<'_, SettingsWindow>,
1150) -> Stateful<Div> {
1151 let (found_in_file, _) = setting_item.field.file_set_in(file.clone(), cx);
1152 let file_set_in = SettingsUiFile::from_settings(found_in_file.clone());
1153
1154 h_flex()
1155 .id(setting_item.title)
1156 .min_w_0()
1157 .justify_between()
1158 .child(
1159 v_flex()
1160 .relative()
1161 .w_full()
1162 .max_w_2_3()
1163 .min_w_0()
1164 .child(
1165 h_flex()
1166 .w_full()
1167 .gap_1()
1168 .child(Label::new(SharedString::new_static(setting_item.title)))
1169 .when_some(
1170 if sub_field {
1171 None
1172 } else {
1173 setting_item
1174 .field
1175 .reset_to_default_fn(&file, &found_in_file, cx)
1176 },
1177 |this, reset_to_default| {
1178 this.child(
1179 IconButton::new("reset-to-default-btn", IconName::Undo)
1180 .icon_color(Color::Muted)
1181 .icon_size(IconSize::Small)
1182 .tooltip(Tooltip::text("Reset to Default"))
1183 .on_click({
1184 move |_, window, cx| {
1185 reset_to_default(window, cx);
1186 }
1187 }),
1188 )
1189 },
1190 )
1191 .when_some(
1192 file_set_in.filter(|file_set_in| file_set_in != &file),
1193 |this, file_set_in| {
1194 this.child(
1195 Label::new(format!(
1196 "— Modified in {}",
1197 settings_window
1198 .display_name(&file_set_in)
1199 .expect("File name should exist")
1200 ))
1201 .color(Color::Muted)
1202 .size(LabelSize::Small),
1203 )
1204 },
1205 ),
1206 )
1207 .child(
1208 Label::new(SharedString::new_static(setting_item.description))
1209 .size(LabelSize::Small)
1210 .color(Color::Muted),
1211 ),
1212 )
1213 .child(control)
1214 .when(settings_window.sub_page_stack.is_empty(), |this| {
1215 this.child(render_settings_item_link(
1216 setting_item.description,
1217 setting_item.field.json_path(),
1218 sub_field,
1219 cx,
1220 ))
1221 })
1222}
1223
1224fn render_settings_item_link(
1225 id: impl Into<ElementId>,
1226 json_path: Option<&'static str>,
1227 sub_field: bool,
1228 cx: &mut Context<'_, SettingsWindow>,
1229) -> impl IntoElement {
1230 let clipboard_has_link = cx
1231 .read_from_clipboard()
1232 .and_then(|entry| entry.text())
1233 .map_or(false, |maybe_url| {
1234 json_path.is_some() && maybe_url.strip_prefix("zed://settings/") == json_path
1235 });
1236
1237 let (link_icon, link_icon_color) = if clipboard_has_link {
1238 (IconName::Check, Color::Success)
1239 } else {
1240 (IconName::Link, Color::Muted)
1241 };
1242
1243 div()
1244 .absolute()
1245 .top(rems_from_px(18.))
1246 .map(|this| {
1247 if sub_field {
1248 this.visible_on_hover("setting-sub-item")
1249 .left(rems_from_px(-8.5))
1250 } else {
1251 this.visible_on_hover("setting-item")
1252 .left(rems_from_px(-22.))
1253 }
1254 })
1255 .child(
1256 IconButton::new((id.into(), "copy-link-btn"), link_icon)
1257 .icon_color(link_icon_color)
1258 .icon_size(IconSize::Small)
1259 .shape(IconButtonShape::Square)
1260 .tooltip(Tooltip::text("Copy Link"))
1261 .when_some(json_path, |this, path| {
1262 this.on_click(cx.listener(move |_, _, _, cx| {
1263 let link = format!("zed://settings/{}", path);
1264 cx.write_to_clipboard(ClipboardItem::new_string(link));
1265 cx.notify();
1266 }))
1267 }),
1268 )
1269}
1270
1271struct SettingItem {
1272 title: &'static str,
1273 description: &'static str,
1274 field: Box<dyn AnySettingField>,
1275 metadata: Option<Box<SettingsFieldMetadata>>,
1276 files: FileMask,
1277}
1278
1279struct DynamicItem {
1280 discriminant: SettingItem,
1281 pick_discriminant: fn(&SettingsContent) -> Option<usize>,
1282 fields: Vec<Vec<SettingItem>>,
1283}
1284
1285impl PartialEq for DynamicItem {
1286 fn eq(&self, other: &Self) -> bool {
1287 self.discriminant == other.discriminant && self.fields == other.fields
1288 }
1289}
1290
1291#[derive(PartialEq, Eq, Clone, Copy)]
1292struct FileMask(u8);
1293
1294impl std::fmt::Debug for FileMask {
1295 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1296 write!(f, "FileMask(")?;
1297 let mut items = vec![];
1298
1299 if self.contains(USER) {
1300 items.push("USER");
1301 }
1302 if self.contains(PROJECT) {
1303 items.push("LOCAL");
1304 }
1305 if self.contains(SERVER) {
1306 items.push("SERVER");
1307 }
1308
1309 write!(f, "{})", items.join(" | "))
1310 }
1311}
1312
1313const USER: FileMask = FileMask(1 << 0);
1314const PROJECT: FileMask = FileMask(1 << 2);
1315const SERVER: FileMask = FileMask(1 << 3);
1316
1317impl std::ops::BitAnd for FileMask {
1318 type Output = Self;
1319
1320 fn bitand(self, other: Self) -> Self {
1321 Self(self.0 & other.0)
1322 }
1323}
1324
1325impl std::ops::BitOr for FileMask {
1326 type Output = Self;
1327
1328 fn bitor(self, other: Self) -> Self {
1329 Self(self.0 | other.0)
1330 }
1331}
1332
1333impl FileMask {
1334 fn contains(&self, other: FileMask) -> bool {
1335 self.0 & other.0 != 0
1336 }
1337}
1338
1339impl PartialEq for SettingItem {
1340 fn eq(&self, other: &Self) -> bool {
1341 self.title == other.title
1342 && self.description == other.description
1343 && (match (&self.metadata, &other.metadata) {
1344 (None, None) => true,
1345 (Some(m1), Some(m2)) => m1.placeholder == m2.placeholder,
1346 _ => false,
1347 })
1348 }
1349}
1350
1351#[derive(Clone, PartialEq, Default)]
1352enum SubPageType {
1353 Language,
1354 #[default]
1355 Other,
1356}
1357
1358#[derive(Clone)]
1359struct SubPageLink {
1360 title: SharedString,
1361 r#type: SubPageType,
1362 description: Option<SharedString>,
1363 /// See [`SettingField.json_path`]
1364 json_path: Option<&'static str>,
1365 /// Whether or not the settings in this sub page are configurable in settings.json
1366 /// Removes the "Edit in settings.json" button from the page.
1367 in_json: bool,
1368 files: FileMask,
1369 render:
1370 fn(&SettingsWindow, &ScrollHandle, &mut Window, &mut Context<SettingsWindow>) -> AnyElement,
1371}
1372
1373impl PartialEq for SubPageLink {
1374 fn eq(&self, other: &Self) -> bool {
1375 self.title == other.title
1376 }
1377}
1378
1379#[derive(Clone)]
1380struct ActionLink {
1381 title: SharedString,
1382 description: Option<SharedString>,
1383 button_text: SharedString,
1384 on_click: Arc<dyn Fn(&mut SettingsWindow, &mut Window, &mut App) + Send + Sync>,
1385 files: FileMask,
1386}
1387
1388impl PartialEq for ActionLink {
1389 fn eq(&self, other: &Self) -> bool {
1390 self.title == other.title
1391 }
1392}
1393
1394fn all_language_names(cx: &App) -> Vec<SharedString> {
1395 workspace::AppState::global(cx)
1396 .upgrade()
1397 .map_or(vec![], |state| {
1398 state
1399 .languages
1400 .language_names()
1401 .into_iter()
1402 .filter(|name| name.as_ref() != "Zed Keybind Context")
1403 .map(Into::into)
1404 .collect()
1405 })
1406}
1407
1408#[allow(unused)]
1409#[derive(Clone, PartialEq, Debug)]
1410enum SettingsUiFile {
1411 User, // Uses all settings.
1412 Project((WorktreeId, Arc<RelPath>)), // Has a special name, and special set of settings
1413 Server(&'static str), // Uses a special name, and the user settings
1414}
1415
1416impl SettingsUiFile {
1417 fn setting_type(&self) -> &'static str {
1418 match self {
1419 SettingsUiFile::User => "User",
1420 SettingsUiFile::Project(_) => "Project",
1421 SettingsUiFile::Server(_) => "Server",
1422 }
1423 }
1424
1425 fn is_server(&self) -> bool {
1426 matches!(self, SettingsUiFile::Server(_))
1427 }
1428
1429 fn worktree_id(&self) -> Option<WorktreeId> {
1430 match self {
1431 SettingsUiFile::User => None,
1432 SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
1433 SettingsUiFile::Server(_) => None,
1434 }
1435 }
1436
1437 fn from_settings(file: settings::SettingsFile) -> Option<Self> {
1438 Some(match file {
1439 settings::SettingsFile::User => SettingsUiFile::User,
1440 settings::SettingsFile::Project(location) => SettingsUiFile::Project(location),
1441 settings::SettingsFile::Server => SettingsUiFile::Server("todo: server name"),
1442 settings::SettingsFile::Default => return None,
1443 settings::SettingsFile::Global => return None,
1444 })
1445 }
1446
1447 fn to_settings(&self) -> settings::SettingsFile {
1448 match self {
1449 SettingsUiFile::User => settings::SettingsFile::User,
1450 SettingsUiFile::Project(location) => settings::SettingsFile::Project(location.clone()),
1451 SettingsUiFile::Server(_) => settings::SettingsFile::Server,
1452 }
1453 }
1454
1455 fn mask(&self) -> FileMask {
1456 match self {
1457 SettingsUiFile::User => USER,
1458 SettingsUiFile::Project(_) => PROJECT,
1459 SettingsUiFile::Server(_) => SERVER,
1460 }
1461 }
1462}
1463
1464impl SettingsWindow {
1465 fn new(
1466 original_window: Option<WindowHandle<MultiWorkspace>>,
1467 window: &mut Window,
1468 cx: &mut Context<Self>,
1469 ) -> Self {
1470 let font_family_cache = theme::FontFamilyCache::global(cx);
1471
1472 cx.spawn(async move |this, cx| {
1473 font_family_cache.prefetch(cx).await;
1474 this.update(cx, |_, cx| {
1475 cx.notify();
1476 })
1477 })
1478 .detach();
1479
1480 let current_file = SettingsUiFile::User;
1481 let search_bar = cx.new(|cx| {
1482 let mut editor = Editor::single_line(window, cx);
1483 editor.set_placeholder_text("Search settings…", window, cx);
1484 editor
1485 });
1486 cx.subscribe(&search_bar, |this, _, event: &EditorEvent, cx| {
1487 let EditorEvent::Edited { transaction_id: _ } = event else {
1488 return;
1489 };
1490
1491 if this.opening_link {
1492 this.opening_link = false;
1493 return;
1494 }
1495 this.update_matches(cx);
1496 })
1497 .detach();
1498
1499 let mut ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
1500 cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
1501 this.fetch_files(window, cx);
1502
1503 // Whenever settings are changed, it's possible that the changed
1504 // settings affects the rendering of the `SettingsWindow`, like is
1505 // the case with `ui_font_size`. When that happens, we need to
1506 // instruct the `ListState` to re-measure the list items, as the
1507 // list item heights may have changed depending on the new font
1508 // size.
1509 let new_ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
1510 if new_ui_font_size != ui_font_size {
1511 this.list_state.remeasure();
1512 ui_font_size = new_ui_font_size;
1513 }
1514
1515 cx.notify();
1516 })
1517 .detach();
1518
1519 cx.on_window_closed(|cx, _window_id| {
1520 if let Some(existing_window) = cx
1521 .windows()
1522 .into_iter()
1523 .find_map(|window| window.downcast::<SettingsWindow>())
1524 && cx.windows().len() == 1
1525 {
1526 cx.update_window(*existing_window, |_, window, _| {
1527 window.remove_window();
1528 })
1529 .ok();
1530
1531 telemetry::event!("Settings Closed")
1532 }
1533 })
1534 .detach();
1535
1536 if let Some(app_state) = AppState::global(cx).upgrade() {
1537 let workspaces: Vec<Entity<Workspace>> = app_state
1538 .workspace_store
1539 .read(cx)
1540 .workspaces()
1541 .filter_map(|weak| weak.upgrade())
1542 .collect();
1543
1544 for workspace in workspaces {
1545 let project = workspace.read(cx).project().clone();
1546 cx.observe_release_in(&project, window, |this, _, window, cx| {
1547 this.fetch_files(window, cx)
1548 })
1549 .detach();
1550 cx.subscribe_in(&project, window, Self::handle_project_event)
1551 .detach();
1552 cx.observe_release_in(&workspace, window, |this, _, window, cx| {
1553 this.fetch_files(window, cx)
1554 })
1555 .detach();
1556 }
1557 } else {
1558 log::error!("App state doesn't exist when creating a new settings window");
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 Some(app_state) = workspace::AppState::global(cx).upgrade() else {
3364 return;
3365 };
3366
3367 let Some((workspace_window, worktree, corresponding_workspace)) = app_state
3368 .workspace_store
3369 .read(cx)
3370 .workspaces_with_windows()
3371 .filter_map(|(window_handle, weak)| {
3372 let workspace = weak.upgrade()?;
3373 let window = window_handle.downcast::<MultiWorkspace>()?;
3374 Some((window, workspace))
3375 })
3376 .find_map(|(window, workspace): (_, Entity<Workspace>)| {
3377 workspace
3378 .read(cx)
3379 .project()
3380 .read(cx)
3381 .worktree_for_id(*worktree_id, cx)
3382 .map(|worktree| (window, worktree, workspace))
3383 })
3384 else {
3385 log::error!(
3386 "No corresponding workspace contains worktree id: {}",
3387 worktree_id
3388 );
3389
3390 return;
3391 };
3392
3393 let create_task = if worktree.read(cx).entry_for_path(&settings_path).is_some() {
3394 None
3395 } else {
3396 Some(worktree.update(cx, |tree, cx| {
3397 tree.create_entry(
3398 settings_path.clone(),
3399 false,
3400 Some(initial_project_settings_content().as_bytes().to_vec()),
3401 cx,
3402 )
3403 }))
3404 };
3405
3406 let worktree_id = *worktree_id;
3407
3408 // TODO: move zed::open_local_file() APIs to this crate, and
3409 // re-implement the "initial_contents" behavior
3410 let workspace_weak = corresponding_workspace.downgrade();
3411 workspace_window
3412 .update(cx, |_, window, cx| {
3413 cx.spawn_in(window, async move |_, cx| {
3414 if let Some(create_task) = create_task {
3415 create_task.await.ok()?;
3416 };
3417
3418 workspace_weak
3419 .update_in(cx, |workspace, window, cx| {
3420 workspace.open_path(
3421 (worktree_id, settings_path.clone()),
3422 None,
3423 true,
3424 window,
3425 cx,
3426 )
3427 })
3428 .ok()?
3429 .await
3430 .log_err()?;
3431
3432 workspace_weak
3433 .update_in(cx, |_, window, cx| {
3434 window.activate_window();
3435 cx.notify();
3436 })
3437 .ok();
3438
3439 Some(())
3440 })
3441 .detach();
3442 })
3443 .ok();
3444
3445 window.remove_window();
3446 }
3447 SettingsUiFile::Server(_) => {
3448 // Server files are not editable
3449 return;
3450 }
3451 };
3452 }
3453
3454 fn current_page_index(&self) -> usize {
3455 if self.navbar_entries.is_empty() {
3456 return 0;
3457 }
3458
3459 self.navbar_entries[self.navbar_entry].page_index
3460 }
3461
3462 fn current_page(&self) -> &SettingsPage {
3463 &self.pages[self.current_page_index()]
3464 }
3465
3466 fn is_navbar_entry_selected(&self, ix: usize) -> bool {
3467 ix == self.navbar_entry
3468 }
3469
3470 fn push_sub_page(
3471 &mut self,
3472 sub_page_link: SubPageLink,
3473 section_header: SharedString,
3474 window: &mut Window,
3475 cx: &mut Context<SettingsWindow>,
3476 ) {
3477 self.sub_page_stack
3478 .push(SubPage::new(sub_page_link, section_header));
3479 self.content_focus_handle.focus_handle(cx).focus(window, cx);
3480 cx.notify();
3481 }
3482
3483 /// Push a dynamically-created sub-page with a custom render function.
3484 /// This is useful for nested sub-pages that aren't defined in the main pages list.
3485 pub fn push_dynamic_sub_page(
3486 &mut self,
3487 title: impl Into<SharedString>,
3488 section_header: impl Into<SharedString>,
3489 json_path: Option<&'static str>,
3490 render: fn(
3491 &SettingsWindow,
3492 &ScrollHandle,
3493 &mut Window,
3494 &mut Context<SettingsWindow>,
3495 ) -> AnyElement,
3496 window: &mut Window,
3497 cx: &mut Context<SettingsWindow>,
3498 ) {
3499 self.regex_validation_error = None;
3500 let sub_page_link = SubPageLink {
3501 title: title.into(),
3502 r#type: SubPageType::default(),
3503 description: None,
3504 json_path,
3505 in_json: true,
3506 files: USER,
3507 render,
3508 };
3509 self.push_sub_page(sub_page_link, section_header.into(), window, cx);
3510 }
3511
3512 /// Navigate to a sub-page by its json_path.
3513 /// Returns true if the sub-page was found and pushed, false otherwise.
3514 pub fn navigate_to_sub_page(
3515 &mut self,
3516 json_path: &str,
3517 window: &mut Window,
3518 cx: &mut Context<SettingsWindow>,
3519 ) -> bool {
3520 for page in &self.pages {
3521 for (item_index, item) in page.items.iter().enumerate() {
3522 if let SettingsPageItem::SubPageLink(sub_page_link) = item {
3523 if sub_page_link.json_path == Some(json_path) {
3524 let section_header = page
3525 .items
3526 .iter()
3527 .take(item_index)
3528 .rev()
3529 .find_map(|item| item.header_text().map(SharedString::new_static))
3530 .unwrap_or_else(|| "Settings".into());
3531
3532 self.push_sub_page(sub_page_link.clone(), section_header, window, cx);
3533 return true;
3534 }
3535 }
3536 }
3537 }
3538 false
3539 }
3540
3541 /// Navigate to a setting by its json_path.
3542 /// Clears the sub-page stack and scrolls to the setting item.
3543 /// Returns true if the setting was found, false otherwise.
3544 pub fn navigate_to_setting(
3545 &mut self,
3546 json_path: &str,
3547 window: &mut Window,
3548 cx: &mut Context<SettingsWindow>,
3549 ) -> bool {
3550 self.sub_page_stack.clear();
3551
3552 for (page_index, page) in self.pages.iter().enumerate() {
3553 for (item_index, item) in page.items.iter().enumerate() {
3554 let item_json_path = match item {
3555 SettingsPageItem::SettingItem(setting_item) => setting_item.field.json_path(),
3556 SettingsPageItem::DynamicItem(dynamic_item) => {
3557 dynamic_item.discriminant.field.json_path()
3558 }
3559 _ => None,
3560 };
3561 if item_json_path == Some(json_path) {
3562 if let Some(navbar_entry_index) = self
3563 .navbar_entries
3564 .iter()
3565 .position(|e| e.page_index == page_index && e.is_root)
3566 {
3567 self.open_and_scroll_to_navbar_entry(
3568 navbar_entry_index,
3569 None,
3570 false,
3571 window,
3572 cx,
3573 );
3574 self.scroll_to_content_item(item_index, window, cx);
3575 return true;
3576 }
3577 }
3578 }
3579 }
3580 false
3581 }
3582
3583 fn pop_sub_page(&mut self, window: &mut Window, cx: &mut Context<SettingsWindow>) {
3584 self.regex_validation_error = None;
3585 self.sub_page_stack.pop();
3586 self.content_focus_handle.focus_handle(cx).focus(window, cx);
3587 cx.notify();
3588 }
3589
3590 fn focus_file_at_index(&mut self, index: usize, window: &mut Window, cx: &mut App) {
3591 if let Some((_, handle)) = self.files.get(index) {
3592 handle.focus(window, cx);
3593 }
3594 }
3595
3596 fn focused_file_index(&self, window: &Window, cx: &Context<Self>) -> usize {
3597 if self.files_focus_handle.contains_focused(window, cx)
3598 && let Some(index) = self
3599 .files
3600 .iter()
3601 .position(|(_, handle)| handle.is_focused(window))
3602 {
3603 return index;
3604 }
3605 if let Some(current_file_index) = self
3606 .files
3607 .iter()
3608 .position(|(file, _)| file == &self.current_file)
3609 {
3610 return current_file_index;
3611 }
3612 0
3613 }
3614
3615 fn focus_handle_for_content_element(
3616 &self,
3617 actual_item_index: usize,
3618 cx: &Context<Self>,
3619 ) -> FocusHandle {
3620 let page_index = self.current_page_index();
3621 self.content_handles[page_index][actual_item_index].focus_handle(cx)
3622 }
3623
3624 fn focused_nav_entry(&self, window: &Window, cx: &App) -> Option<usize> {
3625 if !self
3626 .navbar_focus_handle
3627 .focus_handle(cx)
3628 .contains_focused(window, cx)
3629 {
3630 return None;
3631 }
3632 for (index, entry) in self.navbar_entries.iter().enumerate() {
3633 if entry.focus_handle.is_focused(window) {
3634 return Some(index);
3635 }
3636 }
3637 None
3638 }
3639
3640 fn root_entry_containing(&self, nav_entry_index: usize) -> usize {
3641 let mut index = Some(nav_entry_index);
3642 while let Some(prev_index) = index
3643 && !self.navbar_entries[prev_index].is_root
3644 {
3645 index = prev_index.checked_sub(1);
3646 }
3647 return index.expect("No root entry found");
3648 }
3649}
3650
3651impl Render for SettingsWindow {
3652 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3653 let ui_font = theme::setup_ui_font(window, cx);
3654
3655 client_side_decorations(
3656 v_flex()
3657 .text_color(cx.theme().colors().text)
3658 .size_full()
3659 .children(self.title_bar.clone())
3660 .child(
3661 div()
3662 .id("settings-window")
3663 .key_context("SettingsWindow")
3664 .track_focus(&self.focus_handle)
3665 .on_action(cx.listener(|this, _: &OpenCurrentFile, window, cx| {
3666 this.open_current_settings_file(window, cx);
3667 }))
3668 .on_action(|_: &Minimize, window, _cx| {
3669 window.minimize_window();
3670 })
3671 .on_action(cx.listener(|this, _: &search::FocusSearch, window, cx| {
3672 this.search_bar.focus_handle(cx).focus(window, cx);
3673 }))
3674 .on_action(cx.listener(|this, _: &ToggleFocusNav, window, cx| {
3675 if this
3676 .navbar_focus_handle
3677 .focus_handle(cx)
3678 .contains_focused(window, cx)
3679 {
3680 this.open_and_scroll_to_navbar_entry(
3681 this.navbar_entry,
3682 None,
3683 true,
3684 window,
3685 cx,
3686 );
3687 } else {
3688 this.focus_and_scroll_to_nav_entry(this.navbar_entry, window, cx);
3689 }
3690 }))
3691 .on_action(cx.listener(
3692 |this, FocusFile(file_index): &FocusFile, window, cx| {
3693 this.focus_file_at_index(*file_index as usize, window, cx);
3694 },
3695 ))
3696 .on_action(cx.listener(|this, _: &FocusNextFile, window, cx| {
3697 let next_index = usize::min(
3698 this.focused_file_index(window, cx) + 1,
3699 this.files.len().saturating_sub(1),
3700 );
3701 this.focus_file_at_index(next_index, window, cx);
3702 }))
3703 .on_action(cx.listener(|this, _: &FocusPreviousFile, window, cx| {
3704 let prev_index = this.focused_file_index(window, cx).saturating_sub(1);
3705 this.focus_file_at_index(prev_index, window, cx);
3706 }))
3707 .on_action(cx.listener(|this, _: &menu::SelectNext, window, cx| {
3708 if this
3709 .search_bar
3710 .focus_handle(cx)
3711 .contains_focused(window, cx)
3712 {
3713 this.focus_and_scroll_to_first_visible_nav_entry(window, cx);
3714 } else {
3715 window.focus_next(cx);
3716 }
3717 }))
3718 .on_action(|_: &menu::SelectPrevious, window, cx| {
3719 window.focus_prev(cx);
3720 })
3721 .flex()
3722 .flex_row()
3723 .flex_1()
3724 .min_h_0()
3725 .font(ui_font)
3726 .bg(cx.theme().colors().background)
3727 .text_color(cx.theme().colors().text)
3728 .when(!cfg!(target_os = "macos"), |this| {
3729 this.border_t_1().border_color(cx.theme().colors().border)
3730 })
3731 .child(self.render_nav(window, cx))
3732 .child(self.render_page(window, cx)),
3733 ),
3734 window,
3735 cx,
3736 Tiling::default(),
3737 )
3738 }
3739}
3740
3741fn all_projects(
3742 window: Option<&WindowHandle<MultiWorkspace>>,
3743 cx: &App,
3744) -> impl Iterator<Item = Entity<Project>> {
3745 let mut seen_project_ids = std::collections::HashSet::new();
3746 workspace::AppState::global(cx)
3747 .upgrade()
3748 .map(|app_state| {
3749 app_state
3750 .workspace_store
3751 .read(cx)
3752 .workspaces()
3753 .filter_map(|weak| weak.upgrade())
3754 .map(|workspace: Entity<Workspace>| workspace.read(cx).project().clone())
3755 .chain(
3756 window
3757 .and_then(|handle| handle.read(cx).ok())
3758 .into_iter()
3759 .flat_map(|multi_workspace| {
3760 multi_workspace
3761 .workspaces()
3762 .iter()
3763 .map(|workspace| workspace.read(cx).project().clone())
3764 .collect::<Vec<_>>()
3765 }),
3766 )
3767 .filter(move |project| seen_project_ids.insert(project.entity_id()))
3768 })
3769 .into_iter()
3770 .flatten()
3771}
3772
3773fn open_user_settings_in_workspace(
3774 workspace: &mut Workspace,
3775 window: &mut Window,
3776 cx: &mut Context<Workspace>,
3777) {
3778 let project = workspace.project().clone();
3779
3780 cx.spawn_in(window, async move |workspace, cx| {
3781 let (config_dir, settings_file) = project.update(cx, |project, cx| {
3782 (
3783 project.try_windows_path_to_wsl(paths::config_dir().as_path(), cx),
3784 project.try_windows_path_to_wsl(paths::settings_file().as_path(), cx),
3785 )
3786 });
3787 let config_dir = config_dir.await?;
3788 let settings_file = settings_file.await?;
3789 project
3790 .update(cx, |project, cx| {
3791 project.find_or_create_worktree(&config_dir, false, cx)
3792 })
3793 .await
3794 .ok();
3795 workspace
3796 .update_in(cx, |workspace, window, cx| {
3797 workspace.open_paths(
3798 vec![settings_file],
3799 OpenOptions {
3800 visible: Some(OpenVisible::None),
3801 ..Default::default()
3802 },
3803 None,
3804 window,
3805 cx,
3806 )
3807 })?
3808 .await;
3809
3810 workspace.update_in(cx, |_, window, cx| {
3811 window.activate_window();
3812 cx.notify();
3813 })
3814 })
3815 .detach();
3816}
3817
3818fn update_settings_file(
3819 file: SettingsUiFile,
3820 file_name: Option<&'static str>,
3821 window: &mut Window,
3822 cx: &mut App,
3823 update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
3824) -> Result<()> {
3825 telemetry::event!("Settings Change", setting = file_name, type = file.setting_type());
3826
3827 match file {
3828 SettingsUiFile::Project((worktree_id, rel_path)) => {
3829 let rel_path = rel_path.join(paths::local_settings_file_relative_path());
3830 let Some(settings_window) = window.root::<SettingsWindow>().flatten() else {
3831 anyhow::bail!("No settings window found");
3832 };
3833
3834 update_project_setting_file(worktree_id, rel_path, update, settings_window, cx)
3835 }
3836 SettingsUiFile::User => {
3837 // todo(settings_ui) error?
3838 SettingsStore::global(cx).update_settings_file(<dyn fs::Fs>::global(cx), update);
3839 Ok(())
3840 }
3841 SettingsUiFile::Server(_) => unimplemented!(),
3842 }
3843}
3844
3845struct ProjectSettingsUpdateEntry {
3846 worktree_id: WorktreeId,
3847 rel_path: Arc<RelPath>,
3848 settings_window: WeakEntity<SettingsWindow>,
3849 project: WeakEntity<Project>,
3850 worktree: WeakEntity<Worktree>,
3851 update: Box<dyn FnOnce(&mut SettingsContent, &App)>,
3852}
3853
3854struct ProjectSettingsUpdateQueue {
3855 tx: mpsc::UnboundedSender<ProjectSettingsUpdateEntry>,
3856 _task: Task<()>,
3857}
3858
3859impl Global for ProjectSettingsUpdateQueue {}
3860
3861impl ProjectSettingsUpdateQueue {
3862 fn new(cx: &mut App) -> Self {
3863 let (tx, mut rx) = mpsc::unbounded();
3864 let task = cx.spawn(async move |mut cx| {
3865 while let Some(entry) = rx.next().await {
3866 if let Err(err) = Self::process_entry(entry, &mut cx).await {
3867 log::error!("Failed to update project settings: {err:?}");
3868 }
3869 }
3870 });
3871 Self { tx, _task: task }
3872 }
3873
3874 fn enqueue(cx: &mut App, entry: ProjectSettingsUpdateEntry) {
3875 cx.update_global::<Self, _>(|queue, _cx| {
3876 if let Err(err) = queue.tx.unbounded_send(entry) {
3877 log::error!("Failed to enqueue project settings update: {err}");
3878 }
3879 });
3880 }
3881
3882 async fn process_entry(entry: ProjectSettingsUpdateEntry, cx: &mut AsyncApp) -> Result<()> {
3883 let ProjectSettingsUpdateEntry {
3884 worktree_id,
3885 rel_path,
3886 settings_window,
3887 project,
3888 worktree,
3889 update,
3890 } = entry;
3891
3892 let project_path = ProjectPath {
3893 worktree_id,
3894 path: rel_path.clone(),
3895 };
3896
3897 let needs_creation = worktree.read_with(cx, |worktree, _| {
3898 worktree.entry_for_path(&rel_path).is_none()
3899 })?;
3900
3901 if needs_creation {
3902 worktree
3903 .update(cx, |worktree, cx| {
3904 worktree.create_entry(rel_path.clone(), false, None, cx)
3905 })?
3906 .await?;
3907 }
3908
3909 let buffer_store = project.read_with(cx, |project, _cx| project.buffer_store().clone())?;
3910
3911 let cached_buffer = settings_window
3912 .read_with(cx, |settings_window, _| {
3913 settings_window
3914 .project_setting_file_buffers
3915 .get(&project_path)
3916 .cloned()
3917 })
3918 .unwrap_or_default();
3919
3920 let buffer = if let Some(cached_buffer) = cached_buffer {
3921 let needs_reload = cached_buffer.read_with(cx, |buffer, _| buffer.has_conflict());
3922 if needs_reload {
3923 cached_buffer
3924 .update(cx, |buffer, cx| buffer.reload(cx))
3925 .await
3926 .context("Failed to reload settings file")?;
3927 }
3928 cached_buffer
3929 } else {
3930 let buffer = buffer_store
3931 .update(cx, |store, cx| store.open_buffer(project_path.clone(), cx))
3932 .await
3933 .context("Failed to open settings file")?;
3934
3935 let _ = settings_window.update(cx, |this, _cx| {
3936 this.project_setting_file_buffers
3937 .insert(project_path, buffer.clone());
3938 });
3939
3940 buffer
3941 };
3942
3943 buffer.update(cx, |buffer, cx| {
3944 let current_text = buffer.text();
3945 let new_text = cx
3946 .global::<SettingsStore>()
3947 .new_text_for_update(current_text, |settings| update(settings, cx));
3948 buffer.edit([(0..buffer.len(), new_text)], None, cx);
3949 });
3950
3951 buffer_store
3952 .update(cx, |store, cx| store.save_buffer(buffer, cx))
3953 .await
3954 .context("Failed to save settings file")?;
3955
3956 Ok(())
3957 }
3958}
3959
3960fn update_project_setting_file(
3961 worktree_id: WorktreeId,
3962 rel_path: Arc<RelPath>,
3963 update: impl 'static + FnOnce(&mut SettingsContent, &App),
3964 settings_window: Entity<SettingsWindow>,
3965 cx: &mut App,
3966) -> Result<()> {
3967 let Some((worktree, project)) =
3968 all_projects(settings_window.read(cx).original_window.as_ref(), cx).find_map(|project| {
3969 project
3970 .read(cx)
3971 .worktree_for_id(worktree_id, cx)
3972 .zip(Some(project))
3973 })
3974 else {
3975 anyhow::bail!("Could not find project with worktree id: {}", worktree_id);
3976 };
3977
3978 let entry = ProjectSettingsUpdateEntry {
3979 worktree_id,
3980 rel_path,
3981 settings_window: settings_window.downgrade(),
3982 project: project.downgrade(),
3983 worktree: worktree.downgrade(),
3984 update: Box::new(update),
3985 };
3986
3987 ProjectSettingsUpdateQueue::enqueue(cx, entry);
3988
3989 Ok(())
3990}
3991
3992fn render_text_field<T: From<String> + Into<String> + AsRef<str> + Clone>(
3993 field: SettingField<T>,
3994 file: SettingsUiFile,
3995 metadata: Option<&SettingsFieldMetadata>,
3996 _window: &mut Window,
3997 cx: &mut App,
3998) -> AnyElement {
3999 let (_, initial_text) =
4000 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4001 let initial_text = initial_text.filter(|s| !s.as_ref().is_empty());
4002
4003 SettingsInputField::new()
4004 .tab_index(0)
4005 .when_some(initial_text, |editor, text| {
4006 editor.with_initial_text(text.as_ref().to_string())
4007 })
4008 .when_some(
4009 metadata.and_then(|metadata| metadata.placeholder),
4010 |editor, placeholder| editor.with_placeholder(placeholder),
4011 )
4012 .on_confirm({
4013 move |new_text, window, cx| {
4014 update_settings_file(
4015 file.clone(),
4016 field.json_path,
4017 window,
4018 cx,
4019 move |settings, _cx| {
4020 (field.write)(settings, new_text.map(Into::into));
4021 },
4022 )
4023 .log_err(); // todo(settings_ui) don't log err
4024 }
4025 })
4026 .into_any_element()
4027}
4028
4029fn render_toggle_button<B: Into<bool> + From<bool> + Copy>(
4030 field: SettingField<B>,
4031 file: SettingsUiFile,
4032 _metadata: Option<&SettingsFieldMetadata>,
4033 _window: &mut Window,
4034 cx: &mut App,
4035) -> AnyElement {
4036 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4037
4038 let toggle_state = if value.copied().map_or(false, Into::into) {
4039 ToggleState::Selected
4040 } else {
4041 ToggleState::Unselected
4042 };
4043
4044 Switch::new("toggle_button", toggle_state)
4045 .tab_index(0_isize)
4046 .on_click({
4047 move |state, window, cx| {
4048 telemetry::event!("Settings Change", setting = field.json_path, type = file.setting_type());
4049
4050 let state = *state == ui::ToggleState::Selected;
4051 update_settings_file(file.clone(), field.json_path, window, cx, move |settings, _cx| {
4052 (field.write)(settings, Some(state.into()));
4053 })
4054 .log_err(); // todo(settings_ui) don't log err
4055 }
4056 })
4057 .into_any_element()
4058}
4059
4060fn render_number_field<T: NumberFieldType + Send + Sync>(
4061 field: SettingField<T>,
4062 file: SettingsUiFile,
4063 _metadata: Option<&SettingsFieldMetadata>,
4064 window: &mut Window,
4065 cx: &mut App,
4066) -> AnyElement {
4067 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4068 let value = value.copied().unwrap_or_else(T::min_value);
4069
4070 let id = field
4071 .json_path
4072 .map(|p| format!("numeric_stepper_{}", p))
4073 .unwrap_or_else(|| "numeric_stepper".to_string());
4074
4075 NumberField::new(id, value, window, cx)
4076 .tab_index(0_isize)
4077 .on_change({
4078 move |value, window, cx| {
4079 let value = *value;
4080 update_settings_file(
4081 file.clone(),
4082 field.json_path,
4083 window,
4084 cx,
4085 move |settings, _cx| {
4086 (field.write)(settings, Some(value));
4087 },
4088 )
4089 .log_err(); // todo(settings_ui) don't log err
4090 }
4091 })
4092 .into_any_element()
4093}
4094
4095fn render_editable_number_field<T: NumberFieldType + Send + Sync>(
4096 field: SettingField<T>,
4097 file: SettingsUiFile,
4098 _metadata: Option<&SettingsFieldMetadata>,
4099 window: &mut Window,
4100 cx: &mut App,
4101) -> AnyElement {
4102 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4103 let value = value.copied().unwrap_or_else(T::min_value);
4104
4105 let id = field
4106 .json_path
4107 .map(|p| format!("numeric_stepper_{}", p))
4108 .unwrap_or_else(|| "numeric_stepper".to_string());
4109
4110 NumberField::new(id, value, window, cx)
4111 .mode(NumberFieldMode::Edit, cx)
4112 .tab_index(0_isize)
4113 .on_change({
4114 move |value, window, cx| {
4115 let value = *value;
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 .into_any_element()
4129}
4130
4131fn render_dropdown<T>(
4132 field: SettingField<T>,
4133 file: SettingsUiFile,
4134 metadata: Option<&SettingsFieldMetadata>,
4135 _window: &mut Window,
4136 cx: &mut App,
4137) -> AnyElement
4138where
4139 T: strum::VariantArray + strum::VariantNames + Copy + PartialEq + Send + Sync + 'static,
4140{
4141 let variants = || -> &'static [T] { <T as strum::VariantArray>::VARIANTS };
4142 let labels = || -> &'static [&'static str] { <T as strum::VariantNames>::VARIANTS };
4143 let should_do_titlecase = metadata
4144 .and_then(|metadata| metadata.should_do_titlecase)
4145 .unwrap_or(true);
4146
4147 let (_, current_value) =
4148 SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4149 let current_value = current_value.copied().unwrap_or(variants()[0]);
4150
4151 EnumVariantDropdown::new("dropdown", current_value, variants(), labels(), {
4152 move |value, window, cx| {
4153 if value == current_value {
4154 return;
4155 }
4156 update_settings_file(
4157 file.clone(),
4158 field.json_path,
4159 window,
4160 cx,
4161 move |settings, _cx| {
4162 (field.write)(settings, Some(value));
4163 },
4164 )
4165 .log_err(); // todo(settings_ui) don't log err
4166 }
4167 })
4168 .tab_index(0)
4169 .title_case(should_do_titlecase)
4170 .into_any_element()
4171}
4172
4173fn render_picker_trigger_button(id: SharedString, label: SharedString) -> Button {
4174 Button::new(id, label)
4175 .tab_index(0_isize)
4176 .style(ButtonStyle::Outlined)
4177 .size(ButtonSize::Medium)
4178 .end_icon(
4179 Icon::new(IconName::ChevronUpDown)
4180 .size(IconSize::Small)
4181 .color(Color::Muted),
4182 )
4183}
4184
4185fn render_font_picker(
4186 field: SettingField<settings::FontFamilyName>,
4187 file: SettingsUiFile,
4188 _metadata: Option<&SettingsFieldMetadata>,
4189 _window: &mut Window,
4190 cx: &mut App,
4191) -> AnyElement {
4192 let current_value = SettingsStore::global(cx)
4193 .get_value_from_file(file.to_settings(), field.pick)
4194 .1
4195 .cloned()
4196 .map_or_else(|| SharedString::default(), |value| value.into_gpui());
4197
4198 PopoverMenu::new("font-picker")
4199 .trigger(render_picker_trigger_button(
4200 "font_family_picker_trigger".into(),
4201 current_value.clone(),
4202 ))
4203 .menu(move |window, cx| {
4204 let file = file.clone();
4205 let current_value = current_value.clone();
4206
4207 Some(cx.new(move |cx| {
4208 font_picker(
4209 current_value,
4210 move |font_name, window, cx| {
4211 update_settings_file(
4212 file.clone(),
4213 field.json_path,
4214 window,
4215 cx,
4216 move |settings, _cx| {
4217 (field.write)(settings, Some(font_name.to_string().into()));
4218 },
4219 )
4220 .log_err(); // todo(settings_ui) don't log err
4221 },
4222 window,
4223 cx,
4224 )
4225 }))
4226 })
4227 .anchor(gpui::Corner::TopLeft)
4228 .offset(gpui::Point {
4229 x: px(0.0),
4230 y: px(2.0),
4231 })
4232 .with_handle(ui::PopoverMenuHandle::default())
4233 .into_any_element()
4234}
4235
4236fn render_theme_picker(
4237 field: SettingField<settings::ThemeName>,
4238 file: SettingsUiFile,
4239 _metadata: Option<&SettingsFieldMetadata>,
4240 _window: &mut Window,
4241 cx: &mut App,
4242) -> AnyElement {
4243 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4244 let current_value = value
4245 .cloned()
4246 .map(|theme_name| theme_name.0.into())
4247 .unwrap_or_else(|| cx.theme().name.clone());
4248
4249 PopoverMenu::new("theme-picker")
4250 .trigger(render_picker_trigger_button(
4251 "theme_picker_trigger".into(),
4252 current_value.clone(),
4253 ))
4254 .menu(move |window, cx| {
4255 Some(cx.new(|cx| {
4256 let file = file.clone();
4257 let current_value = current_value.clone();
4258 theme_picker(
4259 current_value,
4260 move |theme_name, window, cx| {
4261 update_settings_file(
4262 file.clone(),
4263 field.json_path,
4264 window,
4265 cx,
4266 move |settings, _cx| {
4267 (field.write)(
4268 settings,
4269 Some(settings::ThemeName(theme_name.into())),
4270 );
4271 },
4272 )
4273 .log_err(); // todo(settings_ui) don't log err
4274 },
4275 window,
4276 cx,
4277 )
4278 }))
4279 })
4280 .anchor(gpui::Corner::TopLeft)
4281 .offset(gpui::Point {
4282 x: px(0.0),
4283 y: px(2.0),
4284 })
4285 .with_handle(ui::PopoverMenuHandle::default())
4286 .into_any_element()
4287}
4288
4289fn render_icon_theme_picker(
4290 field: SettingField<settings::IconThemeName>,
4291 file: SettingsUiFile,
4292 _metadata: Option<&SettingsFieldMetadata>,
4293 _window: &mut Window,
4294 cx: &mut App,
4295) -> AnyElement {
4296 let (_, value) = SettingsStore::global(cx).get_value_from_file(file.to_settings(), field.pick);
4297 let current_value = value
4298 .cloned()
4299 .map(|theme_name| theme_name.0.into())
4300 .unwrap_or_else(|| cx.theme().name.clone());
4301
4302 PopoverMenu::new("icon-theme-picker")
4303 .trigger(render_picker_trigger_button(
4304 "icon_theme_picker_trigger".into(),
4305 current_value.clone(),
4306 ))
4307 .menu(move |window, cx| {
4308 Some(cx.new(|cx| {
4309 let file = file.clone();
4310 let current_value = current_value.clone();
4311 icon_theme_picker(
4312 current_value,
4313 move |theme_name, window, cx| {
4314 update_settings_file(
4315 file.clone(),
4316 field.json_path,
4317 window,
4318 cx,
4319 move |settings, _cx| {
4320 (field.write)(
4321 settings,
4322 Some(settings::IconThemeName(theme_name.into())),
4323 );
4324 },
4325 )
4326 .log_err(); // todo(settings_ui) don't log err
4327 },
4328 window,
4329 cx,
4330 )
4331 }))
4332 })
4333 .anchor(gpui::Corner::TopLeft)
4334 .offset(gpui::Point {
4335 x: px(0.0),
4336 y: px(2.0),
4337 })
4338 .with_handle(ui::PopoverMenuHandle::default())
4339 .into_any_element()
4340}
4341
4342#[cfg(test)]
4343pub mod test {
4344
4345 use super::*;
4346
4347 impl SettingsWindow {
4348 fn navbar_entry(&self) -> usize {
4349 self.navbar_entry
4350 }
4351
4352 #[cfg(any(test, feature = "test-support"))]
4353 pub fn test(window: &mut Window, cx: &mut Context<Self>) -> Self {
4354 let search_bar = cx.new(|cx| Editor::single_line(window, cx));
4355 let dummy_page = SettingsPage {
4356 title: "Test",
4357 items: Box::new([]),
4358 };
4359 Self {
4360 title_bar: None,
4361 original_window: None,
4362 worktree_root_dirs: HashMap::default(),
4363 files: Vec::default(),
4364 current_file: SettingsUiFile::User,
4365 project_setting_file_buffers: HashMap::default(),
4366 pages: vec![dummy_page],
4367 search_bar,
4368 navbar_entry: 0,
4369 navbar_entries: Vec::default(),
4370 navbar_scroll_handle: UniformListScrollHandle::default(),
4371 navbar_focus_subscriptions: Vec::default(),
4372 filter_table: Vec::default(),
4373 has_query: false,
4374 content_handles: Vec::default(),
4375 search_task: None,
4376 sub_page_stack: Vec::default(),
4377 opening_link: false,
4378 focus_handle: cx.focus_handle(),
4379 navbar_focus_handle: NonFocusableHandle::new(
4380 NAVBAR_CONTAINER_TAB_INDEX,
4381 false,
4382 window,
4383 cx,
4384 ),
4385 content_focus_handle: NonFocusableHandle::new(
4386 CONTENT_CONTAINER_TAB_INDEX,
4387 false,
4388 window,
4389 cx,
4390 ),
4391 files_focus_handle: cx.focus_handle(),
4392 search_index: None,
4393 list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
4394 shown_errors: HashSet::default(),
4395 regex_validation_error: None,
4396 }
4397 }
4398 }
4399
4400 impl PartialEq for NavBarEntry {
4401 fn eq(&self, other: &Self) -> bool {
4402 self.title == other.title
4403 && self.is_root == other.is_root
4404 && self.expanded == other.expanded
4405 && self.page_index == other.page_index
4406 && self.item_index == other.item_index
4407 // ignoring focus_handle
4408 }
4409 }
4410
4411 pub fn register_settings(cx: &mut App) {
4412 settings::init(cx);
4413 theme::init(theme::LoadThemes::JustBase, cx);
4414 editor::init(cx);
4415 menu::init();
4416 }
4417
4418 fn parse(input: &'static str, window: &mut Window, cx: &mut App) -> SettingsWindow {
4419 struct PageBuilder {
4420 title: &'static str,
4421 items: Vec<SettingsPageItem>,
4422 }
4423 let mut page_builders: Vec<PageBuilder> = Vec::new();
4424 let mut expanded_pages = Vec::new();
4425 let mut selected_idx = None;
4426 let mut index = 0;
4427 let mut in_expanded_section = false;
4428
4429 for mut line in input
4430 .lines()
4431 .map(|line| line.trim())
4432 .filter(|line| !line.is_empty())
4433 {
4434 if let Some(pre) = line.strip_suffix('*') {
4435 assert!(selected_idx.is_none(), "Only one selected entry allowed");
4436 selected_idx = Some(index);
4437 line = pre;
4438 }
4439 let (kind, title) = line.split_once(" ").unwrap();
4440 assert_eq!(kind.len(), 1);
4441 let kind = kind.chars().next().unwrap();
4442 if kind == 'v' {
4443 let page_idx = page_builders.len();
4444 expanded_pages.push(page_idx);
4445 page_builders.push(PageBuilder {
4446 title,
4447 items: vec![],
4448 });
4449 index += 1;
4450 in_expanded_section = true;
4451 } else if kind == '>' {
4452 page_builders.push(PageBuilder {
4453 title,
4454 items: vec![],
4455 });
4456 index += 1;
4457 in_expanded_section = false;
4458 } else if kind == '-' {
4459 page_builders
4460 .last_mut()
4461 .unwrap()
4462 .items
4463 .push(SettingsPageItem::SectionHeader(title));
4464 if selected_idx == Some(index) && !in_expanded_section {
4465 panic!("Items in unexpanded sections cannot be selected");
4466 }
4467 index += 1;
4468 } else {
4469 panic!(
4470 "Entries must start with one of 'v', '>', or '-'\n line: {}",
4471 line
4472 );
4473 }
4474 }
4475
4476 let pages: Vec<SettingsPage> = page_builders
4477 .into_iter()
4478 .map(|builder| SettingsPage {
4479 title: builder.title,
4480 items: builder.items.into_boxed_slice(),
4481 })
4482 .collect();
4483
4484 let mut settings_window = SettingsWindow {
4485 title_bar: None,
4486 original_window: None,
4487 worktree_root_dirs: HashMap::default(),
4488 files: Vec::default(),
4489 current_file: crate::SettingsUiFile::User,
4490 project_setting_file_buffers: HashMap::default(),
4491 pages,
4492 search_bar: cx.new(|cx| Editor::single_line(window, cx)),
4493 navbar_entry: selected_idx.expect("Must have a selected navbar entry"),
4494 navbar_entries: Vec::default(),
4495 navbar_scroll_handle: UniformListScrollHandle::default(),
4496 navbar_focus_subscriptions: vec![],
4497 filter_table: vec![],
4498 sub_page_stack: vec![],
4499 opening_link: false,
4500 has_query: false,
4501 content_handles: vec![],
4502 search_task: None,
4503 focus_handle: cx.focus_handle(),
4504 navbar_focus_handle: NonFocusableHandle::new(
4505 NAVBAR_CONTAINER_TAB_INDEX,
4506 false,
4507 window,
4508 cx,
4509 ),
4510 content_focus_handle: NonFocusableHandle::new(
4511 CONTENT_CONTAINER_TAB_INDEX,
4512 false,
4513 window,
4514 cx,
4515 ),
4516 files_focus_handle: cx.focus_handle(),
4517 search_index: None,
4518 list_state: ListState::new(0, gpui::ListAlignment::Top, px(0.0)),
4519 shown_errors: HashSet::default(),
4520 regex_validation_error: None,
4521 };
4522
4523 settings_window.build_filter_table();
4524 settings_window.build_navbar(cx);
4525 for expanded_page_index in expanded_pages {
4526 for entry in &mut settings_window.navbar_entries {
4527 if entry.page_index == expanded_page_index && entry.is_root {
4528 entry.expanded = true;
4529 }
4530 }
4531 }
4532 settings_window
4533 }
4534
4535 #[track_caller]
4536 fn check_navbar_toggle(
4537 before: &'static str,
4538 toggle_page: &'static str,
4539 after: &'static str,
4540 window: &mut Window,
4541 cx: &mut App,
4542 ) {
4543 let mut settings_window = parse(before, window, cx);
4544 let toggle_page_idx = settings_window
4545 .pages
4546 .iter()
4547 .position(|page| page.title == toggle_page)
4548 .expect("page not found");
4549 let toggle_idx = settings_window
4550 .navbar_entries
4551 .iter()
4552 .position(|entry| entry.page_index == toggle_page_idx)
4553 .expect("page not found");
4554 settings_window.toggle_navbar_entry(toggle_idx);
4555
4556 let expected_settings_window = parse(after, window, cx);
4557
4558 pretty_assertions::assert_eq!(
4559 settings_window
4560 .visible_navbar_entries()
4561 .map(|(_, entry)| entry)
4562 .collect::<Vec<_>>(),
4563 expected_settings_window
4564 .visible_navbar_entries()
4565 .map(|(_, entry)| entry)
4566 .collect::<Vec<_>>(),
4567 );
4568 pretty_assertions::assert_eq!(
4569 settings_window.navbar_entries[settings_window.navbar_entry()],
4570 expected_settings_window.navbar_entries[expected_settings_window.navbar_entry()],
4571 );
4572 }
4573
4574 macro_rules! check_navbar_toggle {
4575 ($name:ident, before: $before:expr, toggle_page: $toggle_page:expr, after: $after:expr) => {
4576 #[gpui::test]
4577 fn $name(cx: &mut gpui::TestAppContext) {
4578 let window = cx.add_empty_window();
4579 window.update(|window, cx| {
4580 register_settings(cx);
4581 check_navbar_toggle($before, $toggle_page, $after, window, cx);
4582 });
4583 }
4584 };
4585 }
4586
4587 check_navbar_toggle!(
4588 navbar_basic_open,
4589 before: r"
4590 v General
4591 - General
4592 - Privacy*
4593 v Project
4594 - Project Settings
4595 ",
4596 toggle_page: "General",
4597 after: r"
4598 > General*
4599 v Project
4600 - Project Settings
4601 "
4602 );
4603
4604 check_navbar_toggle!(
4605 navbar_basic_close,
4606 before: r"
4607 > General*
4608 - General
4609 - Privacy
4610 v Project
4611 - Project Settings
4612 ",
4613 toggle_page: "General",
4614 after: r"
4615 v General*
4616 - General
4617 - Privacy
4618 v Project
4619 - Project Settings
4620 "
4621 );
4622
4623 check_navbar_toggle!(
4624 navbar_basic_second_root_entry_close,
4625 before: r"
4626 > General
4627 - General
4628 - Privacy
4629 v Project
4630 - Project Settings*
4631 ",
4632 toggle_page: "Project",
4633 after: r"
4634 > General
4635 > Project*
4636 "
4637 );
4638
4639 check_navbar_toggle!(
4640 navbar_toggle_subroot,
4641 before: r"
4642 v General Page
4643 - General
4644 - Privacy
4645 v Project
4646 - Worktree Settings Content*
4647 v AI
4648 - General
4649 > Appearance & Behavior
4650 ",
4651 toggle_page: "Project",
4652 after: r"
4653 v General Page
4654 - General
4655 - Privacy
4656 > Project*
4657 v AI
4658 - General
4659 > Appearance & Behavior
4660 "
4661 );
4662
4663 check_navbar_toggle!(
4664 navbar_toggle_close_propagates_selected_index,
4665 before: r"
4666 v General Page
4667 - General
4668 - Privacy
4669 v Project
4670 - Worktree Settings Content
4671 v AI
4672 - General*
4673 > Appearance & Behavior
4674 ",
4675 toggle_page: "General Page",
4676 after: r"
4677 > General Page*
4678 v Project
4679 - Worktree Settings Content
4680 v AI
4681 - General
4682 > Appearance & Behavior
4683 "
4684 );
4685
4686 check_navbar_toggle!(
4687 navbar_toggle_expand_propagates_selected_index,
4688 before: r"
4689 > General Page
4690 - General
4691 - Privacy
4692 v Project
4693 - Worktree Settings Content
4694 v AI
4695 - General*
4696 > Appearance & Behavior
4697 ",
4698 toggle_page: "General Page",
4699 after: r"
4700 v General Page*
4701 - General
4702 - Privacy
4703 v Project
4704 - Worktree Settings Content
4705 v AI
4706 - General
4707 > Appearance & Behavior
4708 "
4709 );
4710
4711 #[gpui::test]
4712 async fn test_settings_window_shows_worktrees_from_multiple_workspaces(
4713 cx: &mut gpui::TestAppContext,
4714 ) {
4715 use project::Project;
4716 use serde_json::json;
4717
4718 cx.update(|cx| {
4719 register_settings(cx);
4720 });
4721
4722 let app_state = cx.update(|cx| {
4723 let app_state = AppState::test(cx);
4724 AppState::set_global(Arc::downgrade(&app_state), cx);
4725 app_state
4726 });
4727
4728 let fake_fs = app_state.fs.as_fake();
4729
4730 fake_fs
4731 .insert_tree(
4732 "/workspace1",
4733 json!({
4734 "worktree_a": {
4735 "file1.rs": "fn main() {}"
4736 },
4737 "worktree_b": {
4738 "file2.rs": "fn test() {}"
4739 }
4740 }),
4741 )
4742 .await;
4743
4744 fake_fs
4745 .insert_tree(
4746 "/workspace2",
4747 json!({
4748 "worktree_c": {
4749 "file3.rs": "fn foo() {}"
4750 }
4751 }),
4752 )
4753 .await;
4754
4755 let project1 = cx.update(|cx| {
4756 Project::local(
4757 app_state.client.clone(),
4758 app_state.node_runtime.clone(),
4759 app_state.user_store.clone(),
4760 app_state.languages.clone(),
4761 app_state.fs.clone(),
4762 None,
4763 project::LocalProjectFlags::default(),
4764 cx,
4765 )
4766 });
4767
4768 project1
4769 .update(cx, |project, cx| {
4770 project.find_or_create_worktree("/workspace1/worktree_a", true, cx)
4771 })
4772 .await
4773 .expect("Failed to create worktree_a");
4774 project1
4775 .update(cx, |project, cx| {
4776 project.find_or_create_worktree("/workspace1/worktree_b", true, cx)
4777 })
4778 .await
4779 .expect("Failed to create worktree_b");
4780
4781 let project2 = cx.update(|cx| {
4782 Project::local(
4783 app_state.client.clone(),
4784 app_state.node_runtime.clone(),
4785 app_state.user_store.clone(),
4786 app_state.languages.clone(),
4787 app_state.fs.clone(),
4788 None,
4789 project::LocalProjectFlags::default(),
4790 cx,
4791 )
4792 });
4793
4794 project2
4795 .update(cx, |project, cx| {
4796 project.find_or_create_worktree("/workspace2/worktree_c", true, cx)
4797 })
4798 .await
4799 .expect("Failed to create worktree_c");
4800
4801 let (_multi_workspace1, cx) = cx.add_window_view(|window, cx| {
4802 let workspace = cx.new(|cx| {
4803 Workspace::new(
4804 Default::default(),
4805 project1.clone(),
4806 app_state.clone(),
4807 window,
4808 cx,
4809 )
4810 });
4811 MultiWorkspace::new(workspace, window, cx)
4812 });
4813
4814 let (_multi_workspace2, cx) = cx.add_window_view(|window, cx| {
4815 let workspace = cx.new(|cx| {
4816 Workspace::new(
4817 Default::default(),
4818 project2.clone(),
4819 app_state.clone(),
4820 window,
4821 cx,
4822 )
4823 });
4824 MultiWorkspace::new(workspace, window, cx)
4825 });
4826
4827 let workspace2_handle = cx.window_handle().downcast::<MultiWorkspace>().unwrap();
4828
4829 cx.run_until_parked();
4830
4831 let (settings_window, cx) = cx
4832 .add_window_view(|window, cx| SettingsWindow::new(Some(workspace2_handle), window, cx));
4833
4834 cx.run_until_parked();
4835
4836 settings_window.read_with(cx, |settings_window, _| {
4837 let worktree_names: Vec<_> = settings_window
4838 .worktree_root_dirs
4839 .values()
4840 .cloned()
4841 .collect();
4842
4843 assert!(
4844 worktree_names.iter().any(|name| name == "worktree_a"),
4845 "Should contain worktree_a from workspace1, but found: {:?}",
4846 worktree_names
4847 );
4848 assert!(
4849 worktree_names.iter().any(|name| name == "worktree_b"),
4850 "Should contain worktree_b from workspace1, but found: {:?}",
4851 worktree_names
4852 );
4853 assert!(
4854 worktree_names.iter().any(|name| name == "worktree_c"),
4855 "Should contain worktree_c from workspace2, but found: {:?}",
4856 worktree_names
4857 );
4858
4859 assert_eq!(
4860 worktree_names.len(),
4861 3,
4862 "Should have exactly 3 worktrees from both workspaces, but found: {:?}",
4863 worktree_names
4864 );
4865
4866 let project_files: Vec<_> = settings_window
4867 .files
4868 .iter()
4869 .filter_map(|(f, _)| match f {
4870 SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
4871 _ => None,
4872 })
4873 .collect();
4874
4875 let unique_project_files: std::collections::HashSet<_> = project_files.iter().collect();
4876 assert_eq!(
4877 project_files.len(),
4878 unique_project_files.len(),
4879 "Should have no duplicate project files, but found duplicates. All files: {:?}",
4880 project_files
4881 );
4882 });
4883 }
4884
4885 #[gpui::test]
4886 async fn test_settings_window_updates_when_new_workspace_created(
4887 cx: &mut gpui::TestAppContext,
4888 ) {
4889 use project::Project;
4890 use serde_json::json;
4891
4892 cx.update(|cx| {
4893 register_settings(cx);
4894 });
4895
4896 let app_state = cx.update(|cx| {
4897 let app_state = AppState::test(cx);
4898 AppState::set_global(Arc::downgrade(&app_state), cx);
4899 app_state
4900 });
4901
4902 let fake_fs = app_state.fs.as_fake();
4903
4904 fake_fs
4905 .insert_tree(
4906 "/workspace1",
4907 json!({
4908 "worktree_a": {
4909 "file1.rs": "fn main() {}"
4910 }
4911 }),
4912 )
4913 .await;
4914
4915 fake_fs
4916 .insert_tree(
4917 "/workspace2",
4918 json!({
4919 "worktree_b": {
4920 "file2.rs": "fn test() {}"
4921 }
4922 }),
4923 )
4924 .await;
4925
4926 let project1 = cx.update(|cx| {
4927 Project::local(
4928 app_state.client.clone(),
4929 app_state.node_runtime.clone(),
4930 app_state.user_store.clone(),
4931 app_state.languages.clone(),
4932 app_state.fs.clone(),
4933 None,
4934 project::LocalProjectFlags::default(),
4935 cx,
4936 )
4937 });
4938
4939 project1
4940 .update(cx, |project, cx| {
4941 project.find_or_create_worktree("/workspace1/worktree_a", true, cx)
4942 })
4943 .await
4944 .expect("Failed to create worktree_a");
4945
4946 let (_multi_workspace1, cx) = cx.add_window_view(|window, cx| {
4947 let workspace = cx.new(|cx| {
4948 Workspace::new(
4949 Default::default(),
4950 project1.clone(),
4951 app_state.clone(),
4952 window,
4953 cx,
4954 )
4955 });
4956 MultiWorkspace::new(workspace, window, cx)
4957 });
4958
4959 let workspace1_handle = cx.window_handle().downcast::<MultiWorkspace>().unwrap();
4960
4961 cx.run_until_parked();
4962
4963 let (settings_window, cx) = cx
4964 .add_window_view(|window, cx| SettingsWindow::new(Some(workspace1_handle), window, cx));
4965
4966 cx.run_until_parked();
4967
4968 settings_window.read_with(cx, |settings_window, _| {
4969 assert_eq!(
4970 settings_window.worktree_root_dirs.len(),
4971 1,
4972 "Should have 1 worktree initially"
4973 );
4974 });
4975
4976 let project2 = cx.update(|_, cx| {
4977 Project::local(
4978 app_state.client.clone(),
4979 app_state.node_runtime.clone(),
4980 app_state.user_store.clone(),
4981 app_state.languages.clone(),
4982 app_state.fs.clone(),
4983 None,
4984 project::LocalProjectFlags::default(),
4985 cx,
4986 )
4987 });
4988
4989 project2
4990 .update(&mut cx.cx, |project, cx| {
4991 project.find_or_create_worktree("/workspace2/worktree_b", true, cx)
4992 })
4993 .await
4994 .expect("Failed to create worktree_b");
4995
4996 let (_multi_workspace2, cx) = cx.add_window_view(|window, cx| {
4997 let workspace = cx.new(|cx| {
4998 Workspace::new(
4999 Default::default(),
5000 project2.clone(),
5001 app_state.clone(),
5002 window,
5003 cx,
5004 )
5005 });
5006 MultiWorkspace::new(workspace, window, cx)
5007 });
5008
5009 cx.run_until_parked();
5010
5011 settings_window.read_with(cx, |settings_window, _| {
5012 let worktree_names: Vec<_> = settings_window
5013 .worktree_root_dirs
5014 .values()
5015 .cloned()
5016 .collect();
5017
5018 assert!(
5019 worktree_names.iter().any(|name| name == "worktree_a"),
5020 "Should contain worktree_a, but found: {:?}",
5021 worktree_names
5022 );
5023 assert!(
5024 worktree_names.iter().any(|name| name == "worktree_b"),
5025 "Should contain worktree_b from newly created workspace, but found: {:?}",
5026 worktree_names
5027 );
5028
5029 assert_eq!(
5030 worktree_names.len(),
5031 2,
5032 "Should have 2 worktrees after new workspace created, but found: {:?}",
5033 worktree_names
5034 );
5035
5036 let project_files: Vec<_> = settings_window
5037 .files
5038 .iter()
5039 .filter_map(|(f, _)| match f {
5040 SettingsUiFile::Project((worktree_id, _)) => Some(*worktree_id),
5041 _ => None,
5042 })
5043 .collect();
5044
5045 let unique_project_files: std::collections::HashSet<_> = project_files.iter().collect();
5046 assert_eq!(
5047 project_files.len(),
5048 unique_project_files.len(),
5049 "Should have no duplicate project files, but found duplicates. All files: {:?}",
5050 project_files
5051 );
5052 });
5053 }
5054}
5055
5056#[cfg(test)]
5057mod project_settings_update_tests {
5058 use super::*;
5059 use fs::{FakeFs, Fs as _};
5060 use gpui::TestAppContext;
5061 use project::Project;
5062 use serde_json::json;
5063 use std::sync::atomic::{AtomicUsize, Ordering};
5064
5065 struct TestSetup {
5066 fs: Arc<FakeFs>,
5067 project: Entity<Project>,
5068 worktree_id: WorktreeId,
5069 worktree: WeakEntity<Worktree>,
5070 rel_path: Arc<RelPath>,
5071 project_path: ProjectPath,
5072 }
5073
5074 async fn init_test(cx: &mut TestAppContext, initial_settings: Option<&str>) -> TestSetup {
5075 cx.update(|cx| {
5076 let store = settings::SettingsStore::test(cx);
5077 cx.set_global(store);
5078 theme::init(theme::LoadThemes::JustBase, cx);
5079 editor::init(cx);
5080 menu::init();
5081 let queue = ProjectSettingsUpdateQueue::new(cx);
5082 cx.set_global(queue);
5083 });
5084
5085 let fs = FakeFs::new(cx.executor());
5086 let tree = if let Some(settings_content) = initial_settings {
5087 json!({
5088 ".zed": {
5089 "settings.json": settings_content
5090 },
5091 "src": { "main.rs": "" }
5092 })
5093 } else {
5094 json!({ "src": { "main.rs": "" } })
5095 };
5096 fs.insert_tree("/project", tree).await;
5097
5098 let project = Project::test(fs.clone(), ["/project".as_ref()], cx).await;
5099
5100 let (worktree_id, worktree) = project.read_with(cx, |project, cx| {
5101 let worktree = project.worktrees(cx).next().unwrap();
5102 (worktree.read(cx).id(), worktree.downgrade())
5103 });
5104
5105 let rel_path: Arc<RelPath> = RelPath::unix(".zed/settings.json")
5106 .expect("valid path")
5107 .into_arc();
5108 let project_path = ProjectPath {
5109 worktree_id,
5110 path: rel_path.clone(),
5111 };
5112
5113 TestSetup {
5114 fs,
5115 project,
5116 worktree_id,
5117 worktree,
5118 rel_path,
5119 project_path,
5120 }
5121 }
5122
5123 #[gpui::test]
5124 async fn test_creates_settings_file_if_missing(cx: &mut TestAppContext) {
5125 let setup = init_test(cx, None).await;
5126
5127 let entry = ProjectSettingsUpdateEntry {
5128 worktree_id: setup.worktree_id,
5129 rel_path: setup.rel_path.clone(),
5130 settings_window: WeakEntity::new_invalid(),
5131 project: setup.project.downgrade(),
5132 worktree: setup.worktree,
5133 update: Box::new(|content, _cx| {
5134 content.project.all_languages.defaults.tab_size = Some(NonZeroU32::new(4).unwrap());
5135 }),
5136 };
5137
5138 cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5139 cx.executor().run_until_parked();
5140
5141 let buffer_store = setup
5142 .project
5143 .read_with(cx, |project, _| project.buffer_store().clone());
5144 let buffer = buffer_store
5145 .update(cx, |store, cx| store.open_buffer(setup.project_path, cx))
5146 .await
5147 .expect("buffer should exist");
5148
5149 let text = buffer.read_with(cx, |buffer, _| buffer.text());
5150 assert!(
5151 text.contains("\"tab_size\": 4"),
5152 "Expected tab_size setting in: {}",
5153 text
5154 );
5155 }
5156
5157 #[gpui::test]
5158 async fn test_updates_existing_settings_file(cx: &mut TestAppContext) {
5159 let setup = init_test(cx, Some(r#"{ "tab_size": 2 }"#)).await;
5160
5161 let entry = ProjectSettingsUpdateEntry {
5162 worktree_id: setup.worktree_id,
5163 rel_path: setup.rel_path.clone(),
5164 settings_window: WeakEntity::new_invalid(),
5165 project: setup.project.downgrade(),
5166 worktree: setup.worktree,
5167 update: Box::new(|content, _cx| {
5168 content.project.all_languages.defaults.tab_size = Some(NonZeroU32::new(8).unwrap());
5169 }),
5170 };
5171
5172 cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5173 cx.executor().run_until_parked();
5174
5175 let buffer_store = setup
5176 .project
5177 .read_with(cx, |project, _| project.buffer_store().clone());
5178 let buffer = buffer_store
5179 .update(cx, |store, cx| store.open_buffer(setup.project_path, cx))
5180 .await
5181 .expect("buffer should exist");
5182
5183 let text = buffer.read_with(cx, |buffer, _| buffer.text());
5184 assert!(
5185 text.contains("\"tab_size\": 8"),
5186 "Expected updated tab_size in: {}",
5187 text
5188 );
5189 }
5190
5191 #[gpui::test]
5192 async fn test_updates_are_serialized(cx: &mut TestAppContext) {
5193 let setup = init_test(cx, Some("{}")).await;
5194
5195 let update_order = Arc::new(std::sync::Mutex::new(Vec::new()));
5196
5197 for i in 1..=3 {
5198 let update_order = update_order.clone();
5199 let entry = ProjectSettingsUpdateEntry {
5200 worktree_id: setup.worktree_id,
5201 rel_path: setup.rel_path.clone(),
5202 settings_window: WeakEntity::new_invalid(),
5203 project: setup.project.downgrade(),
5204 worktree: setup.worktree.clone(),
5205 update: Box::new(move |content, _cx| {
5206 update_order.lock().unwrap().push(i);
5207 content.project.all_languages.defaults.tab_size =
5208 Some(NonZeroU32::new(i).unwrap());
5209 }),
5210 };
5211 cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5212 }
5213
5214 cx.executor().run_until_parked();
5215
5216 let order = update_order.lock().unwrap().clone();
5217 assert_eq!(order, vec![1, 2, 3], "Updates should be processed in order");
5218
5219 let buffer_store = setup
5220 .project
5221 .read_with(cx, |project, _| project.buffer_store().clone());
5222 let buffer = buffer_store
5223 .update(cx, |store, cx| store.open_buffer(setup.project_path, cx))
5224 .await
5225 .expect("buffer should exist");
5226
5227 let text = buffer.read_with(cx, |buffer, _| buffer.text());
5228 assert!(
5229 text.contains("\"tab_size\": 3"),
5230 "Final tab_size should be 3: {}",
5231 text
5232 );
5233 }
5234
5235 #[gpui::test]
5236 async fn test_queue_continues_after_failure(cx: &mut TestAppContext) {
5237 let setup = init_test(cx, Some("{}")).await;
5238
5239 let successful_updates = Arc::new(AtomicUsize::new(0));
5240
5241 {
5242 let successful_updates = successful_updates.clone();
5243 let entry = ProjectSettingsUpdateEntry {
5244 worktree_id: setup.worktree_id,
5245 rel_path: setup.rel_path.clone(),
5246 settings_window: WeakEntity::new_invalid(),
5247 project: setup.project.downgrade(),
5248 worktree: setup.worktree.clone(),
5249 update: Box::new(move |content, _cx| {
5250 successful_updates.fetch_add(1, Ordering::SeqCst);
5251 content.project.all_languages.defaults.tab_size =
5252 Some(NonZeroU32::new(2).unwrap());
5253 }),
5254 };
5255 cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5256 }
5257
5258 {
5259 let entry = ProjectSettingsUpdateEntry {
5260 worktree_id: setup.worktree_id,
5261 rel_path: setup.rel_path.clone(),
5262 settings_window: WeakEntity::new_invalid(),
5263 project: WeakEntity::new_invalid(),
5264 worktree: setup.worktree.clone(),
5265 update: Box::new(|content, _cx| {
5266 content.project.all_languages.defaults.tab_size =
5267 Some(NonZeroU32::new(99).unwrap());
5268 }),
5269 };
5270 cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5271 }
5272
5273 {
5274 let successful_updates = successful_updates.clone();
5275 let entry = ProjectSettingsUpdateEntry {
5276 worktree_id: setup.worktree_id,
5277 rel_path: setup.rel_path.clone(),
5278 settings_window: WeakEntity::new_invalid(),
5279 project: setup.project.downgrade(),
5280 worktree: setup.worktree.clone(),
5281 update: Box::new(move |content, _cx| {
5282 successful_updates.fetch_add(1, Ordering::SeqCst);
5283 content.project.all_languages.defaults.tab_size =
5284 Some(NonZeroU32::new(4).unwrap());
5285 }),
5286 };
5287 cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5288 }
5289
5290 cx.executor().run_until_parked();
5291
5292 assert_eq!(
5293 successful_updates.load(Ordering::SeqCst),
5294 2,
5295 "Two updates should have succeeded despite middle failure"
5296 );
5297
5298 let buffer_store = setup
5299 .project
5300 .read_with(cx, |project, _| project.buffer_store().clone());
5301 let buffer = buffer_store
5302 .update(cx, |store, cx| store.open_buffer(setup.project_path, cx))
5303 .await
5304 .expect("buffer should exist");
5305
5306 let text = buffer.read_with(cx, |buffer, _| buffer.text());
5307 assert!(
5308 text.contains("\"tab_size\": 4"),
5309 "Final tab_size should be 4 (third update): {}",
5310 text
5311 );
5312 }
5313
5314 #[gpui::test]
5315 async fn test_handles_dropped_worktree(cx: &mut TestAppContext) {
5316 let setup = init_test(cx, Some("{}")).await;
5317
5318 let entry = ProjectSettingsUpdateEntry {
5319 worktree_id: setup.worktree_id,
5320 rel_path: setup.rel_path.clone(),
5321 settings_window: WeakEntity::new_invalid(),
5322 project: setup.project.downgrade(),
5323 worktree: WeakEntity::new_invalid(),
5324 update: Box::new(|content, _cx| {
5325 content.project.all_languages.defaults.tab_size =
5326 Some(NonZeroU32::new(99).unwrap());
5327 }),
5328 };
5329
5330 cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5331 cx.executor().run_until_parked();
5332
5333 let file_content = setup
5334 .fs
5335 .load("/project/.zed/settings.json".as_ref())
5336 .await
5337 .unwrap();
5338 assert_eq!(
5339 file_content, "{}",
5340 "File should be unchanged when worktree is dropped"
5341 );
5342 }
5343
5344 #[gpui::test]
5345 async fn test_reloads_conflicted_buffer(cx: &mut TestAppContext) {
5346 let setup = init_test(cx, Some(r#"{ "tab_size": 2 }"#)).await;
5347
5348 let buffer_store = setup
5349 .project
5350 .read_with(cx, |project, _| project.buffer_store().clone());
5351 let buffer = buffer_store
5352 .update(cx, |store, cx| {
5353 store.open_buffer(setup.project_path.clone(), cx)
5354 })
5355 .await
5356 .expect("buffer should exist");
5357
5358 buffer.update(cx, |buffer, cx| {
5359 buffer.edit([(0..0, "// comment\n")], None, cx);
5360 });
5361
5362 let has_unsaved_edits = buffer.read_with(cx, |buffer, _| buffer.has_unsaved_edits());
5363 assert!(has_unsaved_edits, "Buffer should have unsaved edits");
5364
5365 setup
5366 .fs
5367 .save(
5368 "/project/.zed/settings.json".as_ref(),
5369 &r#"{ "tab_size": 99 }"#.into(),
5370 Default::default(),
5371 )
5372 .await
5373 .expect("save should succeed");
5374
5375 cx.executor().run_until_parked();
5376
5377 let has_conflict = buffer.read_with(cx, |buffer, _| buffer.has_conflict());
5378 assert!(
5379 has_conflict,
5380 "Buffer should have conflict after external modification"
5381 );
5382
5383 let (settings_window, _) = cx.add_window_view(|window, cx| {
5384 let mut sw = SettingsWindow::test(window, cx);
5385 sw.project_setting_file_buffers
5386 .insert(setup.project_path.clone(), buffer.clone());
5387 sw
5388 });
5389
5390 let entry = ProjectSettingsUpdateEntry {
5391 worktree_id: setup.worktree_id,
5392 rel_path: setup.rel_path.clone(),
5393 settings_window: settings_window.downgrade(),
5394 project: setup.project.downgrade(),
5395 worktree: setup.worktree.clone(),
5396 update: Box::new(|content, _cx| {
5397 content.project.all_languages.defaults.tab_size = Some(NonZeroU32::new(4).unwrap());
5398 }),
5399 };
5400
5401 cx.update(|cx| ProjectSettingsUpdateQueue::enqueue(cx, entry));
5402 cx.executor().run_until_parked();
5403
5404 let text = buffer.read_with(cx, |buffer, _| buffer.text());
5405 assert!(
5406 text.contains("\"tab_size\": 4"),
5407 "Buffer should have the new tab_size after reload and update: {}",
5408 text
5409 );
5410 assert!(
5411 !text.contains("// comment"),
5412 "Buffer should not contain the unsaved edit after reload: {}",
5413 text
5414 );
5415 assert!(
5416 !text.contains("99"),
5417 "Buffer should not contain the external modification value: {}",
5418 text
5419 );
5420 }
5421}