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