Skip to content

Visual Studio Code, rebuilt in Rust

Rust

fix(windows): open a file in the window whose folder holds it

rokartur63e5c297e560
diff --git a/native/crates/app/src/workbench/host.rs b/native/crates/app/src/workbench/host.rs
index fb43d910a38..88d049738c3 100644
--- a/native/crates/app/src/workbench/host.rs
+++ b/native/crates/app/src/workbench/host.rs
@@ -2,7 +2,7 @@
//! a folder or file, `reload`, a workspace replacing this window's, switching windows, and the window's extension host
//! ending with it.
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -218,7 +218,7 @@ impl Workbench {
/// launchMainService.ts `startOpenWindow` for a second instance's command line: without paths the last active window
/// comes to the front (the macOS default of `window.openWithoutArgumentsInNewWindow`), or an empty window opens with
/// `on` or `--new-window`. With paths, windowsMainService.ts `open`: `--add` folders join the last active window,
-/// files open there (or in the first folder's window), folders and workspaces in new windows unless `--reuse-window`,
+/// files open in the window whose folder holds them (`findWindowOnFile`), else there, folders and workspaces in new windows unless `--reuse-window`,
/// `--wait` or `window.openFoldersInNewWindow` keep the first one in the last active window. `from_dock` is the
/// `DOCK` context of Finder and the Dock, where files open in a new window too.
pub(crate) fn start_open_window(args: Vec<String>, cwd: PathBuf, from_dock: bool, cx: &mut App) {
@@ -276,7 +276,9 @@ pub(crate) fn start_open_window(args: Vec<String>, cwd: PathBuf, from_dock: bool
}
}
let Some(files) = files else { return };
- match last_active.filter(|_| !files_in_new_window) {
+ let file_to_check = files.open.first().map(|file| file.path.as_path()).or(files.diff.first().map(PathBuf::as_path)).or(files.merge.first().map(PathBuf::as_path));
+ let window_on_file = file_to_check.and_then(|file| find_window_on_file(file, cx));
+ match window_on_file.or(last_active).filter(|_| !files_in_new_window) {
Some(handle) => drop(handle.update(cx, |workbench, window, cx| {
workbench.open_command_line_files(files, None, window, cx);
window.activate_window();
@@ -285,6 +287,28 @@ pub(crate) fn start_open_window(args: Vec<String>, cwd: PathBuf, from_dock: bool
}
}
+/// windowsFinder.ts `findWindowOnFile`: the first workspace window with a folder that holds the file, else the single
+/// folder window nearest above it. Paths compare ignoring case (`extUriBiasedIgnorePathCase` on macOS).
+fn find_window_on_file(file: &Path, cx: &App) -> Option<WindowHandle<Workbench>> {
+ let file = PathBuf::from(file.to_string_lossy().to_lowercase());
+ let holds_file = |folder: &Path| file.starts_with(folder.to_string_lossy().to_lowercase());
+ let mut folder_window: Option<(WindowHandle<Workbench>, usize)> = None;
+ for handle in cx.windows().into_iter().filter_map(|window| window.downcast::<Workbench>()) {
+ let Some(workspace) = handle.read(cx).ok().and_then(|workbench| workbench.workspace()) else { continue };
+ let depth = workspace.folders.iter().filter(|folder| holds_file(&folder.path)).map(|folder| folder.path.as_os_str().len()).max();
+ match (&workspace.file, depth) {
+ (_, None) => {}
+ (Some(_), Some(_)) => return Some(handle),
+ (None, Some(depth)) => {
+ if folder_window.is_none_or(|(_, deepest)| depth > deepest) {
+ folder_window = Some((handle, depth));
+ }
+ }
+ }
+ }
+ folder_window.map(|(handle, _)| handle)
+}
+
/// windowsMainService.ts `open` with `forceNewWindow`: a folder or `.code-workspace` file opens as a new window's
/// workspace unless a window has it open already (that one comes to the front), any other path as an empty window's
/// file, nothing as an empty window. Opened after the caller's update.
diff --git a/native/crates/app/src/workbench/host/tests.rs b/native/crates/app/src/workbench/host/tests.rs
index a704e200e2f..297f4f1dc42 100644
--- a/native/crates/app/src/workbench/host/tests.rs
+++ b/native/crates/app/src/workbench/host/tests.rs
@@ -1,4 +1,4 @@
-use std::path::Path;
+use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use config::registry::Registry;
@@ -61,3 +61,28 @@ fn switch_window_lists_the_windows_and_closes_one_from_its_row(cx: &mut TestAppC
assert!(!open.contains(&last_window.window_id()), "the last window closed");
assert_eq!(open.len(), 2);
}
+
+/// windowsMainService.ts `open` with `window.openFilesInNewWindow` `off`: a file from the command line or Finder opens
+/// in the window whose folder holds it (`findWindowOnFile`), the nearest folder first, not in the last active window.
+#[gpui::test]
+fn a_file_opens_in_the_window_whose_folder_holds_it(cx: &mut TestAppContext) {
+ let dir = std::env::temp_dir().join(format!("vsrustium-window-on-file-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(dir.join("project/sub")).unwrap();
+ std::fs::write(dir.join("project/top.txt"), "").unwrap();
+ std::fs::write(dir.join("project/sub/deep.txt"), "").unwrap();
+ empty_window(cx);
+ for folder in ["project", "project/sub"] {
+ cx.update(|cx| open_request_window(crate::WindowRequest { workspace: Some(config::workspace::Workspace::open(dir.join(folder))), ..Default::default() }, cx));
+ }
+ let top = dir.join("PROJECT/top.txt").to_string_lossy().into_owned();
+ cx.update(|cx| super::start_open_window(vec![String::new(), top], "/".into(), false, cx));
+ cx.update(|cx| crate::workbench::url_handler::open_system_urls(vec![format!("file://{}", dir.join("project/sub/deep.txt").display())], cx));
+ cx.run_until_parked();
+ let opened: Vec<(Option<PathBuf>, Option<String>)> = cx.update(|cx| {
+ let workbenches = cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>()).filter_map(|handle| handle.entity(cx).ok());
+ workbenches.map(|workbench| workbench.read(cx)).map(|workbench| (workbench.workspace().map(|workspace| workspace.folders[0].path.clone()), workbench.editors.active().map(|editor| editor.document().path.file_name().unwrap().to_string_lossy().into_owned()))).collect()
+ });
+ assert_eq!(opened, [(None, None), (Some(dir.join("project")), Some("top.txt".into())), (Some(dir.join("project/sub")), Some("deep.txt".into()))]);
+ std::fs::remove_dir_all(dir).unwrap();
+}
diff --git a/port/ledger.md b/port/ledger.md
index 67e6e057737..0d3641669b4 100644
--- a/port/ledger.md
+++ b/port/ledger.md
@@ -227,7 +227,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston
| platform/keyboardLayout | src/vs/platform | M9 | verified | | keyboard_layout.rs: layout info and raw mapping as native-keymap reads them, Developer: Inspect Key Mappings (JSON) (cargo test -p app keyboard_layout inspect_key_mappings; output byte-identical to native-keymap on the Studio); keyboard_mapper.rs MacLinuxKeyboardMapper: cargo test -p app keyboard_mapper (dumpDebugInfo byte-identical to mac_de_ch, mac_en_us, mac_zh_hant, mac_zh_hant2; the macOS resolve cases); Developer: Inspect Key Mappings with the installed scan-code mapper's tables as `_dumpDebugInfo` (cargo test -p app inspect_key_mappings_shows_the_scan_code_mapper_tables); the picker is web-only |
| platform/label | src/vs/platform | M12 | verified | | the ILabelService interface; the file scheme labels are workbench/services/label; verified at port-m12b-verify: cargo test -p app path_labels 2/2 |
| platform/languagePacks | src/vs/platform | M18 | verified | | languagepacks.json from `contributes.localizations`, `resolveLanguagePackLanguage`, manifest translations: cargo test -p exthost language_packs; with MS-CEINTL.vscode-language-pack-de installed and `--locale de` the Command Palette shows German titles (port/results/extensions.md) |
-| platform/launch | src/vs/platform | M11 | verified | | launch.rs (main.ts `claimInstance`, launchMainService.ts): the first instance listens on `<user data>/1.147.0-main.sock`; a later start with the same user data sends its arguments and working directory and exits once they are taken (a stale socket is removed); workbench/host.rs `start_open_window`: no paths brings the last active window to the front (`window.openWithoutArgumentsInNewWindow` default on macOS) or opens an empty window (`on`, `--new-window`), folders and workspaces open or focus their window, files open in the last active window; the `file://` urls Finder and the Dock hand the app (app.ts `open-file`, workbench/url_handler.rs `open_system_urls`) open the same way in the `DOCK` context: the ones that follow within 100 ms open together, files in a new window with `window.openFilesInNewWindow` `default`, and at launch they take the startup window's place, with the last session's windows only for `window.restoreWindows` `preserve` (main.rs `last_session_windows`). The command line: argv.rs (argv.ts `OPTIONS`, minimist, `parseArgs`, `buildHelpMessage`, `buildVersionMessage`, argvHelper.ts `--goto` validation), cli.rs (code/node/cli.ts run by bin/code with `ELECTRON_RUN_AS_NODE`: `-` reads stdin into a 0600 `code-stdin-*` file, `--wait` creates the marker and waits until it is deleted, the app starts through `open -n -g` with `VSCODE_CWD`), workbench/command_line.rs (windowsMainService.ts and window.ts: `--diff`, `--merge`, `--add`, `--goto file:line:col`, `-n`/`-r`, a path that does not exist opens untitled and is created on save, a folder reuses the last active window and keeps its `--wait` marker, `--wait`'s marker deleted once each waited file has an editor closed (not moved) and none is dirty, checked each frame as `onDidChangeDirty`, or when the window closes). `cargo test -p app launch argv:: command_line:: url_handler a_finder_launch` (url_handler::tests::a_workspace_file_from_finder_opens_a_window_of_its_folders, a_file_from_finder_opens_in_a_new_window_with_open_files_in_new_window_default, documents_that_follow_within_100_ms_open_together; a_finder_launch_restores_the_last_session_only_with_preserve; argv::tests::parses_the_command_line_as_upstream_argv, help_matches_upstream_text, goto_mode_validates_its_arguments; command_line::tests::goto_opens_the_file_at_its_line_and_column, diff_and_merge_open_their_editors, the_wait_marker_is_deleted_once_its_editors_close, the_wait_marker_is_deleted_when_one_of_two_editors_of_its_file_closes, the_wait_marker_waits_for_the_dirty_file_to_be_saved, the_wait_marker_is_deleted_when_the_window_closes, a_missing_file_opens_untitled_and_is_created_on_save); packaged app via a /usr/local/bin-style link to bin/code: `--version` and `--help` print, `--wait a.txt` waits until Cmd+W closes the editor, `echo text | vsrustium -` opens the stdin file, `--wait folder` loads the folder in the last active window and waits until that window closes; verified: ui-pair hot-exit.json `launched` vs the reference (port/results/windows.md, milestone 11 verification): a second start hands docs/guide.md to the running instance |
+| platform/launch | src/vs/platform | M11 | verified | | launch.rs (main.ts `claimInstance`, launchMainService.ts): the first instance listens on `<user data>/1.147.0-main.sock`; a later start with the same user data sends its arguments and working directory and exits once they are taken (a stale socket is removed); workbench/host.rs `start_open_window`: no paths brings the last active window to the front (`window.openWithoutArgumentsInNewWindow` default on macOS) or opens an empty window (`on`, `--new-window`), folders and workspaces open or focus their window, files open in the window whose folder holds them (windowsFinder.ts `findWindowOnFile`), else in the last active window; the `file://` urls Finder and the Dock hand the app (app.ts `open-file`, workbench/url_handler.rs `open_system_urls`) open the same way in the `DOCK` context: the ones that follow within 100 ms open together, files in a new window with `window.openFilesInNewWindow` `default`, and at launch they take the startup window's place, with the last session's windows only for `window.restoreWindows` `preserve` (main.rs `last_session_windows`). The command line: argv.rs (argv.ts `OPTIONS`, minimist, `parseArgs`, `buildHelpMessage`, `buildVersionMessage`, argvHelper.ts `--goto` validation), cli.rs (code/node/cli.ts run by bin/code with `ELECTRON_RUN_AS_NODE`: `-` reads stdin into a 0600 `code-stdin-*` file, `--wait` creates the marker and waits until it is deleted, the app starts through `open -n -g` with `VSCODE_CWD`), workbench/command_line.rs (windowsMainService.ts and window.ts: `--diff`, `--merge`, `--add`, `--goto file:line:col`, `-n`/`-r`, a path that does not exist opens untitled and is created on save, a folder reuses the last active window and keeps its `--wait` marker, `--wait`'s marker deleted once each waited file has an editor closed (not moved) and none is dirty, checked each frame as `onDidChangeDirty`, or when the window closes). `cargo test -p app launch argv:: command_line:: url_handler a_finder_launch host::` (host::tests::a_file_opens_in_the_window_whose_folder_holds_it; url_handler::tests::a_workspace_file_from_finder_opens_a_window_of_its_folders, a_file_from_finder_opens_in_a_new_window_with_open_files_in_new_window_default, documents_that_follow_within_100_ms_open_together; a_finder_launch_restores_the_last_session_only_with_preserve; argv::tests::parses_the_command_line_as_upstream_argv, help_matches_upstream_text, goto_mode_validates_its_arguments; command_line::tests::goto_opens_the_file_at_its_line_and_column, diff_and_merge_open_their_editors, the_wait_marker_is_deleted_once_its_editors_close, the_wait_marker_is_deleted_when_one_of_two_editors_of_its_file_closes, the_wait_marker_waits_for_the_dirty_file_to_be_saved, the_wait_marker_is_deleted_when_the_window_closes, a_missing_file_opens_untitled_and_is_created_on_save); packaged app via a /usr/local/bin-style link to bin/code: `--version` and `--help` print, `--wait a.txt` waits until Cmd+W closes the editor, `echo text | vsrustium -` opens the stdin file, `--wait folder` loads the folder in the last active window and waits until that window closes; verified: ui-pair hot-exit.json `launched` vs the reference (port/results/windows.md, milestone 11 verification): a second start hands docs/guide.md to the running instance |
| platform/layout | src/vs/platform | M11 | verified | | `ILayoutService` as the workbench's part grid (workbench/layout.rs, part_grid.rs): container dimensions and part offsets of the main window; checks as workbench/services/layout (port/results/layout.md "Part positions", "Zen mode and centered layout") |
| platform/lifecycle | src/vs/platform | M11 | verified | | lifecycleMainService quit and window close through workbench/lifecycle.rs, menubar.ts confirmBeforeQuit; cargo test -p app lifecycle; verified: ui-pair hot-exit.json `dirty`, `restored` vs the reference (port/results/windows.md, milestone 11 verification) |
| platform/list | src/vs/platform | M9 | verified | | list scrolling, scrollbars, smooth scrolling, sensitivities, scrollByPage, horizontal scrolling, tree indent guides and sticky scroll, type navigation in the Explorer and Keyboard Shortcuts table, listCommands.ts on the Explorer, Search and the table (port/notes.md milestone 9): cargo test -p app menubar list_scroll list_tree type_navigation typing keybindings_editor_view search_actions explorer hover sticky, 135 passed, then list_scroll 5 passed (the_wheel_scrolls_after_a_key_press, scrolling_hides_the_rows_hover); ui-pair Explorer expand and 4 wheel notches: expand, guides, sticky row and its unselected look match the reference; the wheel scrolls the port 282px, the reference 304px (port/notes.md milestone 9 handoff); split_view.rs SplitView (proportional layout, distributeEmptySpace, sash drag with Alt for both sides, sash states) under the Keyboard Shortcuts table's column headers: sash cursors, 300ms hover border, double-click reset to the column weight, tree.tableColumnsBorder fading in on table hover (cargo test -p app split_view keybindings_editor_view; ui-pair drag and reset land on the reference's columns); listWidget and the other lists stay with their views |