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