ZIm/crates/settings_ui/src/settings_ui.rs
Julia Ryan f11c749353
VSCode Settings import (#29018)
Things this doesn't currently handle:

- [x] ~testing~
- ~we really need an snapshot test that takes a vscode settings file
with all options that we support, and verifies the zed settings file you
get from importing it, both from an empty starting file or one with lots
of conflicts. that way we can open said vscode settings file in vscode
to ensure that those options all still exist in the future.~
- Discussed this, we don't think this will meaningfully protect us from
future failures, and we will just do this as a manual validation step
before merging this PR. Any imports that have meaningfully complex
translation steps should still be tested.
- [x] confirmation (right now it just clobbers your settings file
silently)
- it'd be really cool if we could show a diff multibuffer of your
current settings with the result of the vscode import and let you pick
"hunks" to keep, but that's probably too much effort for this feature,
especially given that we expect most of the people using it to have an
empty/barebones zed config when they run the import.
- [x] ~UI in the "welcome" page~
- we're planning on redoing our welcome/walkthrough experience anyways,
but in the meantime it'd be nice to conditionally show a button there if
we see a user level vscode config
- we'll add it to the UI when we land the new walkthrough experience,
for now it'll be accessible through the action
- [ ] project-specific settings
- handling translation of `.vscode/settings.json` or `.code-workspace`
settings to `.zed/settings.json` will come in a future PR, along with UI
to prompt the user for those actions when opening a project with local
vscode settings for the first time
- [ ] extension settings
- we probably want to do a best-effort pass of popular extensions like
vim and git lens
- it's also possible to look for installed/enabled extensions with `code
--list-extensions`, but we'd have to maintain some sort of mapping of
those to our settings and/or extensions
- [ ] LSP settings
- these are tricky without access to the json schemas for various
language server extensions. we could probably manage to do translations
for a couple popular languages and avoid solving it in the general case.
- [ ] platform specific settings (`[macos].blah`)
  - this is blocked on #16392 which I'm hoping to address soon
- [ ] language specific settings (`[rust].foo`)
  - totally doable, just haven't gotten to it yet
 
~We may want to put this behind some kind of flag and/or not land it
until some of the above issues are addressed, given that we expect
people to only run this importer once there's an incentive to get it
right the first time. Maybe we land it alongside a keymap importer so
you don't have to go through separate imports for those?~

We are gonna land this as-is, all these unchecked items at the bottom
will be addressed in followup PRs, so maybe don't run the importer for
now if you have a large and complex VsCode settings file you'd like to
import.

Release Notes:

- Added a VSCode settings importer, available via a
`zed::ImportVsCodeSettings` action

---------

Co-authored-by: Mikayla Maki <mikayla@zed.dev>
Co-authored-by: Kirill Bulatov <kirill@zed.dev>
Co-authored-by: Mikayla Maki <mikayla.c.maki@gmail.com>
Co-authored-by: Marshall Bowers <git@maxdeviant.com>
2025-04-23 20:54:09 +00:00

198 lines
6.3 KiB
Rust

mod appearance_settings_controls;
use std::any::TypeId;
use command_palette_hooks::CommandPaletteFilter;
use editor::EditorSettingsControls;
use feature_flags::{FeatureFlag, FeatureFlagViewExt};
use fs::Fs;
use gpui::{
App, AsyncWindowContext, Entity, EventEmitter, FocusHandle, Focusable, Task, actions,
impl_actions,
};
use schemars::JsonSchema;
use serde::Deserialize;
use settings::SettingsStore;
use ui::prelude::*;
use workspace::Workspace;
use workspace::item::{Item, ItemEvent};
use crate::appearance_settings_controls::AppearanceSettingsControls;
pub struct SettingsUiFeatureFlag;
impl FeatureFlag for SettingsUiFeatureFlag {
const NAME: &'static str = "settings-ui";
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Deserialize, JsonSchema)]
pub struct ImportVsCodeSettings {
#[serde(default)]
pub skip_prompt: bool,
}
impl_actions!(zed, [ImportVsCodeSettings]);
actions!(zed, [OpenSettingsEditor]);
pub fn init(cx: &mut App) {
cx.observe_new(|workspace: &mut Workspace, window, cx| {
let Some(window) = window else {
return;
};
workspace.register_action(|workspace, _: &OpenSettingsEditor, window, cx| {
let existing = workspace
.active_pane()
.read(cx)
.items()
.find_map(|item| item.downcast::<SettingsPage>());
if let Some(existing) = existing {
workspace.activate_item(&existing, true, true, window, cx);
} else {
let settings_page = SettingsPage::new(workspace, cx);
workspace.add_item_to_active_pane(Box::new(settings_page), None, true, window, cx)
}
});
workspace.register_action(|_workspace, action: &ImportVsCodeSettings, window, cx| {
let fs = <dyn Fs>::global(cx);
let action = *action;
window
.spawn(cx, async move |cx: &mut AsyncWindowContext| {
let vscode =
match settings::VsCodeSettings::load_user_settings(fs.clone()).await {
Ok(vscode) => vscode,
Err(err) => {
println!(
"Failed to load VsCode settings: {}",
err.context(format!(
"Loading VsCode settings from path: {:?}",
paths::vscode_settings_file()
))
);
let _ = cx.prompt(
gpui::PromptLevel::Info,
"Could not find or load a VsCode settings file",
None,
&["Ok"],
);
return;
}
};
let prompt = if action.skip_prompt {
Task::ready(Some(0))
} else {
let prompt = cx.prompt(
gpui::PromptLevel::Warning,
"Importing settings may overwrite your existing settings",
None,
&["Ok", "Cancel"],
);
cx.spawn(async move |_| prompt.await.ok())
};
if prompt.await != Some(0) {
return;
}
cx.update(|_, cx| {
cx.global::<SettingsStore>()
.import_vscode_settings(fs, vscode);
log::info!("Imported settings from VsCode");
})
.ok();
})
.detach();
});
let settings_ui_actions = [TypeId::of::<OpenSettingsEditor>()];
CommandPaletteFilter::update_global(cx, |filter, _cx| {
filter.hide_action_types(&settings_ui_actions);
});
cx.observe_flag::<SettingsUiFeatureFlag, _>(
window,
move |is_enabled, _workspace, _, cx| {
if is_enabled {
CommandPaletteFilter::update_global(cx, |filter, _cx| {
filter.show_action_types(settings_ui_actions.iter());
});
} else {
CommandPaletteFilter::update_global(cx, |filter, _cx| {
filter.hide_action_types(&settings_ui_actions);
});
}
},
)
.detach();
})
.detach();
}
pub struct SettingsPage {
focus_handle: FocusHandle,
}
impl SettingsPage {
pub fn new(_workspace: &Workspace, cx: &mut Context<Workspace>) -> Entity<Self> {
cx.new(|cx| Self {
focus_handle: cx.focus_handle(),
})
}
}
impl EventEmitter<ItemEvent> for SettingsPage {}
impl Focusable for SettingsPage {
fn focus_handle(&self, _cx: &App) -> FocusHandle {
self.focus_handle.clone()
}
}
impl Item for SettingsPage {
type Event = ItemEvent;
fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
Some(Icon::new(IconName::Settings))
}
fn tab_content_text(&self, _window: &Window, _cx: &App) -> Option<SharedString> {
Some("Settings".into())
}
fn show_toolbar(&self) -> bool {
false
}
fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
f(*event)
}
}
impl Render for SettingsPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.p_4()
.size_full()
.gap_4()
.child(Label::new("Settings").size(LabelSize::Large))
.child(
v_flex().gap_1().child(Label::new("Appearance")).child(
v_flex()
.elevation_2(cx)
.child(AppearanceSettingsControls::new()),
),
)
.child(
v_flex().gap_1().child(Label::new("Editor")).child(
v_flex()
.elevation_2(cx)
.child(EditorSettingsControls::new()),
),
)
}
}