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