Skip to content

Visual Studio Code, rebuilt in Rust

Rust

fix(settings-import): import the layout from VS Code's global state

rokartur08647aeba622
diff --git a/native/crates/app/src/profile_template.rs b/native/crates/app/src/profile_template.rs
index dc8439af674..905c1cebb09 100644
--- a/native/crates/app/src/profile_template.rs
+++ b/native/crates/app/src/profile_template.rs
@@ -117,20 +117,24 @@ pub fn apply_template(template: &Value, profile: &Profile, registry: &Registry,
}
}
if let Some(content) = resource("globalState") {
- let storage = content["storage"].as_object().cloned().unwrap_or_default();
- let mut targets: Map<String, Value> = global_state.get(TARGET_KEY).and_then(|targets| serde_json::from_str(targets).ok()).unwrap_or_default();
- for (key, value) in &storage {
- global_state.set(key, value.as_str().map_or_else(|| value.to_string(), str::to_owned));
- targets.insert(key.clone(), json!(0));
- }
- if !storage.is_empty() {
- global_state.set(TARGET_KEY, Value::Object(targets).to_string());
- }
+ store_user_state(global_state, &content["storage"].as_object().cloned().unwrap_or_default());
}
let extensions = template["extensions"].as_str().map(|content| serde_json::from_str::<Vec<Value>>(content).unwrap_or_default());
Ok(extensions.unwrap_or_default())
}
+/// `GlobalStateResource.writeGlobalState`: each entry stored for the user (`StorageTarget.USER`).
+pub fn store_user_state(global_state: &mut Storage, storage: &Map<String, Value>) {
+ let mut targets: Map<String, Value> = global_state.get(TARGET_KEY).and_then(|targets| serde_json::from_str(targets).ok()).unwrap_or_default();
+ for (key, value) in storage {
+ global_state.set(key, value.as_str().map_or_else(|| value.to_string(), str::to_owned));
+ targets.insert(key.clone(), json!(0));
+ }
+ if !storage.is_empty() {
+ global_state.set(TARGET_KEY, Value::Object(targets).to_string());
+ }
+}
+
/// `SettingsResource.getIgnoredSettings`: machine scoped settings stay with the machine.
fn ignored_settings(registry: &Registry) -> Vec<String> {
let machine = |key: &&String| registry.property(key).is_some_and(|property| matches!(property.scope, Scope::Machine | Scope::ApplicationMachine | Scope::MachineOverridable));
diff --git a/native/crates/app/src/settings_import.rs b/native/crates/app/src/settings_import.rs
index cb2172a1d6d..3bfeb36e852 100644
--- a/native/crates/app/src/settings_import.rs
+++ b/native/crates/app/src/settings_import.rs
@@ -49,6 +49,8 @@ pub struct Import {
pub extensions: Vec<String>,
/// The ones of `extensions` disabled there.
pub disabled_extensions: Vec<String>,
+ /// The global storage entries a profile export carries as its UI state (view locations, pinned and hidden views).
+ pub ui_state: Map<String, Value>,
}
/// Setting prefixes of removed features.
@@ -128,9 +130,29 @@ pub fn read(source: &Source) -> Import {
let ids: Vec<String> = disabled.iter().filter_map(|identifier| identifier["id"].as_str().map(str::to_lowercase)).collect();
import.disabled_extensions = import.extensions.iter().filter(|id| ids.contains(id)).cloned().collect();
}
+ import.ui_state = ui_state(&source.user_dir.join("globalStorage/state.vscdb"));
import
}
+/// The layout part of globalStateResource.ts `getGlobalState` (the keys stored with `StorageTarget.USER`): view
+/// locations, pinned and hidden views. Its other keys, such as `extensions.trustedPublishers` or a sign-in's account
+/// access, would skip the trust and sign-in this import leaves to the user.
+fn ui_state(database: &Path) -> Map<String, Value> {
+ const LAYOUT_KEYS: [&str; 6] = ["views.customizations", "workbench.activity.pinnedViewlets2", "workbench.auxiliarybar.pinnedPanels", "workbench.panel.pinnedPanels", "workbench.panel.alignment", "workbench.statusbar.hidden"];
+ let targets = storage::read_item(database, "__$__targetStorageMarker").and_then(|targets| serde_json::from_str::<Map<String, Value>>(&targets).ok());
+ let mut state = Map::new();
+ for (key, target) in targets.unwrap_or_default() {
+ let layout = LAYOUT_KEYS.contains(&key.as_str()) || key.ends_with(".hidden");
+ if target != 0 || !layout || is_removed_setting(&key) {
+ continue;
+ }
+ if let Some(value) = storage::read_item(database, &key) {
+ state.insert(key, Value::String(value));
+ }
+ }
+ state
+}
+
/// The ids of `extensions.json`, else of the folder names (`<publisher>.<name>-<version>`).
fn extension_ids(folder: &Path) -> Vec<String> {
let mut ids: Vec<String> = match parse(&folder.join("extensions.json")) {
diff --git a/native/crates/app/src/workbench/settings_import.rs b/native/crates/app/src/workbench/settings_import.rs
index 44c5d10caf0..90bd7f5bce2 100644
--- a/native/crates/app/src/workbench/settings_import.rs
+++ b/native/crates/app/src/workbench/settings_import.rs
@@ -72,6 +72,7 @@ impl Workbench {
("Keyboard Shortcuts", import.keybindings.len()),
("Snippets", import.snippets.len()),
("Extensions", import.extensions.len()),
+ ("UI State", import.ui_state.len()),
];
let mut input = QuickInput::new(0, Kind::QuickPick);
input.title = Some(format!("Import from {}", source.name));
@@ -99,6 +100,7 @@ impl Workbench {
keybindings_text: import.keybindings_text,
extensions: if chosen.contains(&3) { import.extensions } else { Vec::new() },
disabled_extensions: if chosen.contains(&3) { import.disabled_extensions } else { Vec::new() },
+ ui_state: if chosen.contains(&4) { import.ui_state } else { Default::default() },
};
let _ = workbench.update_in(cx, |workbench, window, cx| workbench.write_settings_import(&source, import, window, cx));
})
@@ -116,6 +118,7 @@ impl Workbench {
Err(error) => return self.notify_error(error),
};
self.reload_changed_settings_files(cx);
+ crate::profile_template::store_user_state(&mut self.profile_storage.lock().unwrap(), &import.ui_state);
let installed: Vec<String> = self.extensions.iter().map(|extension| extension.id.to_lowercase()).collect();
let missing: Vec<String> = import.extensions.into_iter().filter(|id| !installed.contains(id)).collect();
// extensionsResource.ts: an extension disabled there is disabled here before it is installed and started.
@@ -128,10 +131,11 @@ impl Workbench {
}
}
let message = format!(
- "Imported from {name}: {} settings, {} keyboard shortcuts, {} snippet files; installing {} extensions from Open VSX, else from {name}'s extensions folder.",
+ "Imported from {name}: {} settings, {} keyboard shortcuts, {} snippet files, {} UI state entries; installing {} extensions from Open VSX, else from {name}'s extensions folder.",
written.settings,
written.keybindings,
written.snippets,
+ import.ui_state.len(),
missing.len()
);
drop(self.prompt_notification(Severity::Info, message, &[]));
@@ -182,7 +186,9 @@ pub(super) mod tests {
use crate::host_sync::HostSync;
use crate::languages::Languages;
- /// Enter on the contents pick imports every part, as they all start checked.
+ /// Enter on the contents pick imports every part, as they all start checked. The UI state is what a VS Code profile
+ /// export carries (globalStateResource.ts: the `StorageTarget.USER` keys), so Source Control moved to the secondary
+ /// side bar comes along, and neither the side bar's size, a machine key, nor the trusted publishers do.
#[gpui::test]
fn accepting_the_contents_pick_imports_every_part(cx: &mut TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
@@ -194,6 +200,13 @@ pub(super) mod tests {
std::fs::create_dir_all(&source.user_dir).unwrap();
std::fs::write(source.user_dir.join("settings.json"), r#"{ "editor.fontSize": 17 }"#).unwrap();
std::fs::write(source.user_dir.join("keybindings.json"), r#"[{ "key": "cmd+alt+7", "command": "workbench.action.files.save" }]"#).unwrap();
+ std::fs::create_dir_all(source.user_dir.join("globalStorage")).unwrap();
+ let mut state = storage::Storage::open(&source.user_dir.join("globalStorage/state.vscdb"));
+ state.set("views.customizations", r#"{"viewContainerLocations":{"workbench.view.scm":2},"viewLocations":{},"viewContainerBadgeEnablementStates":{}}"#.into());
+ state.set("workbench.sideBar.size", "300".into());
+ state.set("extensions.trustedPublishers", r#"{"ms-azuretools":{}}"#.into());
+ state.set("__$__targetStorageMarker", r#"{"views.customizations":0,"workbench.sideBar.size":1,"extensions.trustedPublishers":0}"#.into());
+ drop(state);
let user = dir.join("data/User");
std::fs::create_dir_all(&user).unwrap();
let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), user.clone(), None)));
@@ -212,6 +225,11 @@ pub(super) mod tests {
let keybindings = workbench.read_with(cx, |workbench, _| workbench.user_data_profiles.state.as_ref().unwrap().current.keybindings_resource.clone());
assert!(std::fs::read_to_string(user.join("settings.json")).unwrap().contains(r#""editor.fontSize": 17"#));
assert!(std::fs::read_to_string(keybindings).unwrap().contains("cmd+alt+7"));
+ workbench.read_with(cx, |workbench, _| {
+ assert_eq!(workbench.container_location("workbench.view.scm"), super::super::layout::Part::AuxiliaryBar);
+ let storage = workbench.profile_storage.lock().unwrap();
+ assert_eq!((storage.get("workbench.sideBar.size"), storage.get("extensions.trustedPublishers")), (None, None));
+ });
std::fs::remove_dir_all(dir).unwrap();
}
diff --git a/port/ledger.md b/port/ledger.md
index 59c9bc361b7..06fe222215e 100644
--- a/port/ledger.md
+++ b/port/ledger.md
@@ -757,6 +757,6 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston
| telemetry/source-search | cross-cutting check | M19 | verified | | port/tools/telemetry-source-check: no telemetry or experimentation endpoint in the release binary, out-exthost and the 86 shipped built-ins with their 339 resolved packages (18370 files); SELF_TEST=1 finds 9 files in the inert packages |
| telemetry/network-capture | cross-cutting check | M19 | verified | | port/tools/network-capture, 600 s with no user action, fresh user data: folder window (eager git, npm, github activated) and empty window, no outbound traffic from the app's process tree; the control curl is seen each run. An earlier folder run with traffic was another session's keystrokes opening JSON files (json-language-features schema downloads), so runs take the Studio GUI lock |
| gallery/open-vsx | cross-cutting check | M18 | verified | | exthost/src/gallery.rs: query, latest-version resource, version choice, download with signature check; cargo test -p exthost gallery (upstream extensionGalleryService.test.ts sorting and filterLatestExtensionVersionsForTargetPlatform cases, Open VSX resource fixture); `workbench.extensions.installExtension redhat.vscode-yaml` downloads 2.0.0 from open-vsx.org, verifies it and activates without restart, not-found errors as upstream: PORT_GALLERY=1 port/tools/extensions-check |
-| port/settings-import | port feature | M10 | verified | | app/src/settings_import.rs, workbench/settings_import.rs: cargo test -p app settings_import installed_extensions_bring extensions_open_vsx_lacks_are_copied_from_the_source accepting_the_contents_pick_imports_every_part imported_extensions_ask_for_publisher_trust_once installed_extensions_bring_the_themes_the_settings_name an_empty_profile_takes_keybindings_json_with_its_comments reads_the_disabled_extensions on port/fixtures/settings-import; release GUI on the host lane: one import each from VS Code, Cursor and VSCodium fixtures under a scratch HOME. AI, sign-in, telemetry, remote and the editors' own settings and extensions are left out |
+| port/settings-import | port feature | M10 | verified | | app/src/settings_import.rs, workbench/settings_import.rs: cargo test -p app settings_import installed_extensions_bring extensions_open_vsx_lacks_are_copied_from_the_source accepting_the_contents_pick_imports_every_part imported_extensions_ask_for_publisher_trust_once installed_extensions_bring_the_themes_the_settings_name an_empty_profile_takes_keybindings_json_with_its_comments reads_the_disabled_extensions on port/fixtures/settings-import; release GUI on the host lane: one import each from VS Code, Cursor and VSCodium fixtures under a scratch HOME. AI, sign-in, telemetry, remote and the editors' own settings and extensions are left out; the UI state is what a VS Code profile export carries, the source global storage's `StorageTarget.USER` keys (view locations, pinned and hidden views; accepting_the_contents_pick_imports_every_part), not the part sizes (port/notes.md Settings import) |
| look/screenshot-diff | cross-cutting check | | verified | | port/tools/pixel-check: CDP reference capture and Metal readback in 3 themes, pixeldiff reference vs itself 0 different; baseline in port/results/pixels.md |
| perf/memory-benchmark | cross-cutting check | | verified | | port/tools/bench, median of 5 on the Studio, the VS Code 1.147.0 checkout open; port/results/benchmark.md: 218 MiB in all, extension host 74 MiB, VS Code 1.147.0 release 975 MiB and 195 MiB |
\ No newline at end of file
diff --git a/port/notes.md b/port/notes.md
index 2cace2c8051..a2fe2321cd1 100644
--- a/port/notes.md
+++ b/port/notes.md
@@ -175,6 +175,7 @@ Done when: api-tests `configuration.test` and `state.test` pass as in the refere
- Switching profiles (`workbench/user_data_profile.rs` `change_current_profile`): the settings layers, keybindings, profile storage and user extensions move to the new profile's files, then `workbench/extension_host_restart.rs` restarts the host, since the port has no window reload: the session thread sends Terminate, the workbench drops what the host registered (commands, language features, SCM, webview views, URI handlers and openers, the host's markers), and a new session starts with the current extensions, settings and storage. `workbench.action.restartExtensionHost` uses the same path. StorageScope.APPLICATION keys stay in the default profile's state.vscdb across switches (`application_storage`, the same storage as `profile_storage` in the default profile). The extension under development runs again without its tests.
- Profiles editor (`workbench/profiles_editor_view.rs`): the modal part with the sidebar and the contents view, rename, Use for Current/New Windows, Contents, Folders & Workspaces, the new profile form (Copy from a profile or an imported template, the Copy, Default or None source of each resource) and Export/Import of `.code-profile` files from a file or a URL (`app/src/profile_template.rs`). A non-default profile's Source radio writes its `useDefaultFlags`; for the current profile the window switches to the updated profile. The Icon row opens the icon picker (`workbench/icon_select_box.rs`, iconSelectBox.ts with the `iconSelectBox.*` commands): Search icons over the 83 `ICONS` in 36px cells, 12 a row, in a sticky hover under the icon. The activity bar's Manage item shows the current profile's icon, or the two-letter profile badge when it has none (globalCompositeBar.ts). The new profile form is named `Untitled N`, keeps Cancel, Preview and Create (Replace when a copy takes an existing name) under its scrolling body and validates as `NewProfileElement.validate`; its sidebar row has the dirty dot, Cancel and, while copying a profile, Export.... shortcut: Preview stores its profile instead of a transient one (each window is its own process, a transient profile would not reach the preview window); Cancel removes it. port/results/profiles.md.
- Settings import (`app/src/settings_import.rs`, `workbench/settings_import.rs`; Artur, no upstream counterpart): Preferences: Import from VS Code, Cursor or VSCodium..., and an offer on the first start with the default user data (no `--user-data-dir`) and no settings.json yet, shown once (`settingsImport.offered` in application storage). Keybindings already present are not duplicated; existing snippet files are kept; extensions are installed from Open VSX, and one Open VSX does not have or cannot install (not found, offline, an incompatible version) is copied from the source's extensions folder instead (`UserExtensions::install_folder`, without that editor's `__metadata`); a publisher the user did not trust is not copied either. The first import installed one extension at a time, each with its own publisher trust dialog queued behind the others, and dropped their results; it now runs like a profile import (one query, one trust dialog, progress, the failures listed), disables what VS Code has disabled, keeps keybindings.json comments when the profile has no keybindings yet, and the theme settings apply when their extension arrives. Settings the port removed (chat.*, github.copilot.*, the AI search toggle) stay left out by design. Fixtures in port/fixtures/settings-import.
+- Settings import, UI state (decision under the rule "only what a VS Code profile export or Settings Sync carries"): the layout lives in the source's `User/globalStorage/state.vscdb`, not in its settings. The import takes what globalStateResource.ts `getGlobalState` exports, the keys `__$__targetStorageMarker` marks `StorageTarget.USER` (0): `views.customizations` (a view or container moved, such as Source Control to the secondary side bar), `workbench.activity.pinnedViewlets2`, `workbench.auxiliarybar.pinnedPanels`, `workbench.panel.pinnedPanels`, the `*.state.hidden` views, `workbench.panel.alignment`, `workbench.statusbar.hidden`, written as `GlobalStateResource` applies them (`profile_template::store_user_state`), as a "UI State" part of the pick. Only these layout keys: the export's other USER keys include `extensions.trustedPublishers` and a sign-in's account access (`github-<account>`), which would skip the publisher trust dialog and the sign-in this import leaves to the user, besides survey, MRU and removed features' state. The part sizes (`workbench.sideBar.size`, `workbench.auxiliaryBar.size`, `workbench.panel.size`) and a workspace's part visibility are `StorageTarget.MACHINE` or workspace storage (layout.ts `LayoutStateKeys`) and neither export nor sync carries them, so they stay the port's. The activity bar at the top, the layout controls and `workbench.secondarySideBar.defaultVisibility` are settings and came with the settings part already.
- configuration-editing's own tests run with `port/tools/extension-tests configuration-editing` (a built-in extension's out/test from the reference checkout, against vsrustium): 18 passing. They needed `_executeCompletionItemProvider` and `_executeLinkProvider` to send cancellation tokens (`host.call_cancellable`, as rpcProtocol.ts does for a method whose last parameter is a token), `$acceptLanguageIds` at host start and restart (`vscode.languages.getLanguages`), `getContextKeyInfo` (the reference's `RawContextKey.all()`, dumped by `port/tools/ref-commands` into `contextkey/reference-context-keys.json`; rerun it when the reference moves) and the development copy of a built-in keeping `isBuiltin` (`scanExtensionsUnderDevelopment`), which `@vscode/internal-github`'s allowlist checks. The extensions.json cases expect `ms-vscode.js-debug`: the Studio mirror needs `port/tools/fetch-builtin-extensions` once.
## Milestone 9: commands, keybindings, quick input