Visual Studio Code, rebuilt in Rust
Rust
//! contrib/userDataProfile/browser/userDataProfile.ts and userDataProfileActions.ts with the window side of
//! userDataProfileManagement.ts: the Profiles commands and menus, the `currentProfile` and `hasProfiles` context
//! keys, and `changeCurrentProfile`, which restarts the extension host on the new profile's files (the port has no
//! window reload).
use std::sync::{Arc, Mutex};
use gpui::{App, BorrowAppContext, Context, Window};
use serde_json::{Value, json};
use storage::Storage;
use storage::profiles::{Profile, Profiles};
use storage::state::FileStorage;
use super::Workbench;
use crate::command_palette::{MenuItem as PaletteItem, locale_compare};
use crate::commands::{Outcome, Registration};
use crate::contextkey::Expr;
use crate::menus::{Entry, MenuId, MenuItem, Toggled};
use crate::quick_input::{Entry as PickEntry, Item, Kind, QuickInput};
use crate::user_data_profile::{ProfileState, UserDataProfilesService, user_files};
use crate::{CliProfile, WindowRequest};
/// userDataProfile.ts `registerHelpAction`.
const PROFILES_HELP_URL: &str = "https://aka.ms/vscode-profiles-help";
#[derive(Default)]
pub struct UserDataProfiles {
pub state: Option<ProfileState>,
/// `registerProfilesActions`: the `profileEntry` and `openProfile` command of each profile, by command id.
registrations: Vec<(String, Registration)>,
pub editor: super::profiles_editor_view::ProfilesEditor,
/// A reload keeps the window's transient profile for the window that replaces it.
pub(super) reloading: bool,
}
impl Workbench {
pub(super) fn register_user_data_profile_commands(&mut self) {
self.commands.register("workbench.profiles.actions.switchProfile", |workbench, _, window, cx| workbench.show_switch_profile(window, cx));
self.commands.register("workbench.profiles.actions.deleteProfile", |workbench, _, window, cx| workbench.show_delete_profiles(window, cx));
self.commands.register("workbench.profiles.actions.newWindowWithProfile", |workbench, _, window, cx| workbench.show_new_window_with_profile(window, cx));
self.commands.register("workbench.profiles.actions.createTemporaryProfile", |_, _, _, cx| {
open_profile_window(CliProfile { temp: true, ..CliProfile::default() }, cx);
Outcome::done()
});
self.commands.register("workbench.profiles.actions.cleanupProfiles", |workbench, _, _, cx| {
if workbench.user_data_profiles.state.is_some() {
workbench.edit_profiles(cx, |profiles, storage| profiles.clean_up(storage));
}
Outcome::done()
});
self.commands.register("workbench.profiles.actions.resetWorkspaces", |workbench, _, _, cx| {
if workbench.user_data_profiles.state.is_some() {
workbench.edit_profiles(cx, |profiles, storage| profiles.reset_workspaces(storage));
}
Outcome::done()
});
self.commands.register("workbench.profiles.actions.help", |workbench, _, window, cx| {
let target = super::opener::Target::Text(PROFILES_HELP_URL.into());
drop(workbench.open_link(target, Default::default(), window, cx));
Outcome::done()
});
}
/// Takes the profile main.rs resolved for the window and publishes the app's profiles to the context keys, menus
/// and commands.
pub fn set_user_data_profiles(&mut self, state: ProfileState, cx: &mut Context<Self>) {
let window = cx.entity_id();
cx.update_global(|service: &mut UserDataProfilesService, _| service.set_window_profile(window, Some(&state.current)));
// userDataProfilesHandler.ts `unsetProfileForWorkspace` on close: a transient profile no other window runs goes.
cx.on_release(move |workbench, cx| {
let reloading = workbench.user_data_profiles.reloading;
let removed = cx.update_global(|service: &mut UserDataProfilesService, _| {
service.set_window_profile(window, None);
!reloading && service.clean_up_transient_profiles()
});
if removed {
cx.defer(did_change_profiles);
}
})
.detach();
self.user_data_profiles.state = Some(state);
self.user_data_profiles.editor.name_focus = Some(cx.focus_handle());
self.profiles_changed(cx);
}
/// A change of the app's profiles, then `onDidChangeProfiles` in every window.
pub(crate) fn edit_profiles<T>(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut Profiles, &mut FileStorage) -> T) -> T {
let result = cx.update_global(|service: &mut UserDataProfilesService, _| service.edit(change));
cx.defer(did_change_profiles);
result
}
/// userDataProfileManagement.ts `onDidChangeProfiles`: a window whose profile another window removed changes to
/// its workspace's or the default one, an updated profile replaces the current one.
pub(super) fn on_did_change_profiles(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(state) = &self.user_data_profiles.state else { return };
let profiles = &cx.global::<UserDataProfilesService>().profiles;
let updated = profiles.profiles().into_iter().find(|profile| profile.id == state.current.id);
match updated {
Some(profile) if profile.use_default_flags != state.current.use_default_flags => self.change_current_profile(profile, window, cx),
Some(profile) => self.user_data_profiles.state.as_mut().expect("checked above").current = profile,
None => {
let next = state.workspace.as_ref().and_then(|workspace| profiles.profile_for_workspace(workspace)).unwrap_or_else(|| profiles.default_profile()).clone();
self.change_current_profile(next, window, cx);
}
}
self.forget_removed_preview_profile(cx);
self.profiles_changed(cx);
}
/// globalCompositeBar.ts `GlobalActivityActionViewItem`: the current profile's icon, the settings gear by default.
pub(super) fn manage_activity_icon(&self) -> &str {
let icon = self.user_data_profiles.state.as_ref().and_then(|state| state.current.icon.as_deref());
super::icon_select_box::profile_icon_file(icon)
}
/// `computeTitle`: "Manage" with the update badge's description, or "Manage {0} (Profile)" in a profile that is
/// not the default one.
pub(super) fn manage_activity_title(&self) -> String {
match (self.user_data_profiles.state.as_ref().map(|state| &state.current).filter(|current| !current.is_default), self.update_badge()) {
(Some(current), _) => format!("Manage {} (Profile)", current.name),
(None, Some((_, description))) => format!("Manage - {description}"),
(None, None) => "Manage".into(),
}
}
/// The global activity's badge (the update's), else the profile badge.
pub(super) fn manage_activity_badge(&self) -> Option<gpui::Div> {
match self.update_badge() {
Some((badge, _)) => super::activity::visible_badge(&[badge]).map(|content| self.activity_badge(content)),
None => self.profile_badge(),
}
}
/// `updateProfileBadge`: the first two letters of a profile that is not the default one and has no icon of its
/// own, as activityaction.css `.profile-text-overlay` draws them with the modern UI's 16px top.
pub(super) fn profile_badge(&self) -> Option<gpui::Div> {
use gpui::{ParentElement, Styled, div, px};
let current = &self.user_data_profiles.state.as_ref()?.current;
if current.is_default || current.icon.as_deref().is_some_and(|icon| icon != super::icon_select_box::DEFAULT_ICON) {
return None;
}
let letters: String = current.name.chars().take(2).collect::<String>().to_uppercase();
let badge = div()
.absolute()
.top(px(16.))
.right(px(6.))
.px(px(3.))
.py(px(2.))
.rounded(px(7.))
.border_2()
.border_color(self.color("activityBar.background"))
.bg(self.color("profileBadge.background"))
.text_color(self.color("profileBadge.foreground"))
.text_size(px(9.))
.line_height(px(10.))
.font_weight(gpui::FontWeight::SEMIBOLD)
.child(letters);
Some(badge)
}
/// `onDidChangeProfiles`: the context keys, the Profiles menus and the commands of each profile.
pub(super) fn profiles_changed(&mut self, cx: &mut Context<Self>) {
let Some(state) = &self.user_data_profiles.state else { return };
let profiles: Vec<Profile> = cx.global::<UserDataProfilesService>().profiles.profiles();
let current = state.current.clone();
self.context_keys.insert("currentProfile".into(), json!(current.id));
self.context_keys.insert("hasProfiles".into(), json!(profiles.len() > 1));
for (id, registration) in std::mem::take(&mut self.user_data_profiles.registrations) {
self.commands.dispose(&id, registration);
}
let mut registrations = Vec::new();
for profile in &profiles {
let entry_id = format!("workbench.profiles.actions.profileEntry.{}", profile.id);
let switch_to = profile.clone();
let registration = self.commands.register(entry_id.clone(), move |workbench, _, window, cx| {
workbench.switch_profile(&switch_to, window, cx);
Outcome::done()
});
registrations.push((entry_id, registration));
let open_id = open_profile_command(&profile.name);
let name = profile.name.clone();
let registration = self.commands.register(open_id.clone(), move |_, _, _, cx| {
open_profile_window(CliProfile { name: Some(name.clone()), ..CliProfile::default() }, cx);
Outcome::done()
});
registrations.push((open_id, registration));
}
self.user_data_profiles.registrations = registrations;
self.menus.retain(|item| !matches!(item.menu, MenuId::ProfilesMenu | MenuId::OpenProfileMenu) && !is_profiles_submenu(item));
self.menus.extend(profile_menus(&profiles, ¤t));
let palette = std::mem::take(&mut self.quick_access.menu)
.into_iter()
.filter(|item| !item.id.starts_with("workbench.action.openProfile.") && item.id != IMPORT_SETTINGS_COMMAND)
.chain(open_profile_palette_items(&profiles))
.chain([import_settings_palette_item()])
.collect();
self.set_command_palette_menu(palette);
cx.notify();
}
/// `SwitchProfileAction`: the profiles by name, the current one checked.
fn show_switch_profile(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
let Some(state) = &self.user_data_profiles.state else { return Outcome::done() };
let mut profiles = cx.global::<UserDataProfilesService>().profiles.profiles();
profiles.sort_by(|a, b| locale_compare(&a.name, &b.name));
let current = state.current.id.clone();
let mut input = QuickInput::new(0, Kind::QuickPick);
input.placeholder = Some("Select Profile".into());
let items = profiles.iter().enumerate().map(|(handle, profile)| {
let label = if profile.id == current { format!("$(check) {}", profile.name) } else { profile.name.clone() };
PickEntry::Item(Item { handle: handle as i64, label, pickable: true, ..Item::default() })
});
input.set_items(items.collect());
let picked = self.choose(input, window, cx);
cx.spawn_in(window, async move |workbench, cx| {
let Ok(Ok(Value::Number(handle))) = picked.await else { return };
let profile = profiles[handle.as_u64().expect("a handle") as usize].clone();
let _ = workbench.update_in(cx, |workbench, window, cx| workbench.switch_profile(&profile, window, cx));
})
.detach();
Outcome::done()
}
/// `DeleteProfileAction`: the profiles but the default, the current one described as such.
fn show_delete_profiles(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
let Some(state) = &self.user_data_profiles.state else { return Outcome::done() };
let profiles: Vec<Profile> = cx.global::<UserDataProfilesService>().profiles.profiles().into_iter().filter(|profile| !profile.is_default).collect();
if profiles.is_empty() {
return Outcome::done();
}
let current = state.current.id.clone();
let mut input = QuickInput::new(0, Kind::QuickPick);
input.title = Some("Delete Profile...".into());
input.placeholder = Some("Select Profiles to Delete".into());
input.can_select_many = true;
let items = profiles.iter().enumerate().map(|(handle, profile)| {
let description = (profile.id == current).then(|| "Current".to_owned());
PickEntry::Item(Item { handle: handle as i64, label: profile.name.clone(), description, pickable: true, ..Item::default() })
});
input.set_items(items.collect());
let picked = self.choose(input, window, cx);
cx.spawn_in(window, async move |workbench, cx| {
let Ok(Ok(Value::Array(handles))) = picked.await else { return };
let picked: Vec<Profile> = handles.iter().filter_map(Value::as_u64).map(|handle| profiles[handle as usize].clone()).collect();
let _ = workbench.update_in(cx, |workbench, window, cx| {
for profile in picked {
workbench.remove_profile(&profile, window, cx);
}
});
})
.detach();
Outcome::done()
}
/// `NewWindowWithProfileAction`: the profiles, each opening a window with it.
fn show_new_window_with_profile(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
if self.user_data_profiles.state.is_none() {
return Outcome::done();
}
let profiles = cx.global::<UserDataProfilesService>().profiles.profiles();
let mut input = QuickInput::new(0, Kind::QuickPick);
input.title = Some("New Window with Profile".into());
input.placeholder = Some("Select Profile".into());
let items = profiles.iter().enumerate().map(|(handle, profile)| PickEntry::Item(Item { handle: handle as i64, label: profile.name.clone(), pickable: true, ..Item::default() }));
input.set_items(items.collect());
let picked = self.choose(input, window, cx);
cx.spawn_in(window, async move |workbench, cx| {
let Ok(Ok(Value::Number(handle))) = picked.await else { return };
let name = profiles[handle.as_u64().expect("a handle") as usize].name.clone();
let _ = workbench.update(cx, |_, cx| open_profile_window(CliProfile { name: Some(name), ..CliProfile::default() }, cx));
})
.detach();
Outcome::done()
}
/// userDataProfileManagement.ts `switchProfile`: the workspace is associated with the profile, then the window
/// changes to it.
pub(crate) fn switch_profile(&mut self, profile: &Profile, window: &mut Window, cx: &mut Context<Self>) {
let Some(state) = &self.user_data_profiles.state else { return };
if state.current.id == profile.id {
return;
}
if let Some(workspace) = state.workspace.clone() {
if let Err(error) = self.edit_profiles(cx, |profiles, storage| profiles.set_profile_for_workspace(&workspace, &profile.id, storage)) {
self.notify_error(error);
return;
}
}
self.change_current_profile(profile.clone(), window, cx);
self.profiles_changed(cx);
}
/// `removeProfile`; removing the current profile changes the window to the workspace's or the default one.
pub(crate) fn remove_profile(&mut self, profile: &Profile, window: &mut Window, cx: &mut Context<Self>) {
if self.user_data_profiles.state.is_none() {
return;
}
if let Err(error) = self.edit_profiles(cx, |profiles, storage| profiles.remove_profile(&profile.id, storage)) {
self.notify_error(error);
return;
}
self.on_did_change_profiles(window, cx);
}
/// `changeCurrentProfile`: the extension host stops first when the profile or what it shares with the default one
/// changed; a veto keeps the current profile and gives the workspace back to it.
pub(crate) fn change_current_profile(&mut self, profile: Profile, window: &mut Window, cx: &mut Context<Self>) {
let Some(state) = &self.user_data_profiles.state else { return };
if state.current.id == profile.id && state.current.use_default_flags == profile.use_default_flags {
return self.update_current_profile(profile, false, window, cx);
}
let stopped = self.stop_extension_hosts("Switching to a profile", window, cx);
cx.spawn_in(window, async move |workbench, cx| {
let stopped = stopped.await;
let _ = workbench.update_in(cx, |workbench, window, cx| {
if stopped {
workbench.update_current_profile(profile, true, window, cx);
workbench.profiles_changed(cx);
return;
}
let Some(state) = &workbench.user_data_profiles.state else { return };
let (workspace, current) = (state.workspace.clone(), state.current.id.clone());
let exists = cx.global::<UserDataProfilesService>().profiles.profiles().iter().any(|profile| profile.id == current);
if let Some(workspace) = workspace.filter(|_| exists)
&& let Err(error) = workbench.edit_profiles(cx, |profiles, storage| profiles.set_profile_for_workspace(&workspace, ¤t, storage))
{
workbench.notify_error(error);
}
});
})
.detach();
}
/// `updateCurrentProfile`: the configuration, keybindings, storage and user extensions move to the profile's
/// files; `restart` starts the stopped extension host again.
fn update_current_profile(&mut self, profile: Profile, restart: bool, window: &mut Window, cx: &mut Context<Self>) {
let Some(state) = self.user_data_profiles.state.as_mut() else { return };
let previous = std::mem::replace(&mut state.current, profile.clone());
let window_id = cx.entity_id();
let removed = cx.update_global(|service: &mut UserDataProfilesService, _| {
service.set_window_profile(window_id, Some(&profile));
previous.is_transient && service.clean_up_transient_profiles()
});
if removed {
cx.defer(did_change_profiles);
}
let files = user_files(&profile, cx.global::<UserDataProfilesService>().profiles.default_profile());
let before = self.model_creation_options();
let change = self.settings.lock().unwrap().set_profile(files);
self.sync_settings_watches();
self.keybindings.user_file = Some(profile.keybindings_resource.clone());
self.watch_user_keybindings();
self.set_user_keybindings(crate::keybindings::user_keybindings(&profile.keybindings_resource));
if let Err(error) = std::fs::create_dir_all(&profile.global_storage_home) {
self.notify_error(format!("{}: {error}", profile.global_storage_home.display()));
}
let application = self.application_storage.clone();
let storage = match profile.is_default {
true => application.clone(),
false => Arc::new(Mutex::new(Storage::open(&profile.global_storage_home.join("state.vscdb")))),
};
self.restore_profile_state(storage, application);
if let Some(user) = self.extensions_viewlet.user.as_mut() {
user.extensions_file = profile.extensions_resource.clone();
}
self.watch_profile_extensions();
self.rescan_installed_extensions();
self.configuration_changed(&change, before, cx);
if restart {
self.start_extension_hosts(window, cx);
}
self.install_template_extensions(window, cx);
}
/// `ExtensionsResource.apply`: the current profile's template extensions it does not have yet, with one trust
/// dialog and an error naming the ones that did not install.
pub(crate) fn install_template_extensions(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(profile_id) = self.user_data_profiles.state.as_ref().map(|state| state.current.id.clone()) else { return };
let pending = cx.update_global(|service: &mut UserDataProfilesService, _| service.pending_installs.remove(&profile_id)).unwrap_or_default();
let installed: Vec<String> = self.extensions.iter().map(|extension| extension.id.to_lowercase()).collect();
let missing: Vec<String> = pending.into_iter().map(|id| id.to_lowercase()).filter(|id| !installed.contains(id)).collect();
if missing.is_empty() {
return;
}
let failed = self.install_gallery_extensions(missing, window, cx);
cx.spawn(async move |workbench, cx| {
let failed = failed.await;
if failed.is_empty() {
return;
}
let lines: Vec<String> = failed.iter().map(|(id, reason)| format!("{id}: {reason}")).collect();
let message = format!("Extensions of the profile that were not installed:\n{}", lines.join("\n"));
let _ = workbench.update(cx, |workbench, _| workbench.notify_error(message));
})
.detach();
}
}
/// `hostService.openWindow({ forceProfile, forceTempProfile })`: an empty window of this process on the profile.
pub(super) fn open_profile_window(profile: CliProfile, cx: &mut App) {
let request = WindowRequest { profile, ..WindowRequest::default() };
#[cfg(not(test))]
cx.defer(move |cx| crate::open_window_or_log(request, cx));
// main.rs `open_window` needs the app's extensions and an extension host; tests open a bare workbench window.
#[cfg(test)]
cx.defer(move |cx| {
tests::open_window(request, cx);
});
}
/// `onDidChangeProfiles` in every window.
fn did_change_profiles(cx: &mut App) {
for handle in cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>()) {
let _ = handle.update(cx, |workbench, window, cx| workbench.on_did_change_profiles(window, cx));
}
}
/// `registerNewWindowAction`'s id; upstream's `name.replace('/\s+/', '_')` replaces a literal string, so the name
/// stays as it is.
fn open_profile_command(name: &str) -> String {
format!("workbench.action.openProfile.{name}")
}
fn is_profiles_submenu(item: &MenuItem) -> bool {
matches!(item.entry, Entry::Submenu { submenu: MenuId::ProfilesMenu | MenuId::OpenProfileMenu, .. })
}
/// `registerProfileSubMenu`, `registerManageProfilesAction`, `registerProfileEntryAction`,
/// `registerOpenProfileSubMenu` and `registerNewWindowAction`.
fn profile_menus(profiles: &[Profile], current: &Profile) -> Vec<MenuItem> {
let command = |id: &str| Entry::Command { id: id.into(), precondition: None, toggled: None, alt: None };
let item = |menu, entry, title: &str, group: &str, order, when: Option<&str>| MenuItem { menu, entry, title: title.into(), group: group.into(), order, when: when.and_then(Expr::deserialize) };
let submenu = |submenu| Entry::Submenu { submenu, toggled: None };
let title = format!("Profile ({})", current.name);
let mut items = vec![
item(MenuId::GlobalActivity, submenu(MenuId::ProfilesMenu), &title, "2_configuration", 1., Some("hasProfiles")),
item(MenuId::MenubarPreferencesMenu, submenu(MenuId::ProfilesMenu), &title, "2_configuration", 1., Some("hasProfiles && !isSessionsWindow")),
item(MenuId::GlobalActivity, command("workbench.profiles.actions.manageProfiles"), "Profiles", "2_configuration", 1., Some("!hasProfiles")),
item(MenuId::MenubarPreferencesMenu, command("workbench.profiles.actions.manageProfiles"), "&&Profiles", "2_configuration", 1., Some("!hasProfiles && !isSessionsWindow")),
item(MenuId::ProfilesMenu, command("workbench.profiles.actions.manageProfiles"), "Profiles", "1_manage", 1., None),
item(MenuId::MenubarFileMenu, submenu(MenuId::OpenProfileMenu), "New Window with Profile", "1_new", 4., None),
item(MenuId::OpenProfileMenu, command("workbench.profiles.actions.createProfile"), "New Profile...", "1_manage_profiles", 1., None),
// userDataProfileActions.ts `ExportProfileAction` under File > Share.
item(MenuId::MenubarShare, command("workbench.profiles.actions.exportProfile"), &format!("Export Profile ({})...", current.name), "", 0., None),
];
for profile in profiles {
let toggled = Toggled::when(Expr::deserialize(&format!("currentProfile == '{}'", profile.id)));
let entry = Entry::Command { id: format!("workbench.profiles.actions.profileEntry.{}", profile.id), precondition: None, toggled, alt: None };
items.push(item(MenuId::ProfilesMenu, entry, &profile.name, "0_profiles", 0., None));
let entry = command(&open_profile_command(&profile.name));
items.push(item(MenuId::OpenProfileMenu, entry, &profile.name, "0_profiles", 0., Some("hasProfiles")));
}
items
}
const IMPORT_SETTINGS_COMMAND: &str = "workbench.action.importSettings";
/// The settings import (port feature, Artur) in the Command Palette.
fn import_settings_palette_item() -> PaletteItem {
PaletteItem { id: IMPORT_SETTINGS_COMMAND.into(), title: "Import from VS Code, Cursor or VSCodium...".into(), category: Some("Preferences".into()), description: None, when: None, precondition: None, source: None }
}
/// `registerNewWindowAction`'s Command Palette item: "Open {name} Profile".
fn open_profile_palette_items(profiles: &[Profile]) -> Vec<PaletteItem> {
let item = |profile: &Profile| PaletteItem {
id: open_profile_command(&profile.name),
title: format!("Open {} Profile", profile.name),
category: Some("Profiles".into()),
description: None,
when: None,
precondition: Expr::deserialize("hasProfiles"),
source: None,
};
profiles.iter().map(item).collect()
}
#[cfg(test)]
pub(super) mod tests;