Skip to content

Visual Studio Code, rebuilt in Rust

Rust
9.3 KB
Raw Blame
//! launchMainService.ts and main.ts `claimInstance`: the first instance listens on `<user data>/<version>-main.sock`
//! (on Windows the pipe `\\.\pipe\<hash>-<version>-main-sock`); a later start with the same user data hands its
//! arguments and working directory to it and exits.

use std::io::{BufRead, BufReader, Write};
#[cfg(unix)]
use std::os::unix::net::{UnixListener as Listener, UnixStream as Stream};
use std::path::{Path, PathBuf};

#[cfg(windows)]
use exthost::pipe::{Listener, Stream};
use futures::StreamExt;
use futures::channel::mpsc::{UnboundedReceiver, unbounded};
use gpui::App;
use serde_json::{Value, json};

/// What a second instance sends: its command line, working directory and whether a terminal's `code` started it
/// (`isLaunchedFromCli` of its `userEnv`), or a `--status` request answered with the
/// main process diagnostics (main.ts asks the `diagnostics` channel of the same socket).
pub enum Launch {
    Open { args: Vec<String>, cwd: PathBuf, launched_from_cli: bool },
    Status(futures::channel::oneshot::Sender<crate::diagnostics::MainDiagnostics>),
}

/// environmentMainService.ts `mainIPCHandle`: ipc.net.ts `createStaticIPCHandle(userDataPath, 'main', version)`.
pub fn socket_path(user_data: &Path) -> PathBuf {
    if cfg!(windows) {
        return windows_pipe_name(user_data, &crate::VERSION);
    }
    user_data.join(format!("{}-main.sock", *crate::VERSION))
}

/// `createStaticIPCHandle` on Windows: the first 8 hex digits of the user data path's SHA-256.
fn windows_pipe_name(user_data: &Path, version: &str) -> PathBuf {
    use sha2::Digest;
    let scope = sha2::Sha256::digest(user_data.to_string_lossy().as_bytes());
    let scope: String = scope[..4].iter().map(|byte| format!("{byte:02x}")).collect();
    PathBuf::from(format!(r"\\.\pipe\{scope}-{version}-main-sock"))
}

/// A second instance: true once the running one took the arguments. False when no instance listens (a stale socket is
/// removed then, as main.ts does on `ECONNREFUSED`).
pub fn send_to_running_instance(socket: &Path, args: &[String], cwd: &Path) -> bool {
    let Ok(mut stream) = Stream::connect(socket) else {
        #[cfg(unix)]
        let _ = std::fs::remove_file(socket);
        return false;
    };
    // main.ts `windowsAllowSetForegroundWindow`: the running instance may bring its window to the front.
    #[cfg(windows)]
    if let Ok(pid) = stream.server_process_id() {
        // SAFETY: takes a process id; no pointers pass.
        unsafe { windows_sys::Win32::UI::WindowsAndMessaging::AllowSetForegroundWindow(pid) };
    }
    let launched_from_cli = std::env::var("VSCODE_CLI").is_ok_and(|cli| cli == "1");
    let message = json!({ "args": args, "cwd": cwd, "launchedFromCli": launched_from_cli });
    if writeln!(stream, "{message}").is_err() {
        return false;
    }
    let mut answer = String::new();
    BufReader::new(stream).read_line(&mut answer).is_ok_and(|read| read > 0)
}

/// `diagnosticsMainService.getMainDiagnostics` of the instance listening on `socket`; None when none listens.
pub fn request_main_diagnostics(socket: &Path) -> Option<crate::diagnostics::MainDiagnostics> {
    let mut stream = Stream::connect(socket).ok()?;
    writeln!(stream, "{}", json!({ "status": true })).ok()?;
    let mut answer = String::new();
    BufReader::new(stream).read_line(&mut answer).ok()?;
    serde_json::from_str(&answer).ok()
}

/// The first instance: each second instance's launch, answered once it is read.
pub fn listen(socket: &Path) -> Option<UnboundedReceiver<Launch>> {
    #[cfg_attr(unix, expect(unused_mut, reason = "accept takes &mut on Windows"))]
    let mut listener = Listener::bind(socket).inspect_err(|error| eprintln!("[launch] listening on {}: {error}", socket.display())).ok()?;
    let (sender, receiver) = unbounded();
    std::thread::Builder::new()
        .name("launch".into())
        .spawn(move || {
            loop {
                #[cfg(unix)]
                let accepted = listener.accept().map(|(stream, _)| stream);
                #[cfg(windows)]
                let accepted = listener.accept(None);
                let Ok(stream) = accepted else { continue };
                let mut line = String::new();
                let mut reader = BufReader::new(&stream);
                if reader.read_line(&mut line).is_err() {
                    continue;
                }
                let Ok(message) = serde_json::from_str::<Value>(&line) else { continue };
                if message["status"] == true {
                    let (reply, answer) = futures::channel::oneshot::channel();
                    if sender.unbounded_send(Launch::Status(reply)).is_err() {
                        return;
                    }
                    if let Ok(diagnostics) = futures::executor::block_on(answer) {
                        let _ = writeln!(&stream, "{}", json!(diagnostics));
                    }
                    continue;
                }
                let args = message["args"].as_array().into_iter().flatten().filter_map(|arg| arg.as_str().map(str::to_owned)).collect();
                let cwd = PathBuf::from(message["cwd"].as_str().unwrap_or_default());
                let launched_from_cli = message["launchedFromCli"] == true;
                if sender.unbounded_send(Launch::Open { args, cwd, launched_from_cli }).is_err() {
                    return;
                }
                let _ = (&stream).write_all(b"ok\n");
            }
        })
        .expect("spawn the launch thread");
    Some(receiver)
}

