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