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