Visual Studio Code, rebuilt in Rust
Rust
//! The command line's paths for a window: windowsMainService.ts `open` with the CLI's `--diff`, `--merge`, `--add`,
//! `--goto` and `--wait`, and window.ts `onOpenFiles` and `trackClosedWaitFiles` for the editors they open.
use std::path::{Path, PathBuf};
use gpui::{Context, Window};
use serde_json::{Value, json};
use super::Workbench;
use super::workspace_actions::Openable;
use crate::argv::{ParsedArgs, parse_line_and_column_aware};
use crate::commands::Outcome;
use crate::editor::uri_value;
/// `IPathToOpen` of a file: its `--goto` line and column become the editor's selection.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct FileToOpen {
pub path: PathBuf,
pub line: Option<u32>,
pub column: Option<u32>,
}
/// `IFilesToOpen`: the files to open, to diff (2) or to merge (4, the result last), and `--wait`'s marker file.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct FilesToOpen {
pub open: Vec<FileToOpen>,
pub diff: Vec<PathBuf>,
pub merge: Vec<PathBuf>,
pub wait_marker: Option<PathBuf>,
}
impl FilesToOpen {
pub fn is_empty(&self) -> bool {
self.open.is_empty() && self.diff.is_empty() && self.merge.is_empty()
}
/// `filesToWait.paths`: the diffed files, the merge result and the opened files.
fn paths_to_wait_for(&self) -> Vec<PathBuf> {
let merge_result = self.merge.get(3).cloned();
self.diff.iter().cloned().chain(merge_result).chain(self.open.iter().map(|file| file.path.clone())).collect()
}
}
/// The command line's paths sorted as windowsMainService.ts `open` sorts them: folders and workspaces to open (or to
/// add to the last active window with `--add`) and files.
#[derive(Debug, Default)]
pub(crate) struct CommandLine {
pub workspaces: Vec<PathBuf>,
pub folders_to_add: Vec<PathBuf>,
pub files: FilesToOpen,
pub new_window: bool,
pub reuse_window: bool,
}
impl CommandLine {
/// The paths relative to `cwd`; with `--goto` each one's `:line:column` is cut off first. A path that does not
/// exist is a file to create (`ignoreFileNotFound`).
pub fn from_args(args: &ParsedArgs, cwd: &Path) -> CommandLine {
let mut command_line = CommandLine { new_window: args.flag("new-window"), reuse_window: args.flag("reuse-window"), ..CommandLine::default() };
let mut files = Vec::new();
for arg in &args.positional {
let (path, line, column) = match args.flag("goto") {
true => match parse_line_and_column_aware(arg) {
Ok(parsed) => parsed,
Err(error) => {
eprintln!("[windows] {error}");
continue;
}
},
false => (arg.clone(), None, None),
};
let path = cwd.join(path);
if let Err(error) = files::unc::check_unc_access(&path) {
eprintln!("[windows] Invalid path provided: {}, {error}", path.display());
continue;
}
let openable = if path.exists() { Openable::of(path) } else { Openable::File(path) };
match openable {
Openable::Workspace(path) if args.flag("add") && path.is_dir() => command_line.folders_to_add.push(path),
Openable::Workspace(path) => command_line.workspaces.push(path),
Openable::File(path) => files.push(FileToOpen { path, line, column }),
}
}
if args.flag("diff") && files.len() >= 2 {
command_line.files.diff = files.drain(..).take(2).map(|file| file.path).collect();
} else if args.flag("merge") && files.len() == 4 {
command_line.files.merge = files.drain(..).map(|file| file.path).collect();
}
command_line.files.open = files;
command_line.files.wait_marker = args.string("waitMarkerFilePath").filter(|_| args.flag("wait")).map(PathBuf::from);
command_line
}
}
/// window.ts `trackClosedWaitFiles`: the marker is deleted once every waited path's editors closed and none is dirty.
pub(crate) struct WaitFiles {
marker: PathBuf,
paths: Vec<PathBuf>,
open: Vec<PathBuf>,
}
impl Workbench {
/// window.ts `onOpenFiles` and layout.ts `resolveEditorsToOpen`: the merge editor, else the diff editor, else each
/// file pinned at its `--goto` selection; then `--wait` tracks them. `startup` is the first window's editor resolver
/// cache and whether its editors are known, for `open_startup_file`.
pub(crate) fn open_command_line_files(&mut self, files: FilesToOpen, startup: Option<(&[String], bool)>, window: &mut Window, cx: &mut Context<Self>) {
let file_uri = |path: &Path| uri_value("file", path);
let mut outcomes = Vec::new();
if let [input1, input2, base, result] = &files.merge[..] {
let input = |path: &PathBuf| json!({ "uri": file_uri(path), "title": path.file_name().map(|name| name.to_string_lossy()), "description": "" });
let args = json!({ "base": file_uri(base), "input1": input(input1), "input2": input(input2), "output": file_uri(result) });
outcomes.push(self.execute_command("_open.mergeEditor", vec![args], window, cx));
} else if let [original, modified] = &files.diff[..] {
let args = vec![file_uri(original), file_uri(modified), Value::Null, json!([null, { "pinned": true }])];
outcomes.push(self.execute_command("_workbench.diff", args, window, cx));
}
for file in &files.open {
// editor.ts `pathsToEditors`: a file that does not exist opens untitled, saved to its path (`forceUntitled`).
if !file.path.exists() {
outcomes.push(self.execute_command("_workbench.open", vec![uri_value("untitled", &file.path), json!([null, { "pinned": true }])], window, cx));
continue;
}
match (file.line, startup) {
(Some(line), _) => {
let selection = json!({ "startLineNumber": line, "startColumn": file.column.unwrap_or(1) });
outcomes.push(self.execute_command("_workbench.open", vec![file_uri(&file.path), json!([null, { "pinned": true, "selection": selection }])], window, cx));
}
(None, Some((resolver_cache, editors_known))) => self.open_startup_file(file.path.clone(), resolver_cache, editors_known, window, cx),
(None, None) => self.open_file(file.path.clone(), true, window, cx),
}
}
let Some(marker) = files.wait_marker.clone() else { return };
if files.is_empty() {
self.wait_markers.push(marker);
return;
}
let paths = files.paths_to_wait_for();
let opened_plain_file = files.open.iter().any(|file| file.line.is_none());
cx.spawn_in(window, async move |workbench, cx| {
let mut opened = opened_plain_file;
for outcome in outcomes {
opened |= match outcome {
Outcome::Ready(result) => result.is_ok(),
Outcome::Pending(receiver) => matches!(receiver.await, Ok(Ok(_))),
};
}
let _ = workbench.update(cx, |workbench, _| {
// window.ts: a marker whose editors did not open is deleted right away.
if !opened {
let _ = std::fs::remove_file(&marker);
return;
}
workbench.wait_files.push(WaitFiles { marker, open: paths.clone(), paths });
workbench.release_closed_wait_files();
});
})
.detach();
}
/// editor.ts `whenEditorClosed`, from the state after a change: an editor of a waited path that left its group
/// closes it, unless the path came into another group (`EditorCloseContext.MOVE`); one that stays shows the
/// replacing editor (`REPLACE`, an untitled file saved). A diff editor shows both sides and a merge editor its
/// result (`EditorResourceAccessor.getOriginalUri`).
pub(super) fn release_closed_wait_files(&mut self) {
let mut shown = Vec::new();
for group in self.groups_in_grid_order() {
for editor in self.editors.group_tabs(group).0 {
if let Some(diff) = self.editors.diffs.get(&editor.model_id) {
shown.extend([(group, diff.original.path.clone()), (group, diff.modified.path.clone())]);
} else if let Some(merge) = self.editors.merges.get(&editor.model_id) {
shown.push((group, merge.result.path.clone()));
} else if editor.document().scheme == "file" || editor.text_model().associated_file {
shown.push((group, editor.document().path.clone()));
}
}
}
let before = std::mem::replace(&mut self.wait_shown, shown);
let shown = &self.wait_shown;
let came_in = |path: &PathBuf| shown.iter().any(|entry| &entry.1 == path && !before.contains(entry));
let closed: Vec<&PathBuf> = before.iter().filter(|entry| !shown.contains(entry) && !came_in(&entry.1)).map(|(_, path)| path).collect();
for wait in &mut self.wait_files {
wait.open.retain(|path| !closed.contains(&path));
}
self.delete_saved_wait_markers();
}
/// `whenEditorClosed`: a wait whose editors closed deletes its marker once none of its files is dirty (a pending
/// auto save), checked each frame as `onDidChangeDirty` would.
pub(super) fn delete_saved_wait_markers(&mut self) {
if self.wait_files.is_empty() {
return;
}
let dirty = |path: &PathBuf| self.editors.model("file", path).is_some_and(|editor| editor.is_dirty());
let (done, waiting): (Vec<WaitFiles>, _) = std::mem::take(&mut self.wait_files).into_iter().partition(|wait| wait.open.is_empty() && !wait.paths.iter().any(dirty));
self.wait_files = waiting;
for wait in done {
let _ = std::fs::remove_file(&wait.marker);
}
}
/// windowsMainService.ts `handleWaitMarkerFile`: the window used for `--wait` closed, so every marker it holds is
/// deleted.
pub(super) fn delete_wait_markers(&mut self) {
let markers = std::mem::take(&mut self.wait_markers).into_iter().chain(std::mem::take(&mut self.wait_files).into_iter().map(|wait| wait.marker));
for marker in markers {
let _ = std::fs::remove_file(marker);
}
}
}
#[cfg(test)]
mod tests;