Visual Studio Code, rebuilt in Rust
Rust
//! The app's profiles (userDataProfile.ts `UserDataProfilesMainService`: `storage.json`'s and the transient ones,
//! shared by every window), the one windowsMainService.ts `resolveProfileForBrowserWindow` picks for a window, and
//! the user files the configuration service reads from it.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use config::service::UserFiles;
use config::workspace::Workspace;
use storage::profiles::{Options, Paths, Profile, Profiles, WorkspaceId};
use storage::state::FileStorage;
/// The app-wide profiles service, one for all windows of the process.
pub struct UserDataProfilesService {
/// `User/globalStorage/storage.json`, opened again for each change so the telemetry ids the extension host
/// sessions write into the same file are kept.
state_file: PathBuf,
pub profiles: Profiles,
/// The profile each open window runs, by its workbench: what keeps a transient profile alive.
windows: HashMap<gpui::EntityId, String>,
/// The gallery extensions of an applied template by profile id, installed by the window that runs the profile.
pub pending_installs: HashMap<String, Vec<String>>,
}
impl gpui::Global for UserDataProfilesService {}
/// The window's side: `userDataProfileService.currentProfile` and the workspace its associations use.
pub struct ProfileState {
pub current: Profile,
/// `None` for an empty window.
pub workspace: Option<WorkspaceId>,
}
impl UserDataProfilesService {
pub fn load(user_data: &Path, extensions_dir: &Path) -> UserDataProfilesService {
let user_home = user_data.join("User");
let state_file = user_home.join("globalStorage/storage.json");
if let Err(error) = std::fs::create_dir_all(user_home.join("globalStorage")) {
eprintln!("[profiles] {}: {error}", user_home.display());
}
let paths = Paths { user_home, cache_home: user_data.to_path_buf(), extensions_dir: Some(extensions_dir.to_path_buf()) };
let profiles = Profiles::load(&FileStorage::open(&state_file), &paths);
UserDataProfilesService { state_file, profiles, windows: HashMap::new(), pending_installs: HashMap::new() }
}
/// `--profile <name>` opens (or creates) that profile, `--profile-temp` a new transient one, else the profile
/// associated with the workspace or the default. The choice is associated with the workspace unless the window
/// develops an extension.
pub fn resolve(&mut self, workspace: Option<&Workspace>, force_profile: Option<&str>, force_temp: bool, extension_development: bool) -> ProfileState {
let mut state = FileStorage::open(&self.state_file);
let user_home = self.profiles.default_profile().location.clone();
let profiles = &mut self.profiles;
let workspace = workspace.map(workspace_id);
let forced = match (force_profile, force_temp) {
(Some(name), _) => match profiles.profiles().into_iter().find(|profile| profile.name == name) {
Some(profile) => Some(Ok(profile)),
None => Some(profiles.create_named_profile(name, Options::default(), None, &mut state).map(|(profile, _)| profile)),
},
(None, true) => Some(profiles.create_transient_profile(None, &mut state).map(|(profile, _)| profile)),
(None, false) => None,
};
let current = match forced {
Some(Ok(profile)) => profile,
Some(Err(error)) => {
eprintln!("[profiles] {error}");
profiles.default_profile().clone()
}
None => {
// windowsMainService.ts: a window with no associated profile opens in `window.newWindowProfile`.
let new_window = new_window_profile(&user_home).and_then(|name| profiles.profiles().into_iter().find(|profile| profile.name == name));
let associated = workspace.as_ref().and_then(|workspace| profiles.profile_for_workspace(workspace)).cloned();
associated.or(new_window).unwrap_or_else(|| profiles.default_profile().clone())
}
};
if let (Some(workspace), false) = (&workspace, extension_development)
&& let Err(error) = profiles.set_profile_for_workspace(workspace, ¤t.id, &mut state)
{
eprintln!("[profiles] {error}");
}
ProfileState { current, workspace }
}
/// Runs a change of the profiles against `storage.json` as it is on disk now.
pub fn edit<T>(&mut self, change: impl FnOnce(&mut Profiles, &mut FileStorage) -> T) -> T {
let mut state = FileStorage::open(&self.state_file);
change(&mut self.profiles, &mut state)
}
/// The window runs `profile`, or closed with `None`.
pub fn set_window_profile(&mut self, window: gpui::EntityId, profile: Option<&Profile>) {
match profile {
Some(profile) => self.windows.insert(window, profile.id.clone()),
None => self.windows.remove(&window),
};
}
/// `cleanUpTransientProfiles`: removes the transient profiles no open window runs. Upstream asks the workspace
/// and empty window associations; the port's empty windows have no id to associate, so the windows stand for them.
/// Answers whether it removed one.
pub fn clean_up_transient_profiles(&mut self) -> bool {
let unused: Vec<String> = self.profiles.profiles().into_iter().filter(|profile| profile.is_transient && !self.windows.values().any(|id| *id == profile.id)).map(|profile| profile.id).collect();
for id in &unused {
if let Err(error) = self.edit(|profiles, storage| profiles.remove_profile(id, storage)) {
eprintln!("[profiles] {error}");
}
}
!unused.is_empty()
}
}
/// The configuration files of a profile; a profile with its own settings also reads the default profile's
/// settings.json for the settings applied to all profiles.
pub fn user_files(profile: &Profile, default: &Profile) -> UserFiles {
let shares_settings = profile.is_default || profile.settings_resource == default.settings_resource;
UserFiles {
settings: profile.settings_resource.clone(),
tasks: profile.tasks_resource.clone(),
mcp: profile.mcp_resource.clone(),
default_settings: (!shares_settings).then(|| default.settings_resource.clone()),
}
}
/// `window.newWindowProfile` of the default profile's settings.json (an application setting).
fn new_window_profile(user_home: &Path) -> Option<String> {
let content = std::fs::read_to_string(user_home.join("settings.json")).ok()?;
let options = config::json::ParseOptions { allow_trailing_comma: true, allow_empty_content: true, ..Default::default() };
let settings = config::json::parse(&content, &mut Vec::new(), options)?;
settings[crate::workbench::NEW_WINDOW_PROFILE_SETTING].as_str().map(str::to_owned)
}
/// `toWorkspaceIdentifier(workspace).uri.toString()`: the workspace file, else the folder.
pub fn workspace_id(workspace: &Workspace) -> WorkspaceId {
let path = workspace.file.as_deref().unwrap_or_else(|| &workspace.folders[0].path);
WorkspaceId::Uri(crate::editor_history::file_uri_string(path))
}
#[cfg(test)]
mod tests;