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