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