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