Skip to content

Visual Studio Code, rebuilt in Rust

Rust

fix(scm): restore the shown repositories and sort key across sessions

rokartura19c61e1651b
diff --git a/native/crates/app/src/workbench.rs b/native/crates/app/src/workbench.rs
index 9ea69333121..267ef1e52f4 100644
--- a/native/crates/app/src/workbench.rs
+++ b/native/crates/app/src/workbench.rs
@@ -1072,6 +1072,7 @@ impl Workbench {
cx.on_app_quit(|workbench, _| {
workbench.store_explorer_view_state();
workbench.store_scm_repositories_view_state();
+ workbench.store_scm_view_state();
workbench.store_editor_view_states();
workbench.save_editor_part_state();
workbench.persist_terminal_state();
@@ -1082,6 +1083,7 @@ impl Workbench {
cx.on_release(|workbench, _| {
workbench.store_explorer_view_state();
workbench.store_scm_repositories_view_state();
+ workbench.store_scm_view_state();
workbench.store_editor_view_states();
workbench.store_editor_resolver_cache();
})
diff --git a/native/crates/app/src/workbench/extension_host_restart.rs b/native/crates/app/src/workbench/extension_host_restart.rs
index 4bfa05546e0..1f1b3332405 100644
--- a/native/crates/app/src/workbench/extension_host_restart.rs
+++ b/native/crates/app/src/workbench/extension_host_restart.rs
@@ -50,6 +50,7 @@ impl Workbench {
// MainThreadLanguageFeatures, MainThreadSCM, MainThreadWebview*, MainThreadUrls, MainThreadUriOpeners.
self.language_features = Default::default();
self.folding_providers = Default::default();
+ self.scm_extension_host_stopping();
self.scm.model = Default::default();
self.webview_views = Default::default();
self.urls.handlers.clear();
diff --git a/native/crates/app/src/workbench/quick_open.rs b/native/crates/app/src/workbench/quick_open.rs
index c9359967ec3..f34dd62a772 100644
--- a/native/crates/app/src/workbench/quick_open.rs
+++ b/native/crates/app/src/workbench/quick_open.rs
@@ -58,6 +58,7 @@ impl Workbench {
self.restore_search_history();
self.restore_explorer_view_state();
self.restore_scm_repositories_view_state();
+ self.restore_scm_view_state();
self.restore_editor_view_states();
self.restore_editor_part_state();
// explorerView.ts: the view shown at startup runs `selectActiveFile(true)` for the restored editor.
diff --git a/native/crates/app/src/workbench/scm_view.rs b/native/crates/app/src/workbench/scm_view.rs
index 6e092f6799d..ed455353a5f 100644
--- a/native/crates/app/src/workbench/scm_view.rs
+++ b/native/crates/app/src/workbench/scm_view.rs
@@ -26,6 +26,23 @@ pub(super) const ROW_HEIGHT: f32 = 22.;
pub(super) const INDENT: f32 = 8.;
pub(super) const TWISTIE: f32 = 16.;
+/// scmViewService.ts `ISCMViewServiceState` but its sort key: the repositories by `getProviderStorageKey` and the
+/// shown ones by their index there.
+struct PreviousState {
+ all: Vec<String>,
+ visible: Vec<i64>,
+}
+
+const VISIBLE_REPOSITORIES_KEY: &str = "scm:view:visibleRepositories";
+
+/// `getProviderStorageKey`.
+fn scm_provider_storage_key(provider: &Provider) -> String {
+ match provider.root_uri.is_null() {
+ true => format!("{}:{}", provider.id, provider.label),
+ false => format!("{}:{}:{}", provider.id, provider.label, crate::debug::uri_string(&provider.root_uri)),
+ }
+}
+
/// The view's state besides the model.
pub struct ScmView {
pub model: Scm,
@@ -58,6 +75,8 @@ pub struct ScmView {
/// `didFinishLoadingRepositories`, and the debounced `eventuallyFinishLoading` that sets it.
pub(super) finished_loading: bool,
finish_loading: Option<gpui::Task<()>>,
+ previous_state: Option<PreviousState>,
+ did_select_repository: bool,
pub(super) repositories: super::scm_repositories_view::RepositoriesView,
pub(super) input_histories: super::scm_actions::InputHistories,
}
@@ -83,6 +102,8 @@ impl ScmView {
sort_key: None,
finished_loading: false,
finish_loading: None,
+ previous_state: None,
+ did_select_repository: false,
repositories: super::scm_repositories_view::RepositoriesView::new(cx),
input_histories: Default::default(),
}
@@ -223,22 +244,94 @@ impl Workbench {
self.scm.input_models.insert(handle, (scheme.to_string(), path));
self.editors_changed(cx);
}
- // scmViewService.ts `onDidAddRepository`: it shows in `multiple` selection mode or as the first shown one, and
- // is focused when none is.
- // shortcut: no `previousState` from `scm:view:visibleRepositories`, port it with the workspace storage restore.
- if !self.scm_single_selection() || self.scm.visible.is_empty() {
- self.scm.visible.push(handle);
- }
+ let focus = self.show_added_scm_repository(handle);
self.sync_scm_tree_selection();
self.sync_scm_repository_menus();
let visible = self.scm.model.provider(handle).is_some_and(|provider| !provider.hidden);
- if visible && self.focused_scm_provider().is_none_or(|focused| focused.hidden || self.scm.focused.is_none()) {
+ if focus && visible && self.focused_scm_provider().is_none_or(|focused| focused.hidden || self.scm.focused.is_none()) {
self.focus_scm_repository(Some(handle));
}
self.restore_scm_input(handle, cx);
self.load_expanded_scm_artifacts(handle, cx);
}
+ /// scmViewService.ts `onDidAddRepository`: until repositories finish loading, `previousState` picks the shown ones:
+ /// a repository it lacks shows them all, the first one it showed replaces those shown so far, and once one it
+ /// showed came, one it hid stays hidden. Else it shows in `multiple` selection mode or as the first shown one. False
+ /// when the focus stays as it is.
+ fn show_added_scm_repository(&mut self, handle: u64) -> bool {
+ let single = self.scm_single_selection();
+ if let Some(previous) = self.scm.previous_state.as_ref().filter(|_| !self.scm.finished_loading) {
+ let key = self.scm.model.provider(handle).map(scm_provider_storage_key);
+ match previous.all.iter().position(|stored| Some(stored) == key.as_ref()) {
+ None => {
+ if !single || self.scm.visible.is_empty() {
+ self.scm.visible = self.scm_repositories().iter().map(|provider| provider.handle).collect();
+ }
+ self.scm.did_select_repository = false;
+ return false;
+ }
+ Some(index) if !previous.visible.contains(&(index as i64)) => {
+ if self.scm.did_select_repository {
+ return false;
+ }
+ }
+ Some(_) => {
+ if !self.scm.did_select_repository {
+ self.scm.visible.clear();
+ self.scm.focused = None;
+ self.scm.did_select_repository = true;
+ }
+ }
+ }
+ }
+ if !single || self.scm.visible.is_empty() {
+ self.scm.visible.push(handle);
+ }
+ true
+ }
+
+ /// `onWillSaveState`, once repositories finished loading: every repository and the shown ones by their index.
+ pub(super) fn store_scm_view_state(&mut self) {
+ if !self.scm.finished_loading {
+ return;
+ }
+ let all: Vec<String> = self.scm_repositories().into_iter().map(scm_provider_storage_key).collect();
+ let visible = self.visible_scm_providers().into_iter().map(|provider| {
+ let key = scm_provider_storage_key(provider);
+ all.iter().position(|stored| *stored == key).map_or(-1, |index| index as i64)
+ });
+ let state = PreviousState { visible: visible.collect(), all };
+ let stored = json!({ "all": state.all, "visible": state.visible, "sortKey": self.scm_repository_sort_key() });
+ self.workspace_storage.lock().unwrap().set(VISIBLE_REPOSITORIES_KEY, stored.to_string());
+ self.scm.previous_state = Some(state);
+ }
+
+ /// The service's constructor: `previousState` with its sort key, in `single` selection mode one shown repository.
+ pub(super) fn restore_scm_view_state(&mut self) {
+ let stored = self.workspace_storage.lock().unwrap().get(VISIBLE_REPOSITORIES_KEY).and_then(|raw| serde_json::from_str::<Value>(raw).ok());
+ let Some(stored) = stored else { return };
+ let strings = |key: &str| stored[key].as_array().into_iter().flatten().filter_map(|value| value.as_str().map(String::from)).collect::<Vec<_>>();
+ let mut visible: Vec<i64> = stored["visible"].as_array().into_iter().flatten().filter_map(Value::as_i64).collect();
+ if self.scm_single_selection() {
+ visible.truncate(1);
+ }
+ self.scm.sort_key = match stored["sortKey"].as_str() {
+ Some("name") => Some("name"),
+ Some("path") => Some("path"),
+ Some("discoveryTime") => Some("discoveryTime"),
+ _ => None,
+ };
+ self.scm.previous_state = Some(PreviousState { all: strings("all"), visible });
+ }
+
+ /// `extensionService.onWillStop`: the shown repositories are kept for the extension host's next repositories.
+ pub(super) fn scm_extension_host_stopping(&mut self) {
+ self.store_scm_view_state();
+ self.scm.finished_loading = false;
+ self.scm.visible.clear();
+ }
+
/// scmViewService.ts `eventuallyFinishLoading` (`@debounce(5000)`): `didFinishLoadingRepositories` turns true 5 s
/// after the last repository came or went, and the Repositories view then expands a lone repository.
fn eventually_finish_scm_loading(&mut self, cx: &mut Context<Self>) {
diff --git a/native/crates/app/src/workbench/scm_view/tests.rs b/native/crates/app/src/workbench/scm_view/tests.rs
index a2166e61ed3..efd09371f25 100644
--- a/native/crates/app/src/workbench/scm_view/tests.rs
+++ b/native/crates/app/src/workbench/scm_view/tests.rs
@@ -303,6 +303,39 @@ fn a_lone_repository_expands_once_repositories_finish_loading(cx: &mut TestAppCo
answer(&receiver, [("$provideArtifactGroups", groups)]);
}
+/// scmViewService.ts `scm:view:visibleRepositories`: stored once repositories finish loading, it picks the shown
+/// repositories of the next ones until they finish loading again; a repository it lacks shows them all.
+#[gpui::test]
+fn the_shown_repositories_come_back_with_their_sort_key(cx: &mut TestAppContext) {
+ let (workbench, _receiver, cx) = workbench_in("scm-visible-repositories", cx);
+ let shown = |workbench: &Workbench| workbench.visible_scm_providers().iter().map(|provider| provider.handle).collect::<Vec<_>>();
+ let roots = [(0, "/w/alpha"), (1, "/w/beta"), (2, "/w/gamma")];
+ workbench.update_in(cx, |workbench, window, cx| {
+ for (handle, root) in roots {
+ drop(workbench.handle_scm_request("$registerSourceControl", &register(handle, root, false), window, cx));
+ }
+ workbench.click_scm_tree_row("repo:1", Default::default());
+ drop(workbench.execute_command("workbench.scm.action.repositories.setSortKey.name", vec![], window, cx));
+ });
+ cx.executor().advance_clock(std::time::Duration::from_secs(5));
+ workbench.update_in(cx, |workbench, window, cx| {
+ workbench.scm_extension_host_stopping();
+ let stored: Value = serde_json::from_str(workbench.workspace_storage.lock().unwrap().get("scm:view:visibleRepositories").unwrap()).unwrap();
+ assert_eq!(stored, json!({ "all": ["git:Git:file:///w/alpha", "git:Git:file:///w/beta", "git:Git:file:///w/gamma"], "visible": [1], "sortKey": "name" }));
+ workbench.scm.model = Default::default();
+ workbench.scm.sort_key = None;
+ workbench.scm.previous_state = None;
+ workbench.restore_scm_view_state();
+ assert_eq!(workbench.scm_repository_sort_key(), "name");
+ for (handle, root) in roots.map(|(handle, root)| (handle + 10, root)) {
+ drop(workbench.handle_scm_request("$registerSourceControl", &register(handle, root, false), window, cx));
+ }
+ assert_eq!((shown(workbench), workbench.scm.focused), (vec![11], Some(11)));
+ drop(workbench.handle_scm_request("$registerSourceControl", &register(13, "/w/delta", false), window, cx));
+ assert_eq!(shown(workbench), [10, 11, 13, 12], "by name: alpha, beta, delta, gamma");
+ });
+}
+
/// scmRepositoriesViewPane.ts `RepositoryTreeDataSource` in explorer mode: a repository expands into its artifact groups
/// and a group with folders into a `ResourceTree` of its artifacts, single-child folders compressed; MainThreadSCM
/// `$onDidChangeArtifacts` asks the expanded repository and groups again.
diff --git a/port/ledger.md b/port/ledger.md
index 01064e5eeae..f59de1af7a5 100644
--- a/port/ledger.md
+++ b/port/ledger.md
@@ -529,7 +529,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston
| workbench/contrib/remoteTunnel | workbench contribution | | removed | | no sign-in/AI by decision (port/notes.md); not ported |
| workbench/contrib/replNotebook | workbench contribution | M17 | verified | | verified (session m17d): cargo test -p app repl; ui-pair m17/interactive-restart.json with replPair.open repl (executed, restored, executed again, status bar) matches (/tmp/m17f); repl_notebook.rs: `$tryShowNotebookDocument` with view type `repl` (ReplEditorInput: one editor per notebook, `ensureInputBoxCell`, `REPL - N` label or `asRepl` label, scratchpad close without asking, soft revert on dispose, tab kind 4 `jupyter-notebook` editor `repl`, `debug-line-by-line` icon), the last cell as the input box under the list of the others (interactive.rs draws and runs both), `repl.execute` (insert before the input), `repl.input.focus`, `repl.focusLastItemExecuted`, `mostRecentReplEditor`, editors delta `viewType: repl`: cargo test -p app repl_notebook, ui-pair m17/interactive-window.json (replPair.open repl). The REPL editor comes back after a reload (ReplEditorSerializer `workbench.editorinputs.replEditorInput`, notebooks.rs). REPL hot exit (ReplWindowWorkingCopyEditorHandler: `notebook/<type>/repl` backups, a REPL editor opened on the restored notebook): cargo test -p app a_repl_backup_opens_a_repl_editor. Not done: the status bar while the REPL input has the focus (reference: `LF` only, then `Spaces: 4 LF Cell 1 of 1`; port: `Ln 1, Col 1 Spaces: 4 LF`), ui-pair m17/interactive-window.json (replPair.open repl) |
| workbench/contrib/sash | workbench contribution | M11 | verified | | `workbench.sash.size` (editor group sashes 4..20, their highlight 1..8; the part grid's sashes are its 4px gaps) and `workbench.sash.hoverDelay` on every sash (part grid, view panes, editor groups, find widget, keybindings table), three-dot grippers on the part sashes with `workbench.sash.autoHideGrippers` and its delay (part_grid.rs); cargo test -p app part_grid; verified: ui-pair hot-exit.json `sash` vs the reference (port/results/windows.md, milestone 11 verification) |
-| workbench/contrib/scm | workbench contribution | M14 | ported | [3 S] scm_repositories_view.rs:415: the Repositories rows lack the reference's 4px pane inset, the tree's indent guides and the repository row's `...` for its menu's secondary actions <br> [3 S] scm_view.rs:969: inline submenus are not drawn (git's Stash submenu on the Stashes artifact group) <br> [3 M] scm_view.rs:228: the shown repositories are not restored across sessions (scmViewService.ts `scm:view:visibleRepositories`) <br> [3 M] scm_view.rs:93, :649: headers as view_panes panes; labels.ts shorten | SCM view: input box, action button, groups, resources with decorations, inline and title actions, activity badge, status bar commands (workbench/scm_view.rs); quick diff gutter and peek (quick_diff.rs, quick_diff_widget.rs), multiple repositories, tree view mode and sort (scm_tree.rs), Graph view (scm_history.rs, scm_graph_view.rs) with its history item ref picker and filters (scm_graph_view/ref_picker.rs; ui-pair m11/scm-graph-refs.json), view actions (scm_actions.rs), editor commands run from the resource row: cargo test -p app scm; Graph subjects draw their `$(icon)`s (cargo test -p app a_subject_draws_its_icons); Repositories view with selection modes, sort keys, nested repositories and explorer mode's artifact groups, folders and artifacts with their menus (scm_repositories_view.rs; cargo test -p app the_repositories_ explorer_mode_), its Shift+click range and list keys (cargo test -p app the_repositories_tree_takes_shift_clicks_and_keys), Escape and `list.toggleSelection` (cargo test -p app escape_and_toggle_selection_leave_the_shown_repositories), the lone repository's expansion and `scm.repositoriesViewState` (cargo test -p app lone_repository) |
+| workbench/contrib/scm | workbench contribution | M14 | ported | [3 S] scm_repositories_view.rs:415: the Repositories rows lack the reference's 4px pane inset, the tree's indent guides and the repository row's `...` for its menu's secondary actions <br> [3 S] scm_view.rs:1062: inline submenus are not drawn (git's Stash submenu on the Stashes artifact group) <br> [3 M] scm_view.rs:114, :742: headers as view_panes panes; labels.ts shorten | SCM view: input box, action button, groups, resources with decorations, inline and title actions, activity badge, status bar commands (workbench/scm_view.rs); quick diff gutter and peek (quick_diff.rs, quick_diff_widget.rs), multiple repositories, tree view mode and sort (scm_tree.rs), Graph view (scm_history.rs, scm_graph_view.rs) with its history item ref picker and filters (scm_graph_view/ref_picker.rs; ui-pair m11/scm-graph-refs.json), view actions (scm_actions.rs), editor commands run from the resource row: cargo test -p app scm; Graph subjects draw their `$(icon)`s (cargo test -p app a_subject_draws_its_icons); Repositories view with selection modes, sort keys, nested repositories and explorer mode's artifact groups, folders and artifacts with their menus (scm_repositories_view.rs; cargo test -p app the_repositories_ explorer_mode_), its Shift+click range and list keys (cargo test -p app the_repositories_tree_takes_shift_clicks_and_keys), Escape and `list.toggleSelection` (cargo test -p app escape_and_toggle_selection_leave_the_shown_repositories), the lone repository's expansion and `scm.repositoriesViewState` (cargo test -p app lone_repository), the shown repositories and sort key across sessions (cargo test -p app the_shown_repositories_come_back_with_their_sort_key) |
| workbench/contrib/screenshotTool | workbench contribution | | removed | | Artur: internal infrastructure or developer tool with no 1:1 counterpart in the native port |
| workbench/contrib/scrollLocking | workbench contribution | M14 | verified | | workbench/scroll_locking.rs: Toggle and Hold Locked Scrolling and the prominent `status.scrollLockingEnabled` entry: cargo test -p app scroll_locking; a locked wheel scroll moves every other visible editor as far from its position when tracked (`onDidEditorPaneScroll`; cargo test -p app a_locked_scroll_moves_every_other_visible_editor); Hold locks while its key is down and unlocks on the key up (keybindingService.ts `enableKeybindingHoldMode`; cargo test -p app a_held_key_locks_scrolling_until_it_goes_up); without a focused element Hold toggles, as the key up reaches the workbench through the focus path |
| workbench/contrib/search | workbench contribution | M12 | verified | | Search view (workbench/search_view.rs, search_actions.rs) and its model (search_model.rs): cargo test -p app search_model (searchResult, fileMatch and replace tests) and workbench::search_actions (context menu, input history, hover right click, the replace preview opened and updated with the replace string), port/tools/ui-pair frames match the reference in dark, light and hc (port/notes.md milestone 12); anythingQuickAccess.ts file picks: cargo test -p app anything_quick_access quick_open. No notebook or AI results; Find in Folder from the Explorer (cargo test -p app find_in_folder; ui-pair m12/find-in-folder.json with `search.mode` newEditor matches); ui-pair m12/search-replace.json (query, Replace input, preview) matches; the message words at their exact widths, so "2 results in 2 files - Open in editor" fits one line as in the reference (cargo test -p app the_message_words_take_their_exact_width; pair: same box, 408 device px wide) |