Skip to main content

blyte_cli/
open_window.rs

1use std::ffi::OsStr;
2use std::path::{Path, PathBuf};
3use std::process::Command;
4
5pub const OPEN_IN_ENV: &str = "BLYTE_OPEN_IN";
6
7pub const APP_FALLBACK_NOTICE: &str = "blyte: no Chrome, Chromium, Edge or Brave found for an app window; opening in the default browser (--open-in browser stops this notice)";
8
9pub const MACOS_APP_BROWSERS: &[&str] = &[
10    "Google Chrome",
11    "Chromium",
12    "Microsoft Edge",
13    "Brave Browser",
14];
15
16pub const LINUX_APP_BROWSERS: &[&str] = &[
17    "google-chrome",
18    "google-chrome-stable",
19    "chromium",
20    "chromium-browser",
21    "microsoft-edge",
22    "brave-browser",
23];
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26pub enum OpenIn {
27    #[default]
28    App,
29    Browser,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct OpenPlan {
34    pub program: String,
35    pub args: Vec<String>,
36    pub notice: Option<String>,
37}
38
39pub fn parse_open_in(raw: &str, source: &str) -> Result<OpenIn, String> {
40    match raw {
41        "app" => Ok(OpenIn::App),
42        "browser" => Ok(OpenIn::Browser),
43        _ => Err(format!(
44            "invalid value `{raw}` for {source}; expected `app` or `browser`"
45        )),
46    }
47}
48
49pub fn resolve_open_in_os(flag: Option<&str>, env: Option<&OsStr>) -> Result<OpenIn, String> {
50    if let Some(raw) = flag {
51        return parse_open_in(raw, "--open-in");
52    }
53    if let Some(raw) = env {
54        return match raw.to_str() {
55            Some(s) => parse_open_in(s, OPEN_IN_ENV),
56            None => Err(format!(
57                "invalid value `{}` for {OPEN_IN_ENV}; expected `app` or `browser`",
58                raw.to_string_lossy()
59            )),
60        };
61    }
62    Ok(OpenIn::App)
63}
64
65pub fn resolve_open_in(flag: Option<&str>, env: Option<&str>) -> Result<OpenIn, String> {
66    resolve_open_in_os(flag, env.map(OsStr::new))
67}
68
69pub fn resolve_open_in_from_env(flag: Option<&str>) -> Result<OpenIn, String> {
70    let env_val = std::env::var_os(OPEN_IN_ENV);
71    resolve_open_in_os(flag, env_val.as_deref())
72}
73
74pub fn open_command(
75    open_in: OpenIn,
76    url: &str,
77    os: &str,
78    installed: &dyn Fn(&str) -> bool,
79) -> Result<OpenPlan, String> {
80    match (os, open_in) {
81        ("macos", OpenIn::App) => {
82            for &name in MACOS_APP_BROWSERS {
83                if installed(name) {
84                    return Ok(OpenPlan {
85                        program: "open".to_string(),
86                        args: vec![
87                            "-na".to_string(),
88                            name.to_string(),
89                            "--args".to_string(),
90                            format!("--app={url}"),
91                        ],
92                        notice: None,
93                    });
94                }
95            }
96            Ok(OpenPlan {
97                program: "open".to_string(),
98                args: vec![url.to_string()],
99                notice: Some(APP_FALLBACK_NOTICE.to_string()),
100            })
101        }
102        ("macos", OpenIn::Browser) => Ok(OpenPlan {
103            program: "open".to_string(),
104            args: vec![url.to_string()],
105            notice: None,
106        }),
107        ("linux", OpenIn::App) => {
108            for &program in LINUX_APP_BROWSERS {
109                if installed(program) {
110                    return Ok(OpenPlan {
111                        program: program.to_string(),
112                        args: vec![format!("--app={url}")],
113                        notice: None,
114                    });
115                }
116            }
117            Ok(OpenPlan {
118                program: "xdg-open".to_string(),
119                args: vec![url.to_string()],
120                notice: Some(APP_FALLBACK_NOTICE.to_string()),
121            })
122        }
123        ("linux", OpenIn::Browser) => Ok(OpenPlan {
124            program: "xdg-open".to_string(),
125            args: vec![url.to_string()],
126            notice: None,
127        }),
128        _ => Err(format!("opening a surface window is not supported on {os}")),
129    }
130}
131
132fn is_executable_file(path: &Path) -> bool {
133    let Ok(meta) = std::fs::metadata(path) else {
134        return false;
135    };
136    if !meta.is_file() {
137        return false;
138    }
139    #[cfg(unix)]
140    {
141        use std::os::unix::fs::PermissionsExt;
142        meta.permissions().mode() & 0o111 != 0
143    }
144    #[cfg(not(unix))]
145    {
146        true
147    }
148}
149
150fn is_macos_app_installed(name: &str) -> bool {
151    let bundle = format!("{name}.app");
152    if Path::new("/Applications").join(&bundle).exists() {
153        return true;
154    }
155    if let Some(home) = std::env::var_os("HOME") {
156        if PathBuf::from(home)
157            .join("Applications")
158            .join(&bundle)
159            .exists()
160        {
161            return true;
162        }
163    }
164    false
165}
166
167fn is_on_path(program: &str) -> bool {
168    let Some(path_var) = std::env::var_os("PATH") else {
169        return false;
170    };
171    for dir in std::env::split_paths(&path_var) {
172        if is_executable_file(&dir.join(program)) {
173            return true;
174        }
175    }
176    false
177}
178
179pub fn is_browser_installed(name: &str, os: &str) -> bool {
180    match os {
181        "macos" => is_macos_app_installed(name),
182        "linux" => is_on_path(name),
183        _ => false,
184    }
185}
186
187pub fn open_url(open_in: OpenIn, url: &str) {
188    let os = std::env::consts::OS;
189    let plan = match open_command(open_in, url, os, &|name| is_browser_installed(name, os)) {
190        Ok(plan) => plan,
191        Err(e) => {
192            eprintln!("blyte: {e}; open {url} yourself");
193            return;
194        }
195    };
196    if let Some(notice) = plan.notice {
197        eprintln!("{notice}");
198    }
199    if let Err(e) = Command::new(&plan.program).args(&plan.args).spawn() {
200        eprintln!(
201            "blyte: could not open a browser with {}: {e}; open {url} yourself",
202            plan.program
203        );
204    }
205}