Skip to content

Visual Studio Code, rebuilt in Rust

Rust

fix(windows): open files and workspaces Finder hands the app

rokartur79ca906e478c
diff --git a/native/crates/app/src/main.rs b/native/crates/app/src/main.rs
index 45a477f8c72..e88ddaca31a 100644
--- a/native/crates/app/src/main.rs
+++ b/native/crates/app/src/main.rs
@@ -286,29 +286,38 @@ fn main() -> anyhow::Result<()> {
open_window_or_log(WindowRequest::default(), cx);
}
});
- // app.ts `open-url` (ElectronURLListener): the bundle's CFBundleURLTypes route `code-oss://` urls here.
- let (url_sender, mut urls) = futures::channel::mpsc::unbounded::<String>();
- application.on_open_urls(move |opened| opened.into_iter().for_each(|url| drop(url_sender.unbounded_send(url))));
+ // app.ts `open-url` and `open-file`: the bundle's CFBundleURLTypes route `code-oss://` urls here, its
+ // CFBundleDocumentTypes the files and folders opened from Finder or dropped on the Dock as `file://` urls.
+ let (url_sender, mut urls) = futures::channel::mpsc::unbounded::<Vec<String>>();
+ application.on_open_urls(move |opened| drop(url_sender.unbounded_send(opened)));
+ let no_cli_paths = positional.is_empty();
application.run(move |cx: &mut App| {
perf::mark("code/mainAppReady");
workbench::accessibility::watch_assistive_apps(cx);
+ // app.ts `macOpenFiles`: AppKit sends the launch's documents before `applicationDidFinishLaunching:`; they replace the
+ // last session's windows and open from the task, as effects deferred from this callback never run.
+ let launch_urls: Vec<Vec<String>> = std::iter::from_fn(|| urls.try_next().ok().flatten()).collect();
+ let opens_documents = no_cli_paths && launch_urls.iter().flatten().any(|url| url.starts_with("file:"));
cx.spawn(async move |cx| {
- while let Some(url) = futures::StreamExt::next(&mut urls).await {
- cx.update(|cx| workbench::url_handler::open_system_url(url, cx));
+ let mut opened_urls = futures::StreamExt::chain(futures::stream::iter(launch_urls), urls);
+ while let Some(opened) = futures::StreamExt::next(&mut opened_urls).await {
+ cx.update(|cx| workbench::url_handler::open_system_urls(opened, cx));
}
})
.detach();
cx.set_global(user_data_profile::UserDataProfilesService::load(&app.user_data, &app.user_extensions_folder));
cx.set_global(app);
- for window in restored {
- let workspace = window.workspace.clone().or(window.folder.clone()).map(Workspace::open);
- open_window_or_log(WindowRequest { workspace, backup_folder: window.backup_path, ui: window.ui, ..WindowRequest::default() }, cx);
- }
- if let Some(startup) = startup
- && let Err(error) = open_window(startup, cx)
- {
- eprintln!("{error:#}");
- std::process::exit(1);
+ if !opens_documents {
+ for window in restored {
+ let workspace = window.workspace.clone().or(window.folder.clone()).map(Workspace::open);
+ open_window_or_log(WindowRequest { workspace, backup_folder: window.backup_path, ui: window.ui, ..WindowRequest::default() }, cx);
+ }
+ if let Some(startup) = startup
+ && let Err(error) = open_window(startup, cx)
+ {
+ eprintln!("{error:#}");
+ std::process::exit(1);
+ }
}
// app.ts `resolveShellEnvironment(..., notifyOnError: true)` once the first window opened: to the focused one.
if let Some(message) = shell_env_error
diff --git a/native/crates/app/src/workbench/host/tests.rs b/native/crates/app/src/workbench/host/tests.rs
index 25d061b2744..a704e200e2f 100644
--- a/native/crates/app/src/workbench/host/tests.rs
+++ b/native/crates/app/src/workbench/host/tests.rs
@@ -28,7 +28,7 @@ pub(crate) fn open_request_window(request: crate::WindowRequest, cx: &mut gpui::
let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
let opened = cx.open_window(gpui::WindowOptions::default(), |window, cx| {
cx.new(|cx| {
- let mut workbench = Workbench::new(theme, app_root, None, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx);
+ let mut workbench = Workbench::new(theme, app_root, request.workspace, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx);
workbench.open_command_line_files(request.files, None, window, cx);
workbench
})
diff --git a/native/crates/app/src/workbench/url_handler.rs b/native/crates/app/src/workbench/url_handler.rs
index 7f6b18ea611..b20a83ea7e6 100644
--- a/native/crates/app/src/workbench/url_handler.rs
+++ b/native/crates/app/src/workbench/url_handler.rs
@@ -68,6 +68,22 @@ impl Workbench {
}
}
+/// app.ts `open-file`: the documents Finder or the Dock hands the app open as the command line's paths would
+/// (`start_open_window`), any other url as `open-url`.
+pub(crate) fn open_system_urls(urls: Vec<String>, cx: &mut gpui::App) {
+ let mut args = vec![String::new()];
+ for url in urls {
+ match Uri::parse(&url) {
+ // `Uri::new` makes a file path absolute: it starts with `/`, so it never reads as a flag.
+ Ok(uri) if uri.scheme == "file" => args.push(uri.path),
+ _ => open_system_url(url, cx),
+ }
+ }
+ if args.len() > 1 {
+ super::host::start_open_window(args, PathBuf::from("/"), cx);
+ }
+}
+
/// electron-main app.ts `open-url`: the last active window handles a url the system hands the running app; with no
/// window, a new one opens with it.
pub(crate) fn open_system_url(url: String, cx: &mut gpui::App) {
@@ -279,6 +295,30 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
+ /// app.ts `open-file`: a `.code-workspace` file Finder hands the running app opens in a window of its folders.
+ #[gpui::test]
+ fn a_workspace_file_from_finder_opens_a_window_of_its_folders(cx: &mut gpui::TestAppContext) {
+ let app_root = std::path::Path::new(env!("VSCODE_SRC")).to_path_buf();
+ let theme = crate::theme::load_theme(&[exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
+ let dir = std::env::temp_dir().join(format!("vsrustium-open-file-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ for folder in ["User", "one", "two", "three"] {
+ std::fs::create_dir_all(dir.join(folder)).unwrap();
+ }
+ let workspace_file = dir.join("my team.code-workspace");
+ std::fs::write(&workspace_file, r#"{ "folders": [{ "path": "one" }, { "path": "two" }, { "path": "three" }] }"#).unwrap();
+ let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));
+ let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), settings, crate::host_sync::HostSync::new(std::sync::mpsc::channel().0), cx));
+ // NSURL `absoluteString`, as gpui hands it over.
+ let url = format!("file://{}", workspace_file.display()).replace(' ', "%20");
+ cx.cx.update(|cx| open_system_urls(vec![url], cx));
+ cx.run_until_parked();
+ let windows: Vec<gpui::Entity<Workbench>> = cx.cx.update(|cx| cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>()).filter_map(|handle| handle.entity(cx).ok()).collect());
+ let opened: Vec<Vec<PathBuf>> = windows.iter().filter(|other| **other != workbench).filter_map(|other| other.read_with(cx, |other, _| other.workspace().map(|workspace| workspace.folders.iter().map(|folder| folder.path.clone()).collect()))).collect();
+ assert_eq!(opened, [["one", "two", "three"].map(|folder| dir.join(folder)).to_vec()]);
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
/// app.ts `handleProtocolUrl`: `windowId=_blank` opens the file in a new window (`forceNewWindow`), at its line.
#[gpui::test]
fn a_file_url_for_a_new_window_opens_the_file_there(cx: &mut gpui::TestAppContext) {
diff --git a/port/ledger.md b/port/ledger.md
index 393f4da69e1..a9e8e28e921 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 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::` (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 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, at launch instead of the last session's windows (port/notes.md "Open from Finder"). 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:: a_workspace_file_from_finder` (url_handler::tests::a_workspace_file_from_finder_opens_a_window_of_its_folders; 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 |
diff --git a/port/notes.md b/port/notes.md
index ca73f193e2d..a8d3cac457b 100644
--- a/port/notes.md
+++ b/port/notes.md
@@ -948,6 +948,7 @@ Scope as in the M19 Work row of port/ledger.md.
- Windows (`main.rs` `AppState`, `WindowRequest`, `open_window`; `workbench/host.rs`): every window is a GPUI window of the one process with its own settings, storage, trust, extension host thread and workbench, as each reference window has its renderer and host. The menu bar runs its items in the active window, else the frontmost; with none, Quit quits and the other items open an empty window first; a Dock click without windows opens one (`app.on('activate')`). Closing the last window does not quit (macOS).
- Window state (`windows_state.rs`): `windowsState` in `User/globalStorage/storage.json`, the same key and shape as the reference (`lastActiveWindow`, `openedWindows`, `uiState` with `mode`, `display`, bounds). Display ids are the CGDirectDisplayID GPUI reports; bounds are points from the display's top left, so a window on a display that is gone opens centered.
- Launch (`launch.rs`): a Unix socket in the user data folder, one JSON line per second instance (`args`, `cwd`) answered with `ok` once taken. Tools that start the port with their own `--user-data-dir` get their own instance; a start from the checkout with the default `~/.vsrustium` hands its arguments to a running VSRustium.
+- Open from Finder (app.ts `open-file`, `macOpenFiles`; url_handler.rs `open_system_urls`): the files, folders and `.code-workspace` files Finder or the Dock hands the app arrive as `file://` urls through `application:openURLs:` and open through `start_open_window` as the command line's paths. At launch AppKit sends them before `applicationDidFinishLaunching:`, so main.rs drains them first and opens them instead of the last session's windows. Differences: no 100 ms batching (AppKit hands one call per open, Electron one event per path); with `window.openFilesInNewWindow: default` a file stays in the last active window, as from the command line, where upstream's `OpenContext.DOCK` opens a new one; with `window.restoreWindows: preserve` a launch from Finder does not restore the last session's windows.
- Inactive window (workbench.rs `title_bar`, `shell_background`; opener.rs re-renders on activation): `titleBar.inactiveBackground` and `inactiveForeground`, `commandCenter.inactiveBorder`, the title bar contents at 0.6 opacity (titlebarpart.css `.inactive > *`), and the modern UI shell in `modernUI.inactiveShellBackground`; both backgrounds are made opaque over WORKBENCH_BACKGROUND as titlebarPart.ts does.
- Open in this list, each waiting on another owner or a decision: `workbench/contrib/limitIndicator` needs the language status item (milestone 13); `workbench/contrib/modernUI` is drawn always on, while the classic look (`workbench.experimental.modernUI: false`) and the compact density (`window.density.layout`, Layout Density menu) change the part grid (main session). Window zoom (`window.zoomLevel`) is n/a by Artur's decision: GPUI has no window-wide scale outside its test build.
- Editor windows (`workbench/auxiliary_windows.rs`; auxiliaryEditorPart.ts, auxiliaryWindowService.ts, editorParts.ts, editorActions.ts): Move/Copy Editor and Editor Group into New Window (Command Palette, the tab menu's Move/Copy into New Window, View > Editor Layout), New Empty Editor Window, Restore Editors into Main Window. A part is a grid of groups in the workbench's `Editors`; `EditorGroups` holds the active group's part layout in its fields and parks the others' (`PartLayout`, `switch_part`, `in_part`), so the group commands act on the active part. `groups_in_grid_order` is every part's groups, main first. The window is a GPUI window whose root `AuxiliaryWindow` asks the workbench to draw the part (no card), the title bar (command center, Turn On/Off Always on Top, `titleBar.border`) and the part's editor status items. The window that turns active makes its part's most recent group the active one (editorParts.ts `activePart`); the overlays (quick input, menus, dialogs, hovers) draw in the active window; keys reach the workbench of the window they come from (the keystroke interceptor was app-wide: every workbench window took every window's keys). Closing the window (its button, Cmd+Shift+W, Close Group on its last group) moves the editors that would ask (dirty ones) to the main part's active group and closes the others; its last editor closed closes it; the main window takes its editor windows with it. `editorparts.state` (each part's grid and editors, bounds, part MRU) is saved on every editor change and restores at start when the main part restored its state. Compact mode (auxiliaryEditorPart.ts `updateCompact`; Toggle Window Compact Mode, the title's Turn On/Off Compact Mode): the part draws no tabs and no breadcrumbs, the window no status bar, the title bar the window title and a diff's Previous/Next Change (`MenuId.CompactWindowEditorTitle`); a split from it goes to the main part (`getAddGroupLocation`); a second group in the part, or another editor shown while its group has several, ends it; `compact` is stored with the window. Not ported: zoom per window. Tests: `cargo test -p app auxiliary_windows`; ui-pair port/results/auxiliary-windows.md.