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