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