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