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