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