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