BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / external_browser.rs

external_browser.rs

external_browser.rs 5.0 KiB Download Raw
1//! Preferred browser for external opens (Google OAuth, links).
2//!
3//! The managed Chrome session for Microsoft Teams login is unchanged (ADR 0003).
4
5use std::path::{Path, PathBuf};
6use std::process::Command;
7
8use gpui_kit::App;
9use store::Store;
10
11const META_KEY: &str = "external_browser";
12const SYSTEM_VALUE: &str = "system";
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum ExternalBrowser {
16 System,
17 Program(String),
18}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct BrowserChoice {
22 pub id: String,
23 pub label: String,
24}
25
26impl ExternalBrowser {
27 pub fn id(&self) -> &str {
28 match self {
29 ExternalBrowser::System => SYSTEM_VALUE,
30 ExternalBrowser::Program(program) => program.as_str(),
31 }
32 }
33}
34
35pub fn load(store: &Store) -> ExternalBrowser {
36 match store.meta(META_KEY).ok().flatten().as_deref() {
37 None | Some(SYSTEM_VALUE) | Some("") => ExternalBrowser::System,
38 Some(program) => ExternalBrowser::Program(program.to_owned()),
39 }
40}
41
42pub fn save(store: &Store, browser: &ExternalBrowser) {
43 let value = match browser {
44 ExternalBrowser::System => SYSTEM_VALUE,
45 ExternalBrowser::Program(program) => program.as_str(),
46 };
47 let _ = store.set_meta(META_KEY, value);
48}
49
50pub fn open_url(cx: &mut App, store: &Store, url: &str) {
51 match load(store) {
52 ExternalBrowser::System => cx.open_url(url),
53 ExternalBrowser::Program(program) => {
54 let known = available_choices().iter().any(|choice| choice.id == program);
55 if !known || launch_program(&program, url).is_err() {
56 cx.open_url(url);
57 }
58 }
59 }
60}
61
62fn launch_program(program: &str, url: &str) -> std::io::Result<()> {
63 #[cfg(target_os = "macos")]
64 {
65 if looks_like_app_name(program) {
66 Command::new("open").args(["-a", program, url]).spawn()?;
67 return Ok(());
68 }
69 }
70 Command::new(program).arg(url).spawn()?;
71 Ok(())
72}
73
74#[cfg(target_os = "macos")]
75fn looks_like_app_name(program: &str) -> bool {
76 !program.contains('/') && program.chars().any(|c| c.is_uppercase() || c == ' ')
77}
78
79pub fn available_choices() -> Vec<BrowserChoice> {
80 let mut choices = vec![BrowserChoice {
81 id: SYSTEM_VALUE.to_owned(),
82 label: SYSTEM_VALUE.to_owned(),
83 }];
84 for (id, label) in discover_browsers() {
85 if choices.iter().any(|choice| choice.id == id) {
86 continue;
87 }
88 choices.push(BrowserChoice { id, label });
89 }
90 choices
91}
92
93pub fn is_system_id(id: &str) -> bool {
94 id == SYSTEM_VALUE
95}
96
97fn discover_browsers() -> Vec<(String, String)> {
98 #[cfg(target_os = "linux")]
99 {
100 const CANDIDATES: [(&str, &str); 6] = [
101 ("google-chrome", "Google Chrome"),
102 ("google-chrome-stable", "Google Chrome"),
103 ("chromium", "Chromium"),
104 ("chromium-browser", "Chromium"),
105 ("firefox", "Firefox"),
106 ("brave-browser", "Brave"),
107 ];
108 return CANDIDATES
109 .into_iter()
110 .filter(|(name, _)| which(name).is_some())
111 .map(|(name, label)| (name.to_owned(), label.to_owned()))
112 .collect();
113 }
114 #[cfg(target_os = "macos")]
115 {
116 let mut found = Vec::new();
117 const APPS: [(&str, &str); 4] = [
118 ("Google Chrome", "Google Chrome"),
119 ("Chromium", "Chromium"),
120 ("Firefox", "Firefox"),
121 ("Safari", "Safari"),
122 ];
123 let mut roots = vec![PathBuf::from("/Applications")];
124 if let Some(home) = dirs_home() {
125 roots.push(home.join("Applications"));
126 }
127 for (app, label) in APPS {
128 if roots
129 .iter()
130 .any(|root| root.join(format!("{app}.app")).is_dir())
131 {
132 found.push((app.to_owned(), label.to_owned()));
133 }
134 }
135 return found;
136 }
137 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
138 {
139 Vec::new()
140 }
141}
142
143fn which(name: &str) -> Option<PathBuf> {
144 let path = std::env::var_os("PATH")?;
145 for dir in std::env::split_paths(&path) {
146 let candidate = dir.join(name);
147 if is_executable(&candidate) {
148 return Some(candidate);
149 }
150 }
151 None
152}
153
154fn is_executable(path: &Path) -> bool {
155 path.is_file()
156}
157
158#[cfg(target_os = "macos")]
159fn dirs_home() -> Option<PathBuf> {
160 std::env::var_os("HOME").map(PathBuf::from)
161}
162
163#[cfg(test)]
164mod tests {
165 use super::{ExternalBrowser, SYSTEM_VALUE, load, save};
166 use store::Store;
167
168 #[test]
169 fn defaults_to_system_and_round_trips() {
170 let store = Store::open_in_memory().unwrap();
171 assert_eq!(load(&store), ExternalBrowser::System);
172 save(&store, &ExternalBrowser::Program("firefox".into()));
173 assert_eq!(load(&store), ExternalBrowser::Program("firefox".into()));
174 save(&store, &ExternalBrowser::System);
175 assert_eq!(load(&store), ExternalBrowser::System);
176 assert_eq!(ExternalBrowser::System.id(), SYSTEM_VALUE);
177 }
178}