BlueGit

ict rusty-teams

Files

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

external_browser.rs

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