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