BlueGit

ict rusty-teams

Files

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

external_browser.rs

external_browser.rs 4.9 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 if launch_program(&program, url).is_err() {
55 cx.open_url(url);
56 }
57 }
58 }
59}
60
61fn launch_program(program: &str, url: &str) -> std::io::Result<()> {
62 #[cfg(target_os = "macos")]
63 {
64 if looks_like_app_name(program) {
65 Command::new("open").args(["-a", program, url]).spawn()?;
66 return Ok(());
67 }
68 }
69 Command::new(program).arg(url).spawn()?;
70 Ok(())
71}
72
73#[cfg(target_os = "macos")]
74fn looks_like_app_name(program: &str) -> bool {
75 !program.contains('/') && program.chars().any(|c| c.is_uppercase() || c == ' ')
76}
77
78pub fn available_choices() -> Vec<BrowserChoice> {
79 let mut choices = vec![BrowserChoice {
80 id: SYSTEM_VALUE.to_owned(),
81 label: SYSTEM_VALUE.to_owned(),
82 }];
83 for (id, label) in discover_browsers() {
84 if choices.iter().any(|choice| choice.id == id) {
85 continue;
86 }
87 choices.push(BrowserChoice { id, label });
88 }
89 choices
90}
91
92pub fn is_system_id(id: &str) -> bool {
93 id == SYSTEM_VALUE
94}
95
96fn discover_browsers() -> Vec<(String, String)> {
97 #[cfg(target_os = "linux")]
98 {
99 const CANDIDATES: [(&str, &str); 6] = [
100 ("google-chrome", "Google Chrome"),
101 ("google-chrome-stable", "Google Chrome"),
102 ("chromium", "Chromium"),
103 ("chromium-browser", "Chromium"),
104 ("firefox", "Firefox"),
105 ("brave-browser", "Brave"),
106 ];
107 return CANDIDATES
108 .into_iter()
109 .filter(|(name, _)| which(name).is_some())
110 .map(|(name, label)| (name.to_owned(), label.to_owned()))
111 .collect();
112 }
113 #[cfg(target_os = "macos")]
114 {
115 let mut found = Vec::new();
116 const APPS: [(&str, &str); 4] = [
117 ("Google Chrome", "Google Chrome"),
118 ("Chromium", "Chromium"),
119 ("Firefox", "Firefox"),
120 ("Safari", "Safari"),
121 ];
122 let mut roots = vec![PathBuf::from("/Applications")];
123 if let Some(home) = dirs_home() {
124 roots.push(home.join("Applications"));
125 }
126 for (app, label) in APPS {
127 if roots
128 .iter()
129 .any(|root| root.join(format!("{app}.app")).is_dir())
130 {
131 found.push((app.to_owned(), label.to_owned()));
132 }
133 }
134 return found;
135 }
136 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
137 {
138 Vec::new()
139 }
140}
141
142fn which(name: &str) -> Option<PathBuf> {
143 let path = std::env::var_os("PATH")?;
144 for dir in std::env::split_paths(&path) {
145 let candidate = dir.join(name);
146 if is_executable(&candidate) {
147 return Some(candidate);
148 }
149 }
150 None
151}
152
153fn is_executable(path: &Path) -> bool {
154 path.is_file()
155}
156
157#[cfg(target_os = "macos")]
158fn dirs_home() -> Option<PathBuf> {
159 std::env::var_os("HOME").map(PathBuf::from)
160}
161
162#[cfg(test)]
163mod tests {
164 use super::{ExternalBrowser, SYSTEM_VALUE, load, save};
165 use store::Store;
166
167 #[test]
168 fn defaults_to_system_and_round_trips() {
169 let store = Store::open_in_memory().unwrap();
170 assert_eq!(load(&store), ExternalBrowser::System);
171 save(&store, &ExternalBrowser::Program("firefox".into()));
172 assert_eq!(load(&store), ExternalBrowser::Program("firefox".into()));
173 save(&store, &ExternalBrowser::System);
174 assert_eq!(load(&store), ExternalBrowser::System);
175 assert_eq!(ExternalBrowser::System.id(), SYSTEM_VALUE);
176 }
177}