main.rs

   1#![cfg_attr(
   2    any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
   3    allow(dead_code)
   4)]
   5
   6use anyhow::{Context as _, Result};
   7use clap::Parser;
   8use cli::{CliRequest, CliResponse, IpcHandshake, ipc::IpcOneShotServer};
   9use parking_lot::Mutex;
  10use std::{
  11    env, fs, io,
  12    path::{Path, PathBuf},
  13    process::ExitStatus,
  14    sync::Arc,
  15    thread::{self, JoinHandle},
  16};
  17use tempfile::NamedTempFile;
  18use util::paths::PathWithPosition;
  19
  20#[cfg(any(target_os = "linux", target_os = "freebsd"))]
  21use std::io::IsTerminal;
  22
  23struct Detect;
  24
  25trait InstalledApp {
  26    fn zed_version_string(&self) -> String;
  27    fn launch(&self, ipc_url: String) -> anyhow::Result<()>;
  28    fn run_foreground(
  29        &self,
  30        ipc_url: String,
  31        user_data_dir: Option<&str>,
  32    ) -> io::Result<ExitStatus>;
  33    fn path(&self) -> PathBuf;
  34}
  35
  36#[derive(Parser, Debug)]
  37#[command(
  38    name = "zed",
  39    disable_version_flag = true,
  40    before_help = "The Zed CLI binary.
  41This CLI is a separate binary that invokes Zed.
  42
  43Examples:
  44    `zed`
  45          Simply opens Zed
  46    `zed --foreground`
  47          Runs in foreground (shows all logs)
  48    `zed path-to-your-project`
  49          Open your project in Zed
  50    `zed -n path-to-file `
  51          Open file/folder in a new window",
  52    after_help = "To read from stdin, append '-', e.g. 'ps axf | zed -'"
  53)]
  54struct Args {
  55    /// Wait for all of the given paths to be opened/closed before exiting.
  56    #[arg(short, long)]
  57    wait: bool,
  58    /// Add files to the currently open workspace
  59    #[arg(short, long, overrides_with = "new")]
  60    add: bool,
  61    /// Create a new workspace
  62    #[arg(short, long, overrides_with = "add")]
  63    new: bool,
  64    /// Sets a custom directory for all user data (e.g., database, extensions, logs).
  65    /// This overrides the default platform-specific data directory location.
  66    /// On macOS, the default is `~/Library/Application Support/Zed`.
  67    /// On Linux/FreeBSD, the default is `$XDG_DATA_HOME/zed`.
  68    /// On Windows, the default is `%LOCALAPPDATA%\Zed`.
  69    #[arg(long, value_name = "DIR")]
  70    user_data_dir: Option<String>,
  71    /// The paths to open in Zed (space-separated).
  72    ///
  73    /// Use `path:line:column` syntax to open a file at the given line and column.
  74    paths_with_position: Vec<String>,
  75    /// Print Zed's version and the app path.
  76    #[arg(short, long)]
  77    version: bool,
  78    /// Run zed in the foreground (useful for debugging)
  79    #[arg(long)]
  80    foreground: bool,
  81    /// Custom path to Zed.app or the zed binary
  82    #[arg(long)]
  83    zed: Option<PathBuf>,
  84    /// Run zed in dev-server mode
  85    #[arg(long)]
  86    dev_server_token: Option<String>,
  87    /// The username and WSL distribution to use when opening paths. If not specified,
  88    /// Zed will attempt to open the paths directly.
  89    ///
  90    /// The username is optional, and if not specified, the default user for the distribution
  91    /// will be used.
  92    ///
  93    /// Example: `me@Ubuntu` or `Ubuntu`.
  94    ///
  95    /// WARN: You should not fill in this field by hand.
  96    #[arg(long, value_name = "USER@DISTRO")]
  97    wsl: Option<String>,
  98    /// Not supported in Zed CLI, only supported on Zed binary
  99    /// Will attempt to give the correct command to run
 100    #[arg(long)]
 101    system_specs: bool,
 102    /// Pairs of file paths to diff. Can be specified multiple times.
 103    #[arg(long, action = clap::ArgAction::Append, num_args = 2, value_names = ["OLD_PATH", "NEW_PATH"])]
 104    diff: Vec<String>,
 105    /// Uninstall Zed from user system
 106    #[cfg(all(
 107        any(target_os = "linux", target_os = "macos"),
 108        not(feature = "no-bundled-uninstall")
 109    ))]
 110    #[arg(long)]
 111    uninstall: bool,
 112}
 113
 114fn parse_path_with_position(argument_str: &str) -> anyhow::Result<String> {
 115    let canonicalized = match Path::new(argument_str).canonicalize() {
 116        Ok(existing_path) => PathWithPosition::from_path(existing_path),
 117        Err(_) => {
 118            let path = PathWithPosition::parse_str(argument_str);
 119            let curdir = env::current_dir().context("retrieving current directory")?;
 120            path.map_path(|path| match fs::canonicalize(&path) {
 121                Ok(path) => Ok(path),
 122                Err(e) => {
 123                    if let Some(mut parent) = path.parent() {
 124                        if parent == Path::new("") {
 125                            parent = &curdir
 126                        }
 127                        match fs::canonicalize(parent) {
 128                            Ok(parent) => Ok(parent.join(path.file_name().unwrap())),
 129                            Err(_) => Err(e),
 130                        }
 131                    } else {
 132                        Err(e)
 133                    }
 134                }
 135            })
 136        }
 137        .with_context(|| format!("parsing as path with position {argument_str}"))?,
 138    };
 139    Ok(canonicalized.to_string(|path| path.to_string_lossy().to_string()))
 140}
 141
 142fn parse_path_in_wsl(source: &str, wsl: &str) -> Result<String> {
 143    let mut command = util::command::new_std_command("wsl.exe");
 144
 145    let (user, distro_name) = if let Some((user, distro)) = wsl.split_once('@') {
 146        if user.is_empty() {
 147            anyhow::bail!("user is empty in wsl argument");
 148        }
 149        (Some(user), distro)
 150    } else {
 151        (None, wsl)
 152    };
 153
 154    if let Some(user) = user {
 155        command.arg("--user").arg(user);
 156    }
 157
 158    let output = command
 159        .arg("--distribution")
 160        .arg(distro_name)
 161        .arg("wslpath")
 162        .arg("-m")
 163        .arg(source)
 164        .output()?;
 165
 166    let result = String::from_utf8_lossy(&output.stdout);
 167    let prefix = format!("//wsl.localhost/{}", distro_name);
 168
 169    Ok(result
 170        .trim()
 171        .strip_prefix(&prefix)
 172        .unwrap_or(&result)
 173        .to_string())
 174}
 175
 176fn main() -> Result<()> {
 177    #[cfg(unix)]
 178    util::prevent_root_execution();
 179
 180    // Exit flatpak sandbox if needed
 181    #[cfg(target_os = "linux")]
 182    {
 183        flatpak::try_restart_to_host();
 184        flatpak::ld_extra_libs();
 185    }
 186
 187    // Intercept version designators
 188    #[cfg(target_os = "macos")]
 189    if let Some(channel) = std::env::args().nth(1).filter(|arg| arg.starts_with("--")) {
 190        // When the first argument is a name of a release channel, we're going to spawn off the CLI of that version, with trailing args passed along.
 191        use std::str::FromStr as _;
 192
 193        if let Ok(channel) = release_channel::ReleaseChannel::from_str(&channel[2..]) {
 194            return mac_os::spawn_channel_cli(channel, std::env::args().skip(2).collect());
 195        }
 196    }
 197    let args = Args::parse();
 198
 199    // Set custom data directory before any path operations
 200    let user_data_dir = args.user_data_dir.clone();
 201    if let Some(dir) = &user_data_dir {
 202        paths::set_custom_data_dir(dir);
 203    }
 204
 205    #[cfg(target_os = "linux")]
 206    let args = flatpak::set_bin_if_no_escape(args);
 207
 208    let app = Detect::detect(args.zed.as_deref()).context("Bundle detection")?;
 209
 210    if args.version {
 211        println!("{}", app.zed_version_string());
 212        return Ok(());
 213    }
 214
 215    if args.system_specs {
 216        let path = app.path();
 217        let msg = [
 218            "The `--system-specs` argument is not supported in the Zed CLI, only on Zed binary.",
 219            "To retrieve the system specs on the command line, run the following command:",
 220            &format!("{} --system-specs", path.display()),
 221        ];
 222        anyhow::bail!(msg.join("\n"));
 223    }
 224
 225    #[cfg(all(
 226        any(target_os = "linux", target_os = "macos"),
 227        not(feature = "no-bundled-uninstall")
 228    ))]
 229    if args.uninstall {
 230        static UNINSTALL_SCRIPT: &[u8] = include_bytes!("../../../script/uninstall.sh");
 231
 232        let tmp_dir = tempfile::tempdir()?;
 233        let script_path = tmp_dir.path().join("uninstall.sh");
 234        fs::write(&script_path, UNINSTALL_SCRIPT)?;
 235
 236        use std::os::unix::fs::PermissionsExt as _;
 237        fs::set_permissions(&script_path, fs::Permissions::from_mode(0o755))?;
 238
 239        let status = std::process::Command::new("sh")
 240            .arg(&script_path)
 241            .env("ZED_CHANNEL", &*release_channel::RELEASE_CHANNEL_NAME)
 242            .status()
 243            .context("Failed to execute uninstall script")?;
 244
 245        std::process::exit(status.code().unwrap_or(1));
 246    }
 247
 248    let (server, server_name) =
 249        IpcOneShotServer::<IpcHandshake>::new().context("Handshake before Zed spawn")?;
 250    let url = format!("zed-cli://{server_name}");
 251
 252    let open_new_workspace = if args.new {
 253        Some(true)
 254    } else if args.add {
 255        Some(false)
 256    } else {
 257        None
 258    };
 259
 260    let env = {
 261        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 262        {
 263            use collections::HashMap;
 264
 265            // On Linux, the desktop entry uses `cli` to spawn `zed`.
 266            // We need to handle env vars correctly since std::env::vars() may not contain
 267            // project-specific vars (e.g. those set by direnv).
 268            // By setting env to None here, the LSP will use worktree env vars instead,
 269            // which is what we want.
 270            if !std::io::stdout().is_terminal() {
 271                None
 272            } else {
 273                Some(std::env::vars().collect::<HashMap<_, _>>())
 274            }
 275        }
 276
 277        #[cfg(target_os = "windows")]
 278        {
 279            // On Windows, by default, a child process inherits a copy of the environment block of the parent process.
 280            // So we don't need to pass env vars explicitly.
 281            None
 282        }
 283
 284        #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
 285        {
 286            use collections::HashMap;
 287
 288            Some(std::env::vars().collect::<HashMap<_, _>>())
 289        }
 290    };
 291
 292    let exit_status = Arc::new(Mutex::new(None));
 293    let mut paths = vec![];
 294    let mut urls = vec![];
 295    let mut diff_paths = vec![];
 296    let mut stdin_tmp_file: Option<fs::File> = None;
 297    let mut anonymous_fd_tmp_files = vec![];
 298
 299    for path in args.diff.chunks(2) {
 300        diff_paths.push([
 301            parse_path_with_position(&path[0])?,
 302            parse_path_with_position(&path[1])?,
 303        ]);
 304    }
 305
 306    for path in args.paths_with_position.iter() {
 307        if path.starts_with("zed://")
 308            || path.starts_with("http://")
 309            || path.starts_with("https://")
 310            || path.starts_with("file://")
 311            || path.starts_with("ssh://")
 312        {
 313            urls.push(path.to_string());
 314        } else if path == "-" && args.paths_with_position.len() == 1 {
 315            let file = NamedTempFile::new()?;
 316            paths.push(file.path().to_string_lossy().to_string());
 317            let (file, _) = file.keep()?;
 318            stdin_tmp_file = Some(file);
 319        } else if let Some(file) = anonymous_fd(path) {
 320            let tmp_file = NamedTempFile::new()?;
 321            paths.push(tmp_file.path().to_string_lossy().to_string());
 322            let (tmp_file, _) = tmp_file.keep()?;
 323            anonymous_fd_tmp_files.push((file, tmp_file));
 324        } else if let Some(wsl) = &args.wsl {
 325            urls.push(format!("file://{}", parse_path_in_wsl(path, wsl)?));
 326        } else {
 327            paths.push(parse_path_with_position(path)?);
 328        }
 329    }
 330
 331    anyhow::ensure!(
 332        args.dev_server_token.is_none(),
 333        "Dev servers were removed in v0.157.x please upgrade to SSH remoting: https://zed.dev/docs/remote-development"
 334    );
 335
 336    let sender: JoinHandle<anyhow::Result<()>> = thread::spawn({
 337        let exit_status = exit_status.clone();
 338        let user_data_dir_for_thread = user_data_dir.clone();
 339        move || {
 340            let (_, handshake) = server.accept().context("Handshake after Zed spawn")?;
 341            let (tx, rx) = (handshake.requests, handshake.responses);
 342
 343            tx.send(CliRequest::Open {
 344                paths,
 345                urls,
 346                diff_paths,
 347                wsl: args.wsl,
 348                wait: args.wait,
 349                open_new_workspace,
 350                env,
 351                user_data_dir: user_data_dir_for_thread,
 352            })?;
 353
 354            while let Ok(response) = rx.recv() {
 355                match response {
 356                    CliResponse::Ping => {}
 357                    CliResponse::Stdout { message } => println!("{message}"),
 358                    CliResponse::Stderr { message } => eprintln!("{message}"),
 359                    CliResponse::Exit { status } => {
 360                        exit_status.lock().replace(status);
 361                        return Ok(());
 362                    }
 363                }
 364            }
 365
 366            Ok(())
 367        }
 368    });
 369
 370    let stdin_pipe_handle: Option<JoinHandle<anyhow::Result<()>>> =
 371        stdin_tmp_file.map(|mut tmp_file| {
 372            thread::spawn(move || {
 373                let mut stdin = std::io::stdin().lock();
 374                if !io::IsTerminal::is_terminal(&stdin) {
 375                    io::copy(&mut stdin, &mut tmp_file)?;
 376                }
 377                Ok(())
 378            })
 379        });
 380
 381    let anonymous_fd_pipe_handles: Vec<_> = anonymous_fd_tmp_files
 382        .into_iter()
 383        .map(|(mut file, mut tmp_file)| thread::spawn(move || io::copy(&mut file, &mut tmp_file)))
 384        .collect();
 385
 386    if args.foreground {
 387        app.run_foreground(url, user_data_dir.as_deref())?;
 388    } else {
 389        app.launch(url)?;
 390        sender.join().unwrap()?;
 391        if let Some(handle) = stdin_pipe_handle {
 392            handle.join().unwrap()?;
 393        }
 394        for handle in anonymous_fd_pipe_handles {
 395            handle.join().unwrap()?;
 396        }
 397    }
 398
 399    if let Some(exit_status) = exit_status.lock().take() {
 400        std::process::exit(exit_status);
 401    }
 402    Ok(())
 403}
 404
 405fn anonymous_fd(path: &str) -> Option<fs::File> {
 406    #[cfg(target_os = "linux")]
 407    {
 408        use std::os::fd::{self, FromRawFd};
 409
 410        let fd_str = path.strip_prefix("/proc/self/fd/")?;
 411
 412        let link = fs::read_link(path).ok()?;
 413        if !link.starts_with("memfd:") {
 414            return None;
 415        }
 416
 417        let fd: fd::RawFd = fd_str.parse().ok()?;
 418        let file = unsafe { fs::File::from_raw_fd(fd) };
 419        Some(file)
 420    }
 421    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
 422    {
 423        use std::os::{
 424            fd::{self, FromRawFd},
 425            unix::fs::FileTypeExt,
 426        };
 427
 428        let fd_str = path.strip_prefix("/dev/fd/")?;
 429
 430        let metadata = fs::metadata(path).ok()?;
 431        let file_type = metadata.file_type();
 432        if !file_type.is_fifo() && !file_type.is_socket() {
 433            return None;
 434        }
 435        let fd: fd::RawFd = fd_str.parse().ok()?;
 436        let file = unsafe { fs::File::from_raw_fd(fd) };
 437        Some(file)
 438    }
 439    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "freebsd")))]
 440    {
 441        _ = path;
 442        // not implemented for bsd, windows. Could be, but isn't yet
 443        None
 444    }
 445}
 446
 447#[cfg(any(target_os = "linux", target_os = "freebsd"))]
 448mod linux {
 449    use std::{
 450        env,
 451        ffi::OsString,
 452        io,
 453        os::unix::net::{SocketAddr, UnixDatagram},
 454        path::{Path, PathBuf},
 455        process::{self, ExitStatus},
 456        thread,
 457        time::Duration,
 458    };
 459
 460    use anyhow::{Context as _, anyhow};
 461    use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
 462    use fork::Fork;
 463
 464    use crate::{Detect, InstalledApp};
 465
 466    struct App(PathBuf);
 467
 468    impl Detect {
 469        pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
 470            let path = if let Some(path) = path {
 471                path.to_path_buf().canonicalize()?
 472            } else {
 473                let cli = env::current_exe()?;
 474                let dir = cli.parent().context("no parent path for cli")?;
 475
 476                // libexec is the standard, lib/zed is for Arch (and other non-libexec distros),
 477                // ./zed is for the target directory in development builds.
 478                let possible_locations =
 479                    ["../libexec/zed-editor", "../lib/zed/zed-editor", "./zed"];
 480                possible_locations
 481                    .iter()
 482                    .find_map(|p| dir.join(p).canonicalize().ok().filter(|path| path != &cli))
 483                    .with_context(|| {
 484                        format!("could not find any of: {}", possible_locations.join(", "))
 485                    })?
 486            };
 487
 488            Ok(App(path))
 489        }
 490    }
 491
 492    impl InstalledApp for App {
 493        fn zed_version_string(&self) -> String {
 494            format!(
 495                "Zed {}{}{}{}",
 496                if *release_channel::RELEASE_CHANNEL_NAME == "stable" {
 497                    "".to_string()
 498                } else {
 499                    format!("{} ", *release_channel::RELEASE_CHANNEL_NAME)
 500                },
 501                option_env!("RELEASE_VERSION").unwrap_or_default(),
 502                match option_env!("ZED_COMMIT_SHA") {
 503                    Some(commit_sha) => format!(" {commit_sha} "),
 504                    None => "".to_string(),
 505                },
 506                self.0.display(),
 507            )
 508        }
 509
 510        fn launch(&self, ipc_url: String) -> anyhow::Result<()> {
 511            let sock_path = paths::data_dir().join(format!(
 512                "zed-{}.sock",
 513                *release_channel::RELEASE_CHANNEL_NAME
 514            ));
 515            let sock = UnixDatagram::unbound()?;
 516            if sock.connect(&sock_path).is_err() {
 517                self.boot_background(ipc_url)?;
 518            } else {
 519                sock.send(ipc_url.as_bytes())?;
 520            }
 521            Ok(())
 522        }
 523
 524        fn run_foreground(
 525            &self,
 526            ipc_url: String,
 527            user_data_dir: Option<&str>,
 528        ) -> io::Result<ExitStatus> {
 529            let mut cmd = std::process::Command::new(self.0.clone());
 530            cmd.arg(ipc_url);
 531            if let Some(dir) = user_data_dir {
 532                cmd.arg("--user-data-dir").arg(dir);
 533            }
 534            cmd.status()
 535        }
 536
 537        fn path(&self) -> PathBuf {
 538            self.0.clone()
 539        }
 540    }
 541
 542    impl App {
 543        fn boot_background(&self, ipc_url: String) -> anyhow::Result<()> {
 544            let path = &self.0;
 545
 546            match fork::fork() {
 547                Ok(Fork::Parent(_)) => Ok(()),
 548                Ok(Fork::Child) => {
 549                    unsafe { std::env::set_var(FORCE_CLI_MODE_ENV_VAR_NAME, "") };
 550                    if fork::setsid().is_err() {
 551                        eprintln!("failed to setsid: {}", std::io::Error::last_os_error());
 552                        process::exit(1);
 553                    }
 554                    if fork::close_fd().is_err() {
 555                        eprintln!("failed to close_fd: {}", std::io::Error::last_os_error());
 556                    }
 557                    let error =
 558                        exec::execvp(path.clone(), &[path.as_os_str(), &OsString::from(ipc_url)]);
 559                    // if exec succeeded, we never get here.
 560                    eprintln!("failed to exec {:?}: {}", path, error);
 561                    process::exit(1)
 562                }
 563                Err(_) => Err(anyhow!(io::Error::last_os_error())),
 564            }
 565        }
 566
 567        fn wait_for_socket(
 568            &self,
 569            sock_addr: &SocketAddr,
 570            sock: &mut UnixDatagram,
 571        ) -> Result<(), std::io::Error> {
 572            for _ in 0..100 {
 573                thread::sleep(Duration::from_millis(10));
 574                if sock.connect_addr(sock_addr).is_ok() {
 575                    return Ok(());
 576                }
 577            }
 578            sock.connect_addr(sock_addr)
 579        }
 580    }
 581}
 582
 583#[cfg(target_os = "linux")]
 584mod flatpak {
 585    use std::ffi::OsString;
 586    use std::path::PathBuf;
 587    use std::process::Command;
 588    use std::{env, process};
 589
 590    const EXTRA_LIB_ENV_NAME: &str = "ZED_FLATPAK_LIB_PATH";
 591    const NO_ESCAPE_ENV_NAME: &str = "ZED_FLATPAK_NO_ESCAPE";
 592
 593    /// Adds bundled libraries to LD_LIBRARY_PATH if running under flatpak
 594    pub fn ld_extra_libs() {
 595        let mut paths = if let Ok(paths) = env::var("LD_LIBRARY_PATH") {
 596            env::split_paths(&paths).collect()
 597        } else {
 598            Vec::new()
 599        };
 600
 601        if let Ok(extra_path) = env::var(EXTRA_LIB_ENV_NAME) {
 602            paths.push(extra_path.into());
 603        }
 604
 605        unsafe { env::set_var("LD_LIBRARY_PATH", env::join_paths(paths).unwrap()) };
 606    }
 607
 608    /// Restarts outside of the sandbox if currently running within it
 609    pub fn try_restart_to_host() {
 610        if let Some(flatpak_dir) = get_flatpak_dir() {
 611            let mut args = vec!["/usr/bin/flatpak-spawn".into(), "--host".into()];
 612            args.append(&mut get_xdg_env_args());
 613            args.push("--env=ZED_UPDATE_EXPLANATION=Please use flatpak to update zed".into());
 614            args.push(
 615                format!(
 616                    "--env={EXTRA_LIB_ENV_NAME}={}",
 617                    flatpak_dir.join("lib").to_str().unwrap()
 618                )
 619                .into(),
 620            );
 621            args.push(flatpak_dir.join("bin").join("zed").into());
 622
 623            let mut is_app_location_set = false;
 624            for arg in &env::args_os().collect::<Vec<_>>()[1..] {
 625                args.push(arg.clone());
 626                is_app_location_set |= arg == "--zed";
 627            }
 628
 629            if !is_app_location_set {
 630                args.push("--zed".into());
 631                args.push(flatpak_dir.join("libexec").join("zed-editor").into());
 632            }
 633
 634            let error = exec::execvp("/usr/bin/flatpak-spawn", args);
 635            eprintln!("failed restart cli on host: {:?}", error);
 636            process::exit(1);
 637        }
 638    }
 639
 640    pub fn set_bin_if_no_escape(mut args: super::Args) -> super::Args {
 641        if env::var(NO_ESCAPE_ENV_NAME).is_ok()
 642            && env::var("FLATPAK_ID").is_ok_and(|id| id.starts_with("dev.zed.Zed"))
 643            && args.zed.is_none()
 644        {
 645            args.zed = Some("/app/libexec/zed-editor".into());
 646            unsafe { env::set_var("ZED_UPDATE_EXPLANATION", "Please use flatpak to update zed") };
 647        }
 648        args
 649    }
 650
 651    fn get_flatpak_dir() -> Option<PathBuf> {
 652        if env::var(NO_ESCAPE_ENV_NAME).is_ok() {
 653            return None;
 654        }
 655
 656        if let Ok(flatpak_id) = env::var("FLATPAK_ID") {
 657            if !flatpak_id.starts_with("dev.zed.Zed") {
 658                return None;
 659            }
 660
 661            let install_dir = Command::new("/usr/bin/flatpak-spawn")
 662                .arg("--host")
 663                .arg("flatpak")
 664                .arg("info")
 665                .arg("--show-location")
 666                .arg(flatpak_id)
 667                .output()
 668                .unwrap();
 669            let install_dir = PathBuf::from(String::from_utf8(install_dir.stdout).unwrap().trim());
 670            Some(install_dir.join("files"))
 671        } else {
 672            None
 673        }
 674    }
 675
 676    fn get_xdg_env_args() -> Vec<OsString> {
 677        let xdg_keys = [
 678            "XDG_DATA_HOME",
 679            "XDG_CONFIG_HOME",
 680            "XDG_CACHE_HOME",
 681            "XDG_STATE_HOME",
 682        ];
 683        env::vars()
 684            .filter(|(key, _)| xdg_keys.contains(&key.as_str()))
 685            .map(|(key, val)| format!("--env=FLATPAK_{}={}", key, val).into())
 686            .collect()
 687    }
 688}
 689
 690#[cfg(target_os = "windows")]
 691mod windows {
 692    use anyhow::Context;
 693    use release_channel::app_identifier;
 694    use windows::{
 695        Win32::{
 696            Foundation::{CloseHandle, ERROR_ALREADY_EXISTS, GENERIC_WRITE, GetLastError},
 697            Storage::FileSystem::{
 698                CreateFileW, FILE_FLAGS_AND_ATTRIBUTES, FILE_SHARE_MODE, OPEN_EXISTING, WriteFile,
 699            },
 700            System::Threading::{CREATE_NEW_PROCESS_GROUP, CreateMutexW},
 701        },
 702        core::HSTRING,
 703    };
 704
 705    use crate::{Detect, InstalledApp};
 706    use std::path::{Path, PathBuf};
 707    use std::process::ExitStatus;
 708    use std::{io, os::windows::process::CommandExt};
 709
 710    fn check_single_instance() -> bool {
 711        let mutex = unsafe {
 712            CreateMutexW(
 713                None,
 714                false,
 715                &HSTRING::from(format!("{}-Instance-Mutex", app_identifier())),
 716            )
 717            .expect("Unable to create instance sync event")
 718        };
 719        let last_err = unsafe { GetLastError() };
 720        let _ = unsafe { CloseHandle(mutex) };
 721        last_err != ERROR_ALREADY_EXISTS
 722    }
 723
 724    struct App(PathBuf);
 725
 726    impl InstalledApp for App {
 727        fn zed_version_string(&self) -> String {
 728            format!(
 729                "Zed {}{}{}{}",
 730                if *release_channel::RELEASE_CHANNEL_NAME == "stable" {
 731                    "".to_string()
 732                } else {
 733                    format!("{} ", *release_channel::RELEASE_CHANNEL_NAME)
 734                },
 735                option_env!("RELEASE_VERSION").unwrap_or_default(),
 736                match option_env!("ZED_COMMIT_SHA") {
 737                    Some(commit_sha) => format!(" {commit_sha} "),
 738                    None => "".to_string(),
 739                },
 740                self.0.display(),
 741            )
 742        }
 743
 744        fn launch(&self, ipc_url: String) -> anyhow::Result<()> {
 745            if check_single_instance() {
 746                std::process::Command::new(self.0.clone())
 747                    .creation_flags(CREATE_NEW_PROCESS_GROUP.0)
 748                    .arg(ipc_url)
 749                    .spawn()?;
 750            } else {
 751                unsafe {
 752                    let pipe = CreateFileW(
 753                        &HSTRING::from(format!("\\\\.\\pipe\\{}-Named-Pipe", app_identifier())),
 754                        GENERIC_WRITE.0,
 755                        FILE_SHARE_MODE::default(),
 756                        None,
 757                        OPEN_EXISTING,
 758                        FILE_FLAGS_AND_ATTRIBUTES::default(),
 759                        None,
 760                    )?;
 761                    let message = ipc_url.as_bytes();
 762                    let mut bytes_written = 0;
 763                    WriteFile(pipe, Some(message), Some(&mut bytes_written), None)?;
 764                    CloseHandle(pipe)?;
 765                }
 766            }
 767            Ok(())
 768        }
 769
 770        fn run_foreground(
 771            &self,
 772            ipc_url: String,
 773            user_data_dir: Option<&str>,
 774        ) -> io::Result<ExitStatus> {
 775            let mut cmd = std::process::Command::new(self.0.clone());
 776            cmd.arg(ipc_url).arg("--foreground");
 777            if let Some(dir) = user_data_dir {
 778                cmd.arg("--user-data-dir").arg(dir);
 779            }
 780            cmd.spawn()?.wait()
 781        }
 782
 783        fn path(&self) -> PathBuf {
 784            self.0.clone()
 785        }
 786    }
 787
 788    impl Detect {
 789        pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
 790            let path = if let Some(path) = path {
 791                path.to_path_buf().canonicalize()?
 792            } else {
 793                let cli = std::env::current_exe()?;
 794                let dir = cli.parent().context("no parent path for cli")?;
 795
 796                // ../Zed.exe is the standard, lib/zed is for MSYS2, ./zed.exe is for the target
 797                // directory in development builds.
 798                let possible_locations = ["../Zed.exe", "../lib/zed/zed-editor.exe", "./zed.exe"];
 799                possible_locations
 800                    .iter()
 801                    .find_map(|p| dir.join(p).canonicalize().ok().filter(|path| path != &cli))
 802                    .context(format!(
 803                        "could not find any of: {}",
 804                        possible_locations.join(", ")
 805                    ))?
 806            };
 807
 808            Ok(App(path))
 809        }
 810    }
 811}
 812
 813#[cfg(target_os = "macos")]
 814mod mac_os {
 815    use anyhow::{Context as _, Result};
 816    use core_foundation::{
 817        array::{CFArray, CFIndex},
 818        base::TCFType as _,
 819        string::kCFStringEncodingUTF8,
 820        url::{CFURL, CFURLCreateWithBytes},
 821    };
 822    use core_services::{LSLaunchURLSpec, LSOpenFromURLSpec, kLSLaunchDefaults};
 823    use serde::Deserialize;
 824    use std::{
 825        ffi::OsStr,
 826        fs, io,
 827        path::{Path, PathBuf},
 828        process::{Command, ExitStatus},
 829        ptr,
 830    };
 831
 832    use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
 833
 834    use crate::{Detect, InstalledApp};
 835
 836    #[derive(Debug, Deserialize)]
 837    struct InfoPlist {
 838        #[serde(rename = "CFBundleShortVersionString")]
 839        bundle_short_version_string: String,
 840    }
 841
 842    enum Bundle {
 843        App {
 844            app_bundle: PathBuf,
 845            plist: InfoPlist,
 846        },
 847        LocalPath {
 848            executable: PathBuf,
 849        },
 850    }
 851
 852    fn locate_bundle() -> Result<PathBuf> {
 853        let cli_path = std::env::current_exe()?.canonicalize()?;
 854        let mut app_path = cli_path.clone();
 855        while app_path.extension() != Some(OsStr::new("app")) {
 856            anyhow::ensure!(
 857                app_path.pop(),
 858                "cannot find app bundle containing {cli_path:?}"
 859            );
 860        }
 861        Ok(app_path)
 862    }
 863
 864    impl Detect {
 865        pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
 866            let bundle_path = if let Some(bundle_path) = path {
 867                bundle_path
 868                    .canonicalize()
 869                    .with_context(|| format!("Args bundle path {bundle_path:?} canonicalization"))?
 870            } else {
 871                locate_bundle().context("bundle autodiscovery")?
 872            };
 873
 874            match bundle_path.extension().and_then(|ext| ext.to_str()) {
 875                Some("app") => {
 876                    let plist_path = bundle_path.join("Contents/Info.plist");
 877                    let plist =
 878                        plist::from_file::<_, InfoPlist>(&plist_path).with_context(|| {
 879                            format!("Reading *.app bundle plist file at {plist_path:?}")
 880                        })?;
 881                    Ok(Bundle::App {
 882                        app_bundle: bundle_path,
 883                        plist,
 884                    })
 885                }
 886                _ => Ok(Bundle::LocalPath {
 887                    executable: bundle_path,
 888                }),
 889            }
 890        }
 891    }
 892
 893    impl InstalledApp for Bundle {
 894        fn zed_version_string(&self) -> String {
 895            format!("Zed {}{}", self.version(), self.path().display(),)
 896        }
 897
 898        fn launch(&self, url: String) -> anyhow::Result<()> {
 899            match self {
 900                Self::App { app_bundle, .. } => {
 901                    let app_path = app_bundle;
 902
 903                    let status = unsafe {
 904                        let app_url = CFURL::from_path(app_path, true)
 905                            .with_context(|| format!("invalid app path {app_path:?}"))?;
 906                        let url_to_open = CFURL::wrap_under_create_rule(CFURLCreateWithBytes(
 907                            ptr::null(),
 908                            url.as_ptr(),
 909                            url.len() as CFIndex,
 910                            kCFStringEncodingUTF8,
 911                            ptr::null(),
 912                        ));
 913                        // equivalent to: open zed-cli:... -a /Applications/Zed\ Preview.app
 914                        let urls_to_open =
 915                            CFArray::from_copyable(&[url_to_open.as_concrete_TypeRef()]);
 916                        LSOpenFromURLSpec(
 917                            &LSLaunchURLSpec {
 918                                appURL: app_url.as_concrete_TypeRef(),
 919                                itemURLs: urls_to_open.as_concrete_TypeRef(),
 920                                passThruParams: ptr::null(),
 921                                launchFlags: kLSLaunchDefaults,
 922                                asyncRefCon: ptr::null_mut(),
 923                            },
 924                            ptr::null_mut(),
 925                        )
 926                    };
 927
 928                    anyhow::ensure!(
 929                        status == 0,
 930                        "cannot start app bundle {}",
 931                        self.zed_version_string()
 932                    );
 933                }
 934
 935                Self::LocalPath { executable, .. } => {
 936                    let executable_parent = executable
 937                        .parent()
 938                        .with_context(|| format!("Executable {executable:?} path has no parent"))?;
 939                    let subprocess_stdout_file = fs::File::create(
 940                        executable_parent.join("zed_dev.log"),
 941                    )
 942                    .with_context(|| format!("Log file creation in {executable_parent:?}"))?;
 943                    let subprocess_stdin_file =
 944                        subprocess_stdout_file.try_clone().with_context(|| {
 945                            format!("Cloning descriptor for file {subprocess_stdout_file:?}")
 946                        })?;
 947                    let mut command = std::process::Command::new(executable);
 948                    let command = command
 949                        .env(FORCE_CLI_MODE_ENV_VAR_NAME, "")
 950                        .stderr(subprocess_stdout_file)
 951                        .stdout(subprocess_stdin_file)
 952                        .arg(url);
 953
 954                    command
 955                        .spawn()
 956                        .with_context(|| format!("Spawning {command:?}"))?;
 957                }
 958            }
 959
 960            Ok(())
 961        }
 962
 963        fn run_foreground(
 964            &self,
 965            ipc_url: String,
 966            user_data_dir: Option<&str>,
 967        ) -> io::Result<ExitStatus> {
 968            let path = match self {
 969                Bundle::App { app_bundle, .. } => app_bundle.join("Contents/MacOS/zed"),
 970                Bundle::LocalPath { executable, .. } => executable.clone(),
 971            };
 972
 973            let mut cmd = std::process::Command::new(path);
 974            cmd.arg(ipc_url);
 975            if let Some(dir) = user_data_dir {
 976                cmd.arg("--user-data-dir").arg(dir);
 977            }
 978            cmd.status()
 979        }
 980
 981        fn path(&self) -> PathBuf {
 982            match self {
 983                Bundle::App { app_bundle, .. } => app_bundle.join("Contents/MacOS/zed"),
 984                Bundle::LocalPath { executable, .. } => executable.clone(),
 985            }
 986        }
 987    }
 988
 989    impl Bundle {
 990        fn version(&self) -> String {
 991            match self {
 992                Self::App { plist, .. } => plist.bundle_short_version_string.clone(),
 993                Self::LocalPath { .. } => "<development>".to_string(),
 994            }
 995        }
 996
 997        fn path(&self) -> &Path {
 998            match self {
 999                Self::App { app_bundle, .. } => app_bundle,
1000                Self::LocalPath { executable, .. } => executable,
1001            }
1002        }
1003    }
1004
1005    pub(super) fn spawn_channel_cli(
1006        channel: release_channel::ReleaseChannel,
1007        leftover_args: Vec<String>,
1008    ) -> Result<()> {
1009        use anyhow::bail;
1010
1011        let app_path_prompt = format!(
1012            "POSIX path of (path to application \"{}\")",
1013            channel.display_name()
1014        );
1015        let app_path_output = Command::new("osascript")
1016            .arg("-e")
1017            .arg(&app_path_prompt)
1018            .output()?;
1019        if !app_path_output.status.success() {
1020            bail!(
1021                "Could not determine app path for {}",
1022                channel.display_name()
1023            );
1024        }
1025        let app_path = String::from_utf8(app_path_output.stdout)?.trim().to_owned();
1026        let cli_path = format!("{app_path}/Contents/MacOS/cli");
1027        Command::new(cli_path).args(leftover_args).spawn()?;
1028        Ok(())
1029    }
1030}