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