main.rs

  1#![cfg_attr(any(target_os = "linux", target_os = "windows"), allow(dead_code))]
  2
  3use anyhow::{Context, Result};
  4use clap::Parser;
  5use cli::{ipc::IpcOneShotServer, CliRequest, CliResponse, IpcHandshake};
  6use collections::HashMap;
  7use parking_lot::Mutex;
  8use std::{
  9    env, fs, io,
 10    path::{Path, PathBuf},
 11    process::ExitStatus,
 12    sync::Arc,
 13    thread::{self, JoinHandle},
 14};
 15use tempfile::NamedTempFile;
 16use util::paths::PathWithPosition;
 17
 18struct Detect;
 19
 20trait InstalledApp {
 21    fn zed_version_string(&self) -> String;
 22    fn launch(&self, ipc_url: String) -> anyhow::Result<()>;
 23    fn run_foreground(&self, ipc_url: String) -> io::Result<ExitStatus>;
 24}
 25
 26#[derive(Parser, Debug)]
 27#[command(
 28    name = "zed",
 29    disable_version_flag = true,
 30    after_help = "To read from stdin, append '-' (e.g. 'ps axf | zed -')"
 31)]
 32struct Args {
 33    /// Wait for all of the given paths to be opened/closed before exiting.
 34    #[arg(short, long)]
 35    wait: bool,
 36    /// Add files to the currently open workspace
 37    #[arg(short, long, overrides_with = "new")]
 38    add: bool,
 39    /// Create a new workspace
 40    #[arg(short, long, overrides_with = "add")]
 41    new: bool,
 42    /// A sequence of space-separated paths that you want to open.
 43    ///
 44    /// Use `path:line:row` syntax to open a file at a specific location.
 45    /// Non-existing paths and directories will ignore `:line:row` suffix.
 46    paths_with_position: Vec<String>,
 47    /// Print Zed's version and the app path.
 48    #[arg(short, long)]
 49    version: bool,
 50    /// Run zed in the foreground (useful for debugging)
 51    #[arg(long)]
 52    foreground: bool,
 53    /// Custom path to Zed.app or the zed binary
 54    #[arg(long)]
 55    zed: Option<PathBuf>,
 56    /// Run zed in dev-server mode
 57    #[arg(long)]
 58    dev_server_token: Option<String>,
 59}
 60
 61fn parse_path_with_position(argument_str: &str) -> Result<String, std::io::Error> {
 62    let path = PathWithPosition::parse_str(argument_str);
 63    let curdir = env::current_dir()?;
 64
 65    let canonicalized = path.map_path(|path| match fs::canonicalize(&path) {
 66        Ok(path) => Ok(path),
 67        Err(e) => {
 68            if let Some(mut parent) = path.parent() {
 69                if parent == Path::new("") {
 70                    parent = &curdir
 71                }
 72                match fs::canonicalize(parent) {
 73                    Ok(parent) => Ok(parent.join(path.file_name().unwrap())),
 74                    Err(_) => Err(e),
 75                }
 76            } else {
 77                Err(e)
 78            }
 79        }
 80    })?;
 81    Ok(canonicalized.to_string(|path| path.display().to_string()))
 82}
 83
 84fn main() -> Result<()> {
 85    // Exit flatpak sandbox if needed
 86    #[cfg(target_os = "linux")]
 87    {
 88        flatpak::try_restart_to_host();
 89        flatpak::ld_extra_libs();
 90    }
 91
 92    // Intercept version designators
 93    #[cfg(target_os = "macos")]
 94    if let Some(channel) = std::env::args().nth(1).filter(|arg| arg.starts_with("--")) {
 95        // When the first argument is a name of a release channel, we're gonna spawn off a cli of that version, with trailing args passed along.
 96        use std::str::FromStr as _;
 97
 98        if let Ok(channel) = release_channel::ReleaseChannel::from_str(&channel[2..]) {
 99            return mac_os::spawn_channel_cli(channel, std::env::args().skip(2).collect());
100        }
101    }
102    let args = Args::parse();
103
104    #[cfg(target_os = "linux")]
105    let args = flatpak::set_bin_if_no_escape(args);
106
107    let app = Detect::detect(args.zed.as_deref()).context("Bundle detection")?;
108
109    if args.version {
110        println!("{}", app.zed_version_string());
111        return Ok(());
112    }
113
114    let (server, server_name) =
115        IpcOneShotServer::<IpcHandshake>::new().context("Handshake before Zed spawn")?;
116    let url = format!("zed-cli://{server_name}");
117
118    let open_new_workspace = if args.new {
119        Some(true)
120    } else if args.add {
121        Some(false)
122    } else {
123        None
124    };
125
126    let env = Some(std::env::vars().collect::<HashMap<_, _>>());
127    let exit_status = Arc::new(Mutex::new(None));
128    let mut paths = vec![];
129    let mut urls = vec![];
130    let mut stdin_tmp_file: Option<fs::File> = None;
131    for path in args.paths_with_position.iter() {
132        if path.starts_with("zed://")
133            || path.starts_with("http://")
134            || path.starts_with("https://")
135            || path.starts_with("file://")
136            || path.starts_with("ssh://")
137        {
138            urls.push(path.to_string());
139        } else if path == "-" && args.paths_with_position.len() == 1 {
140            let file = NamedTempFile::new()?;
141            paths.push(file.path().to_string_lossy().to_string());
142            let (file, _) = file.keep()?;
143            stdin_tmp_file = Some(file);
144        } else {
145            paths.push(parse_path_with_position(path)?)
146        }
147    }
148
149    let sender: JoinHandle<anyhow::Result<()>> = thread::spawn({
150        let exit_status = exit_status.clone();
151        move || {
152            let (_, handshake) = server.accept().context("Handshake after Zed spawn")?;
153            let (tx, rx) = (handshake.requests, handshake.responses);
154
155            tx.send(CliRequest::Open {
156                paths,
157                urls,
158                wait: args.wait,
159                open_new_workspace,
160                dev_server_token: args.dev_server_token,
161                env,
162            })?;
163
164            while let Ok(response) = rx.recv() {
165                match response {
166                    CliResponse::Ping => {}
167                    CliResponse::Stdout { message } => println!("{message}"),
168                    CliResponse::Stderr { message } => eprintln!("{message}"),
169                    CliResponse::Exit { status } => {
170                        exit_status.lock().replace(status);
171                        return Ok(());
172                    }
173                }
174            }
175
176            Ok(())
177        }
178    });
179
180    let pipe_handle: JoinHandle<anyhow::Result<()>> = thread::spawn(move || {
181        if let Some(mut tmp_file) = stdin_tmp_file {
182            let mut stdin = std::io::stdin().lock();
183            if io::IsTerminal::is_terminal(&stdin) {
184                return Ok(());
185            }
186            let mut buffer = [0; 8 * 1024];
187            loop {
188                let bytes_read = io::Read::read(&mut stdin, &mut buffer)?;
189                if bytes_read == 0 {
190                    break;
191                }
192                io::Write::write(&mut tmp_file, &buffer[..bytes_read])?;
193            }
194            io::Write::flush(&mut tmp_file)?;
195        }
196        Ok(())
197    });
198
199    if args.foreground {
200        app.run_foreground(url)?;
201    } else {
202        app.launch(url)?;
203        sender.join().unwrap()?;
204        pipe_handle.join().unwrap()?;
205    }
206
207    if let Some(exit_status) = exit_status.lock().take() {
208        std::process::exit(exit_status);
209    }
210    Ok(())
211}
212
213#[cfg(target_os = "linux")]
214mod linux {
215    use std::{
216        env,
217        ffi::OsString,
218        io,
219        os::unix::net::{SocketAddr, UnixDatagram},
220        path::{Path, PathBuf},
221        process::{self, ExitStatus},
222        thread,
223        time::Duration,
224    };
225
226    use anyhow::anyhow;
227    use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
228    use fork::Fork;
229    use once_cell::sync::Lazy;
230
231    use crate::{Detect, InstalledApp};
232
233    static RELEASE_CHANNEL: Lazy<String> =
234        Lazy::new(|| include_str!("../../zed/RELEASE_CHANNEL").trim().to_string());
235
236    struct App(PathBuf);
237
238    impl Detect {
239        pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
240            let path = if let Some(path) = path {
241                path.to_path_buf().canonicalize()?
242            } else {
243                let cli = env::current_exe()?;
244                let dir = cli
245                    .parent()
246                    .ok_or_else(|| anyhow!("no parent path for cli"))?;
247
248                // libexec is the standard, lib/zed is for Arch (and other non-libexec distros),
249                // ./zed is for the target directory in development builds.
250                let possible_locations =
251                    ["../libexec/zed-editor", "../lib/zed/zed-editor", "./zed"];
252                possible_locations
253                    .iter()
254                    .find_map(|p| dir.join(p).canonicalize().ok().filter(|path| path != &cli))
255                    .ok_or_else(|| {
256                        anyhow!("could not find any of: {}", possible_locations.join(", "))
257                    })?
258            };
259
260            Ok(App(path))
261        }
262    }
263
264    impl InstalledApp for App {
265        fn zed_version_string(&self) -> String {
266            format!(
267                "Zed {}{}{}",
268                if *RELEASE_CHANNEL == "stable" {
269                    "".to_string()
270                } else {
271                    format!(" {} ", *RELEASE_CHANNEL)
272                },
273                option_env!("RELEASE_VERSION").unwrap_or_default(),
274                self.0.display(),
275            )
276        }
277
278        fn launch(&self, ipc_url: String) -> anyhow::Result<()> {
279            let sock_path = paths::support_dir().join(format!("zed-{}.sock", *RELEASE_CHANNEL));
280            let sock = UnixDatagram::unbound()?;
281            if sock.connect(&sock_path).is_err() {
282                self.boot_background(ipc_url)?;
283            } else {
284                sock.send(ipc_url.as_bytes())?;
285            }
286            Ok(())
287        }
288
289        fn run_foreground(&self, ipc_url: String) -> io::Result<ExitStatus> {
290            std::process::Command::new(self.0.clone())
291                .arg(ipc_url)
292                .status()
293        }
294    }
295
296    impl App {
297        fn boot_background(&self, ipc_url: String) -> anyhow::Result<()> {
298            let path = &self.0;
299
300            match fork::fork() {
301                Ok(Fork::Parent(_)) => Ok(()),
302                Ok(Fork::Child) => {
303                    std::env::set_var(FORCE_CLI_MODE_ENV_VAR_NAME, "");
304                    if let Err(_) = fork::setsid() {
305                        eprintln!("failed to setsid: {}", std::io::Error::last_os_error());
306                        process::exit(1);
307                    }
308                    if let Err(_) = fork::close_fd() {
309                        eprintln!("failed to close_fd: {}", std::io::Error::last_os_error());
310                    }
311                    let error =
312                        exec::execvp(path.clone(), &[path.as_os_str(), &OsString::from(ipc_url)]);
313                    // if exec succeeded, we never get here.
314                    eprintln!("failed to exec {:?}: {}", path, error);
315                    process::exit(1)
316                }
317                Err(_) => Err(anyhow!(io::Error::last_os_error())),
318            }
319        }
320
321        fn wait_for_socket(
322            &self,
323            sock_addr: &SocketAddr,
324            sock: &mut UnixDatagram,
325        ) -> Result<(), std::io::Error> {
326            for _ in 0..100 {
327                thread::sleep(Duration::from_millis(10));
328                if sock.connect_addr(&sock_addr).is_ok() {
329                    return Ok(());
330                }
331            }
332            sock.connect_addr(&sock_addr)
333        }
334    }
335}
336
337#[cfg(target_os = "linux")]
338mod flatpak {
339    use std::ffi::OsString;
340    use std::path::PathBuf;
341    use std::process::Command;
342    use std::{env, process};
343
344    const EXTRA_LIB_ENV_NAME: &'static str = "ZED_FLATPAK_LIB_PATH";
345    const NO_ESCAPE_ENV_NAME: &'static str = "ZED_FLATPAK_NO_ESCAPE";
346
347    /// Adds bundled libraries to LD_LIBRARY_PATH if running under flatpak
348    pub fn ld_extra_libs() {
349        let mut paths = if let Ok(paths) = env::var("LD_LIBRARY_PATH") {
350            env::split_paths(&paths).collect()
351        } else {
352            Vec::new()
353        };
354
355        if let Ok(extra_path) = env::var(EXTRA_LIB_ENV_NAME) {
356            paths.push(extra_path.into());
357        }
358
359        env::set_var("LD_LIBRARY_PATH", env::join_paths(paths).unwrap());
360    }
361
362    /// Restarts outside of the sandbox if currently running within it
363    pub fn try_restart_to_host() {
364        if let Some(flatpak_dir) = get_flatpak_dir() {
365            let mut args = vec!["/usr/bin/flatpak-spawn".into(), "--host".into()];
366            args.append(&mut get_xdg_env_args());
367            args.push("--env=ZED_UPDATE_EXPLANATION=Please use flatpak to update zed".into());
368            args.push(
369                format!(
370                    "--env={EXTRA_LIB_ENV_NAME}={}",
371                    flatpak_dir.join("lib").to_str().unwrap()
372                )
373                .into(),
374            );
375            args.push(flatpak_dir.join("bin").join("zed").into());
376
377            let mut is_app_location_set = false;
378            for arg in &env::args_os().collect::<Vec<_>>()[1..] {
379                args.push(arg.clone());
380                is_app_location_set |= arg == "--zed";
381            }
382
383            if !is_app_location_set {
384                args.push("--zed".into());
385                args.push(flatpak_dir.join("libexec").join("zed-editor").into());
386            }
387
388            let error = exec::execvp("/usr/bin/flatpak-spawn", args);
389            eprintln!("failed restart cli on host: {:?}", error);
390            process::exit(1);
391        }
392    }
393
394    pub fn set_bin_if_no_escape(mut args: super::Args) -> super::Args {
395        if env::var(NO_ESCAPE_ENV_NAME).is_ok()
396            && env::var("FLATPAK_ID").map_or(false, |id| id.starts_with("dev.zed.Zed"))
397        {
398            if args.zed.is_none() {
399                args.zed = Some("/app/libexec/zed-editor".into());
400                env::set_var("ZED_UPDATE_EXPLANATION", "Please use flatpak to update zed");
401            }
402        }
403        args
404    }
405
406    fn get_flatpak_dir() -> Option<PathBuf> {
407        if env::var(NO_ESCAPE_ENV_NAME).is_ok() {
408            return None;
409        }
410
411        if let Ok(flatpak_id) = env::var("FLATPAK_ID") {
412            if !flatpak_id.starts_with("dev.zed.Zed") {
413                return None;
414            }
415
416            let install_dir = Command::new("/usr/bin/flatpak-spawn")
417                .arg("--host")
418                .arg("flatpak")
419                .arg("info")
420                .arg("--show-location")
421                .arg(flatpak_id)
422                .output()
423                .unwrap();
424            let install_dir = PathBuf::from(String::from_utf8(install_dir.stdout).unwrap().trim());
425            Some(install_dir.join("files"))
426        } else {
427            None
428        }
429    }
430
431    fn get_xdg_env_args() -> Vec<OsString> {
432        let xdg_keys = [
433            "XDG_DATA_HOME",
434            "XDG_CONFIG_HOME",
435            "XDG_CACHE_HOME",
436            "XDG_STATE_HOME",
437        ];
438        env::vars()
439            .filter(|(key, _)| xdg_keys.contains(&key.as_str()))
440            .map(|(key, val)| format!("--env=FLATPAK_{}={}", key, val).into())
441            .collect()
442    }
443}
444
445// todo("windows")
446#[cfg(target_os = "windows")]
447mod windows {
448    use crate::{Detect, InstalledApp};
449    use std::io;
450    use std::path::Path;
451    use std::process::ExitStatus;
452
453    struct App;
454    impl InstalledApp for App {
455        fn zed_version_string(&self) -> String {
456            unimplemented!()
457        }
458        fn launch(&self, _ipc_url: String) -> anyhow::Result<()> {
459            unimplemented!()
460        }
461        fn run_foreground(&self, _ipc_url: String) -> io::Result<ExitStatus> {
462            unimplemented!()
463        }
464    }
465
466    impl Detect {
467        pub fn detect(_path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
468            Ok(App)
469        }
470    }
471}
472
473#[cfg(target_os = "macos")]
474mod mac_os {
475    use anyhow::{anyhow, Context, Result};
476    use core_foundation::{
477        array::{CFArray, CFIndex},
478        string::kCFStringEncodingUTF8,
479        url::{CFURLCreateWithBytes, CFURL},
480    };
481    use core_services::{kLSLaunchDefaults, LSLaunchURLSpec, LSOpenFromURLSpec, TCFType};
482    use serde::Deserialize;
483    use std::{
484        ffi::OsStr,
485        fs, io,
486        path::{Path, PathBuf},
487        process::{Command, ExitStatus},
488        ptr,
489    };
490
491    use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
492
493    use crate::{Detect, InstalledApp};
494
495    #[derive(Debug, Deserialize)]
496    struct InfoPlist {
497        #[serde(rename = "CFBundleShortVersionString")]
498        bundle_short_version_string: String,
499    }
500
501    enum Bundle {
502        App {
503            app_bundle: PathBuf,
504            plist: InfoPlist,
505        },
506        LocalPath {
507            executable: PathBuf,
508            plist: InfoPlist,
509        },
510    }
511
512    fn locate_bundle() -> Result<PathBuf> {
513        let cli_path = std::env::current_exe()?.canonicalize()?;
514        let mut app_path = cli_path.clone();
515        while app_path.extension() != Some(OsStr::new("app")) {
516            if !app_path.pop() {
517                return Err(anyhow!("cannot find app bundle containing {:?}", cli_path));
518            }
519        }
520        Ok(app_path)
521    }
522
523    impl Detect {
524        pub fn detect(path: Option<&Path>) -> anyhow::Result<impl InstalledApp> {
525            let bundle_path = if let Some(bundle_path) = path {
526                bundle_path
527                    .canonicalize()
528                    .with_context(|| format!("Args bundle path {bundle_path:?} canonicalization"))?
529            } else {
530                locate_bundle().context("bundle autodiscovery")?
531            };
532
533            match bundle_path.extension().and_then(|ext| ext.to_str()) {
534                Some("app") => {
535                    let plist_path = bundle_path.join("Contents/Info.plist");
536                    let plist =
537                        plist::from_file::<_, InfoPlist>(&plist_path).with_context(|| {
538                            format!("Reading *.app bundle plist file at {plist_path:?}")
539                        })?;
540                    Ok(Bundle::App {
541                        app_bundle: bundle_path,
542                        plist,
543                    })
544                }
545                _ => {
546                    println!("Bundle path {bundle_path:?} has no *.app extension, attempting to locate a dev build");
547                    let plist_path = bundle_path
548                        .parent()
549                        .with_context(|| format!("Bundle path {bundle_path:?} has no parent"))?
550                        .join("WebRTC.framework/Resources/Info.plist");
551                    let plist =
552                        plist::from_file::<_, InfoPlist>(&plist_path).with_context(|| {
553                            format!("Reading dev bundle plist file at {plist_path:?}")
554                        })?;
555                    Ok(Bundle::LocalPath {
556                        executable: bundle_path,
557                        plist,
558                    })
559                }
560            }
561        }
562    }
563
564    impl InstalledApp for Bundle {
565        fn zed_version_string(&self) -> String {
566            let is_dev = matches!(self, Self::LocalPath { .. });
567            format!(
568                "Zed {}{}{}",
569                self.plist().bundle_short_version_string,
570                if is_dev { " (dev)" } else { "" },
571                self.path().display(),
572            )
573        }
574
575        fn launch(&self, url: String) -> anyhow::Result<()> {
576            match self {
577                Self::App { app_bundle, .. } => {
578                    let app_path = app_bundle;
579
580                    let status = unsafe {
581                        let app_url = CFURL::from_path(app_path, true)
582                            .with_context(|| format!("invalid app path {app_path:?}"))?;
583                        let url_to_open = CFURL::wrap_under_create_rule(CFURLCreateWithBytes(
584                            ptr::null(),
585                            url.as_ptr(),
586                            url.len() as CFIndex,
587                            kCFStringEncodingUTF8,
588                            ptr::null(),
589                        ));
590                        // equivalent to: open zed-cli:... -a /Applications/Zed\ Preview.app
591                        let urls_to_open =
592                            CFArray::from_copyable(&[url_to_open.as_concrete_TypeRef()]);
593                        LSOpenFromURLSpec(
594                            &LSLaunchURLSpec {
595                                appURL: app_url.as_concrete_TypeRef(),
596                                itemURLs: urls_to_open.as_concrete_TypeRef(),
597                                passThruParams: ptr::null(),
598                                launchFlags: kLSLaunchDefaults,
599                                asyncRefCon: ptr::null_mut(),
600                            },
601                            ptr::null_mut(),
602                        )
603                    };
604
605                    anyhow::ensure!(
606                        status == 0,
607                        "cannot start app bundle {}",
608                        self.zed_version_string()
609                    );
610                }
611
612                Self::LocalPath { executable, .. } => {
613                    let executable_parent = executable
614                        .parent()
615                        .with_context(|| format!("Executable {executable:?} path has no parent"))?;
616                    let subprocess_stdout_file = fs::File::create(
617                        executable_parent.join("zed_dev.log"),
618                    )
619                    .with_context(|| format!("Log file creation in {executable_parent:?}"))?;
620                    let subprocess_stdin_file =
621                        subprocess_stdout_file.try_clone().with_context(|| {
622                            format!("Cloning descriptor for file {subprocess_stdout_file:?}")
623                        })?;
624                    let mut command = std::process::Command::new(executable);
625                    let command = command
626                        .env(FORCE_CLI_MODE_ENV_VAR_NAME, "")
627                        .stderr(subprocess_stdout_file)
628                        .stdout(subprocess_stdin_file)
629                        .arg(url);
630
631                    command
632                        .spawn()
633                        .with_context(|| format!("Spawning {command:?}"))?;
634                }
635            }
636
637            Ok(())
638        }
639
640        fn run_foreground(&self, ipc_url: String) -> io::Result<ExitStatus> {
641            let path = match self {
642                Bundle::App { app_bundle, .. } => app_bundle.join("Contents/MacOS/zed"),
643                Bundle::LocalPath { executable, .. } => executable.clone(),
644            };
645
646            std::process::Command::new(path).arg(ipc_url).status()
647        }
648    }
649
650    impl Bundle {
651        fn plist(&self) -> &InfoPlist {
652            match self {
653                Self::App { plist, .. } => plist,
654                Self::LocalPath { plist, .. } => plist,
655            }
656        }
657
658        fn path(&self) -> &Path {
659            match self {
660                Self::App { app_bundle, .. } => app_bundle,
661                Self::LocalPath { executable, .. } => executable,
662            }
663        }
664    }
665
666    pub(super) fn spawn_channel_cli(
667        channel: release_channel::ReleaseChannel,
668        leftover_args: Vec<String>,
669    ) -> Result<()> {
670        use anyhow::bail;
671
672        let app_id_prompt = format!("id of app \"{}\"", channel.display_name());
673        let app_id_output = Command::new("osascript")
674            .arg("-e")
675            .arg(&app_id_prompt)
676            .output()?;
677        if !app_id_output.status.success() {
678            bail!("Could not determine app id for {}", channel.display_name());
679        }
680        let app_name = String::from_utf8(app_id_output.stdout)?.trim().to_owned();
681        let app_path_prompt = format!("kMDItemCFBundleIdentifier == '{app_name}'");
682        let app_path_output = Command::new("mdfind").arg(app_path_prompt).output()?;
683        if !app_path_output.status.success() {
684            bail!(
685                "Could not determine app path for {}",
686                channel.display_name()
687            );
688        }
689        let app_path = String::from_utf8(app_path_output.stdout)?.trim().to_owned();
690        let cli_path = format!("{app_path}/Contents/MacOS/cli");
691        Command::new(cli_path).args(leftover_args).spawn()?;
692        Ok(())
693    }
694}