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