/// Opens each launch until the app quits.
pub fn handle_launches(mut launches: UnboundedReceiver<Launch>, cx: &mut App) {
    cx.spawn(async move |cx| {
        while let Some(launch) = launches.next().await {
            let _ = cx.update(|cx| match launch {
                Launch::Open { args, cwd, launched_from_cli } => crate::workbench::host::start_open_window(args, cwd, false, launched_from_cli, cx),
                Launch::Status(reply) => drop(reply.send(main_diagnostics(cx))),
            });
        }
    })
    .detach();
}

/// `getMainDiagnostics`: the open windows with their titles and folders, and the extension hosts by name.
fn main_diagnostics(cx: &mut App) -> crate::diagnostics::MainDiagnostics {
    let main_pid = std::process::id();
    let mut windows = Vec::new();
    for handle in cx.windows().into_iter().filter_map(|handle| handle.downcast::<crate::workbench::Workbench>()) {
        let _ = handle.update(cx, |workbench, _, _| {
            let folders = workbench.workspace().map(|workspace| workspace.folders.iter().map(|folder| folder.path.clone()).collect()).unwrap_or_default();
            windows.push(crate::diagnostics::WindowDiagnostics { id: handle.window_id().as_u64(), pid: main_pid, title: workbench.window_title(), folders });
        });
    }
    // utilityProcess.ts names a window's host `extension-host [<window id>]`; the port does not keep the host's pid
    // per window, so the hosts are numbered in start (pid) order.
    let hosts = crate::ps::list_processes(main_pid, 0.).map(|root| root.children).unwrap_or_default();
    let pid_to_names = hosts.iter().filter(|child| child.cmd.contains("bootstrap-exthost.js")).enumerate().map(|(index, host)| (host.pid, format!("extension-host [{}]", index + 1))).collect();
    let screen_reader = crate::workbench::accessibility::screen_reader_running();
    crate::diagnostics::MainDiagnostics { main_pid, main_arguments: std::env::args().skip(1).collect(), windows, pid_to_names, screen_reader }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_windows_pipe_is_named_from_the_user_data_hash_as_create_static_ipc_handle() {
        // Node: createHash('sha256').update('C:\\Users\\Ann\\AppData\\Roaming\\VSRustium').digest('hex').substr(0, 8)
        let name = windows_pipe_name(Path::new(r"C:\Users\Ann\AppData\Roaming\VSRustium"), "1.147.0");
        assert_eq!(name, PathBuf::from(r"\\.\pipe\8c531f1c-1.147.0-main-sock"));
    }

    #[test]
    fn a_second_instance_hands_its_arguments_to_the_first() {
        let dir = std::env::temp_dir().join(format!("vsrustium-launch-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let socket = socket_path(&dir);
        assert!(!send_to_running_instance(&socket, &[], &dir), "nothing listens yet");
        #[cfg(unix)]
        {
            std::fs::write(&socket, "").unwrap();
            assert!(!send_to_running_instance(&socket, &[], &dir));
            assert!(!socket.exists(), "a stale socket file is removed");
        }
        let mut launches = listen(&socket).unwrap();
        let args = vec!["vsrustium".to_owned(), "folder".to_owned()];
        assert!(send_to_running_instance(&socket, &args, Path::new("/tmp")));
        let Some(Launch::Open { args: sent, cwd, .. }) = futures::executor::block_on(launches.next()) else { panic!("an open launch") };
        assert_eq!((sent, cwd), (args, PathBuf::from("/tmp")));
        let request = std::thread::spawn({
            let socket = socket.clone();
            move || request_main_diagnostics(&socket)
        });
        let Some(Launch::Status(reply)) = futures::executor::block_on(launches.next()) else { panic!("a status request") };
        reply.send(crate::diagnostics::MainDiagnostics { main_pid: 7, ..Default::default() }).unwrap();
        assert_eq!(request.join().unwrap().map(|info| info.main_pid), Some(7));
        std::fs::remove_dir_all(&dir).unwrap();
    }
}