BlueGit

ict rusty-teams

Files

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

external_browser.rs

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