BlueGit

ict rusty-teams

feat(macos): managed Chrome sign-in like WebView2 / Linux

Start Chrome/Chromium on debug port 9222 with an Application Support
profile, show the window for login, then return to headless. Links the
browser crate on macOS. Non-Windows Auto/Low mic stay on the ADM path.

metis Joachim Mild · pushed by metis

Authored 2026-11-12 · 2 weeks ago

Hash
be96a9ba4afd58855059efbdad313119230fc6a5
Parent
5a1e4cc7
8 files changed +319 −51
README.md +23 −3
@@ -61,7 +61,7 @@
61 61 **Calls**
62 62 - Test call to the Teams Echo bot from the avatar menu: native WebRTC audio, mute (`Ctrl+Shift+M`), device switching, mini window while you read other chats
63 63 - Phone button in 1:1 and group chat headers: callee tiles show Calling and Ringing, Cancel while ringing, notices like "Bea declined" or "No answer"
64 - Video and screen sharing: H264 tiles, shared screen on a stage (double click for full window, Esc back), camera and screen share buttons with a "You are sharing" banner. Linux needs glib at run time
64 - Video and screen sharing: H264 tiles, shared screen on a stage (double click for full window, Esc back), camera and screen share buttons with a "You are sharing" banner. Linux needs glib at run time. On Wayland, sharing opens the desktop ScreenCast portal dialog, including on KDE, GNOME and Hyprland
65 65 - Incoming calls: topmost ring toast with Decline and Accept, ring tone, missed calls in Activity
66 66 - Join a running meeting from its chat (audio): roster tiles, speaking ring, lobby state, Leave or End meeting for the organizer
67 67 - After every call a pseudonymized test report (JSON and Markdown, newest 30) is saved to the app data folder `call-reports`; toast "Test report saved" with Open folder, Settings > Devices switch
@@ -74,6 +74,11 @@
74 74 - One-click install for Claude Code, Codex CLI, Copilot CLI, VS Code and Cursor, Windows and WSL. WSL needs `networkingMode=mirrored`
75 75 - Delegate a message to a coding-agent CLI (Claude Code, Copilot, any CLI) from the hover toolbar: progress chip, Agents page, toast when it finishes, Open session
76 76
77 **Calendar (fork)**
78 - Outlook calendar as today, plus optional Google Calendar accounts (Settings > Calendar)
79 - Merge by iCal UID / Teams join URL; New meeting writes to the home calendar and optional extra targets
80 - Google OAuth Desktop (PKCE): set `TEAMS_GOOGLE_CLIENT_ID` and optionally `TEAMS_GOOGLE_CLIENT_SECRET` before Connect
81
77 82 **App**
78 83 - Dark theme, opens instantly from the cache
79 84 - Self-update from an update folder
@@ -84,8 +89,8 @@
84 89 | Platform | State |
85 90 |---|---|
86 91 | 🪟 Windows | Main target. Login through an embedded WebView2 |
87 | 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. The app opens an Outlook on the web tab next to Teams when missing (some tenants grant chat scopes only to Outlook). Built-in login without Chrome is planned |
88 | 🍎 macOS | Experimental. Universal arm64 + x86_64 binary, connects to a Chrome like Linux |
92 | 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. The app opens an Outlook on the web tab next to Teams when missing (some tenants grant chat scopes only to Outlook). Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. Copy `crates/app/assets/linux/rusty-teams.desktop` to `~/.local/share/applications/` and `crates/app/assets/icon/teams-fast-256.png` to `~/.local/share/icons/hicolor/256x256/apps/rusty-teams.png` so the dock can match it. Built-in login without Chrome is planned |
93 | 🍎 macOS | Starts Google Chrome or Chromium on its own (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
89 94
90 95 The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
91 96
@@ -97,6 +102,21 @@ Try it with demo data, no account needed:
97 102 cargo run -p app -- --demo
98 103 ```
99 104
105 ### Google Calendar (optional)
106
107 1. Create an OAuth Desktop client in Google Cloud Console with redirect `http://127.0.0.1:<port>/` (loopback; the app picks a free port).
108 2. Export before starting the app:
109
110 ```bash
111 export TEAMS_GOOGLE_CLIENT_ID="….apps.googleusercontent.com"
112 # only if the client has a secret:
113 export TEAMS_GOOGLE_CLIENT_SECRET="…"
114 ```
115
116 3. Settings > Calendar > Connect Google, then choose home calendar and optional dual-write targets.
117
118 Without these env vars the calendar stays Outlook-only.
119
100 120 | Task | Command |
101 121 |---|---|
102 122 | Linux build needs clang 21+ (libwebrtc's hermetic libc++) + mold (set in `.cargo/config.toml`); sccache shares compiled deps across worktrees | `sudo apt install clang mold sccache`, clang from [apt.llvm.org](https://apt.llvm.org) if the distro one is older than 21 |
@@ -61,7 +61,7 @@
61**Calls**
61**Calls**
62- Test call to the Teams Echo bot from the avatar menu: native WebRTC audio, mute (`Ctrl+Shift+M`), device switching, mini window while you read other chats
62- Test call to the Teams Echo bot from the avatar menu: native WebRTC audio, mute (`Ctrl+Shift+M`), device switching, mini window while you read other chats
63- Phone button in 1:1 and group chat headers: callee tiles show Calling and Ringing, Cancel while ringing, notices like "Bea declined" or "No answer"
63- Phone button in 1:1 and group chat headers: callee tiles show Calling and Ringing, Cancel while ringing, notices like "Bea declined" or "No answer"
64- Video and screen sharing: H264 tiles, shared screen on a stage (double click for full window, Esc back), camera and screen share buttons with a "You are sharing" banner. Linux needs glib at run time
64- Video and screen sharing: H264 tiles, shared screen on a stage (double click for full window, Esc back), camera and screen share buttons with a "You are sharing" banner. Linux needs glib at run time. On Wayland, sharing opens the desktop ScreenCast portal dialog, including on KDE, GNOME and Hyprland
65- Incoming calls: topmost ring toast with Decline and Accept, ring tone, missed calls in Activity
65- Incoming calls: topmost ring toast with Decline and Accept, ring tone, missed calls in Activity
66- Join a running meeting from its chat (audio): roster tiles, speaking ring, lobby state, Leave or End meeting for the organizer
66- Join a running meeting from its chat (audio): roster tiles, speaking ring, lobby state, Leave or End meeting for the organizer
67- After every call a pseudonymized test report (JSON and Markdown, newest 30) is saved to the app data folder `call-reports`; toast "Test report saved" with Open folder, Settings > Devices switch
67- After every call a pseudonymized test report (JSON and Markdown, newest 30) is saved to the app data folder `call-reports`; toast "Test report saved" with Open folder, Settings > Devices switch
@@ -74,6 +74,11 @@
74- One-click install for Claude Code, Codex CLI, Copilot CLI, VS Code and Cursor, Windows and WSL. WSL needs `networkingMode=mirrored`
74- One-click install for Claude Code, Codex CLI, Copilot CLI, VS Code and Cursor, Windows and WSL. WSL needs `networkingMode=mirrored`
75- Delegate a message to a coding-agent CLI (Claude Code, Copilot, any CLI) from the hover toolbar: progress chip, Agents page, toast when it finishes, Open session
75- Delegate a message to a coding-agent CLI (Claude Code, Copilot, any CLI) from the hover toolbar: progress chip, Agents page, toast when it finishes, Open session
76
76
77**Calendar (fork)**
78- Outlook calendar as today, plus optional Google Calendar accounts (Settings > Calendar)
79- Merge by iCal UID / Teams join URL; New meeting writes to the home calendar and optional extra targets
80- Google OAuth Desktop (PKCE): set `TEAMS_GOOGLE_CLIENT_ID` and optionally `TEAMS_GOOGLE_CLIENT_SECRET` before Connect
81
77**App**
82**App**
78- Dark theme, opens instantly from the cache
83- Dark theme, opens instantly from the cache
79- Self-update from an update folder
84- Self-update from an update folder
@@ -84,8 +89,8 @@
84| Platform | State |
89| Platform | State |
85|---|---|
90|---|---|
86| 🪟 Windows | Main target. Login through an embedded WebView2 |
91| 🪟 Windows | Main target. Login through an embedded WebView2 |
87| 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. The app opens an Outlook on the web tab next to Teams when missing (some tenants grant chat scopes only to Outlook). Built-in login without Chrome is planned |
92| 🐧 Linux | Starts Google Chrome or Chromium on its own (debug port 9222, own profile in the XDG data folder) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. The app opens an Outlook on the web tab next to Teams when missing (some tenants grant chat scopes only to Outlook). Color emoji use a bundled bitmap Noto Color Emoji font; a system COLRv1 face of the same name is left out of the font list. The window id is `rusty-teams`. Copy `crates/app/assets/linux/rusty-teams.desktop` to `~/.local/share/applications/` and `crates/app/assets/icon/teams-fast-256.png` to `~/.local/share/icons/hicolor/256x256/apps/rusty-teams.png` so the dock can match it. Built-in login without Chrome is planned |
88| 🍎 macOS | Experimental. Universal arm64 + x86_64 binary, connects to a Chrome like Linux |
93| 🍎 macOS | Starts Google Chrome or Chromium on its own (debug port 9222, own profile under Application Support) and keeps it headless in the background. When Teams asks for a login, the Chrome window shows itself and goes back to the background once you are signed in. `--endpoint` connects to a Chrome you started yourself instead. Universal arm64 + x86_64 `.app` bundle. Screen share uses the ScreenCaptureKit system dialog |
89
94
90The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
95The remaining gaps are planned, see [ROADMAP.md](ROADMAP.md).
91
96
@@ -97,6 +102,21 @@ Try it with demo data, no account needed:
97cargo run -p app -- --demo
102cargo run -p app -- --demo
98```
103```
99
104
105### Google Calendar (optional)
106
1071. Create an OAuth Desktop client in Google Cloud Console with redirect `http://127.0.0.1:<port>/` (loopback; the app picks a free port).
1082. Export before starting the app:
109
110```bash
111export TEAMS_GOOGLE_CLIENT_ID="….apps.googleusercontent.com"
112# only if the client has a secret:
113export TEAMS_GOOGLE_CLIENT_SECRET="…"
114```
115
1163. Settings > Calendar > Connect Google, then choose home calendar and optional dual-write targets.
117
118Without these env vars the calendar stays Outlook-only.
119
100| Task | Command |
120| Task | Command |
101|---|---|
121|---|---|
102| Linux build needs clang 21+ (libwebrtc's hermetic libc++) + mold (set in `.cargo/config.toml`); sccache shares compiled deps across worktrees | `sudo apt install clang mold sccache`, clang from [apt.llvm.org](https://apt.llvm.org) if the distro one is older than 21 |
122| Linux build needs clang 21+ (libwebrtc's hermetic libc++) + mold (set in `.cargo/config.toml`); sccache shares compiled deps across worktrees | `sudo apt install clang mold sccache`, clang from [apt.llvm.org](https://apt.llvm.org) if the distro one is older than 21 |
crates/app/Cargo.toml +3 −0
@@ -48,3 +48,6 @@ webview.workspace = true
48 48
49 49 [target.'cfg(target_os = "linux")'.dependencies]
50 50 browser.workspace = true
51
52 [target.'cfg(target_os = "macos")'.dependencies]
53 browser.workspace = true
@@ -48,3 +48,6 @@ webview.workspace = true
48
48
49[target.'cfg(target_os = "linux")'.dependencies]
49[target.'cfg(target_os = "linux")'.dependencies]
50browser.workspace = true
50browser.workspace = true
51
52[target.'cfg(target_os = "macos")'.dependencies]
53browser.workspace = true
crates/app/src/main.rs +25 −7
@@ -4,13 +4,15 @@
4 4 )]
5 5
6 6 mod active_appearance;
7 mod active_locale;
7 8 mod agent_direct;
9 mod i18n;
8 10 pub mod agents;
9 11 pub mod call;
10 12 mod inline_video;
11 13 #[cfg(test)]
12 14 mod layout_guard;
13 #[cfg(target_os = "linux")]
15 #[cfg(any(target_os = "linux", target_os = "macos"))]
14 16 mod linux_browser;
15 17 pub mod notify;
16 18 mod settings;
@@ -124,6 +126,7 @@ fn data_path(name: &str) -> PathBuf {
124 126 fn transport(
125 127 endpoint: Option<&str>,
126 128 database: Option<&std::path::Path>,
129 #[cfg(windows)] sign_in_title: String,
127 130 ) -> Arc<dyn session::Transport> {
128 131 #[cfg(windows)]
129 132 if endpoint.is_none() {
@@ -134,7 +137,7 @@ fn transport(
134 137 inline_video::configure(user_data_folder.clone());
135 138 let transport = webview::start(webview::HostConfig {
136 139 user_data_folder,
137 window_title: format!("{APP_NAME} - Sign in"),
140 window_title: sign_in_title,
138 141 log: |line| app_base::diagnostics::record(line),
139 142 });
140 143 task_dialog::install_host(transport.clone());
@@ -142,7 +145,7 @@ fn transport(
142 145 }
143 146 #[cfg(not(windows))]
144 147 let _ = database;
145 #[cfg(target_os = "linux")]
148 #[cfg(any(target_os = "linux", target_os = "macos"))]
146 149 if endpoint.is_none() {
147 150 return linux_browser::start(session::DEFAULT_ENDPOINT);
148 151 }
@@ -176,8 +179,6 @@ fn main() {
176 179 data_path(crash_log::CRASH_LOG_FILE),
177 180 );
178 181 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
179 #[cfg(target_os = "linux")]
180 app_base::linux_fonts::hide_system_color_emoji();
181 182 let arguments = parse_arguments();
182 183 if !arguments.demo && arguments.database.is_none() {
183 184 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
@@ -219,8 +220,24 @@ fn main() {
219 220 open_store(&path)
220 221 };
221 222 let store = Arc::new(store);
223 app_base::ui_locale::apply_locale(app_base::ui_locale::effective_locale(app_base::ui_locale::load(
224 &store,
225 )));
226 #[cfg(windows)]
227 let sign_in_title = format!(
228 "{} - {}",
229 app_base::APP_NAME,
230 app_base::ui_locale::tr("auth.sign_in")
231 );
222 232 let user_input = user_activity::UserInput::new();
223 233 let receiver = (!arguments.demo).then(|| {
234 #[cfg(windows)]
235 let transport = transport(
236 arguments.endpoint.as_deref(),
237 arguments.database.as_deref(),
238 sign_in_title.clone(),
239 );
240 #[cfg(not(windows))]
224 241 let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
225 242 let activity = user_activity::track(user_input.clone());
226 243 backend::start(store.clone(), transport, !arguments.read_only, activity)
@@ -242,6 +259,7 @@ fn main() {
242 259 .detach();
243 260 theme::load_fonts(cx);
244 261 active_appearance::install(&store, cx);
262 active_locale::install(&store, cx);
245 263 theme::apply(cx);
246 264 bind_keys(cx);
247 265 let state = cx.new(|_| {
@@ -262,7 +280,7 @@ fn main() {
262 280 while let Some(event) = receiver.recv().await {
263 281 let kind = event.kind();
264 282 let started = std::time::Instant::now();
265 #[cfg(target_os = "linux")]
283 #[cfg(any(target_os = "linux", target_os = "macos"))]
266 284 linux_browser::note_backend_event(&event);
267 285 state.update(cx, |state, cx| state.apply(event, cx));
268 286 app_base::diagnostics::record_if_slow(&kind, started.elapsed());
@@ -309,7 +327,7 @@ fn main() {
309 327 .detach();
310 328 });
311 329 presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
312 #[cfg(target_os = "linux")]
330 #[cfg(any(target_os = "linux", target_os = "macos"))]
313 331 linux_browser::stop();
314 332 #[cfg(windows)]
315 333 updater::exit_now();
@@ -4,13 +4,15 @@
4)]
4)]
5
5
6mod active_appearance;
6mod active_appearance;
7mod active_locale;
7mod agent_direct;
8mod agent_direct;
9mod i18n;
8pub mod agents;
10pub mod agents;
9pub mod call;
11pub mod call;
10mod inline_video;
12mod inline_video;
11#[cfg(test)]
13#[cfg(test)]
12mod layout_guard;
14mod layout_guard;
13#[cfg(target_os = "linux")]
15#[cfg(any(target_os = "linux", target_os = "macos"))]
14mod linux_browser;
16mod linux_browser;
15pub mod notify;
17pub mod notify;
16mod settings;
18mod settings;
@@ -124,6 +126,7 @@ fn data_path(name: &str) -> PathBuf {
124fn transport(
126fn transport(
125 endpoint: Option<&str>,
127 endpoint: Option<&str>,
126 database: Option<&std::path::Path>,
128 database: Option<&std::path::Path>,
129 #[cfg(windows)] sign_in_title: String,
127) -> Arc<dyn session::Transport> {
130) -> Arc<dyn session::Transport> {
128 #[cfg(windows)]
131 #[cfg(windows)]
129 if endpoint.is_none() {
132 if endpoint.is_none() {
@@ -134,7 +137,7 @@ fn transport(
134 inline_video::configure(user_data_folder.clone());
137 inline_video::configure(user_data_folder.clone());
135 let transport = webview::start(webview::HostConfig {
138 let transport = webview::start(webview::HostConfig {
136 user_data_folder,
139 user_data_folder,
137 window_title: format!("{APP_NAME} - Sign in"),
140 window_title: sign_in_title,
138 log: |line| app_base::diagnostics::record(line),
141 log: |line| app_base::diagnostics::record(line),
139 });
142 });
140 task_dialog::install_host(transport.clone());
143 task_dialog::install_host(transport.clone());
@@ -142,7 +145,7 @@ fn transport(
142 }
145 }
143 #[cfg(not(windows))]
146 #[cfg(not(windows))]
144 let _ = database;
147 let _ = database;
145 #[cfg(target_os = "linux")]
148 #[cfg(any(target_os = "linux", target_os = "macos"))]
146 if endpoint.is_none() {
149 if endpoint.is_none() {
147 return linux_browser::start(session::DEFAULT_ENDPOINT);
150 return linux_browser::start(session::DEFAULT_ENDPOINT);
148 }
151 }
@@ -176,8 +179,6 @@ fn main() {
176 data_path(crash_log::CRASH_LOG_FILE),
179 data_path(crash_log::CRASH_LOG_FILE),
177 );
180 );
178 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
181 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
179 #[cfg(target_os = "linux")]
180 app_base::linux_fonts::hide_system_color_emoji();
181 let arguments = parse_arguments();
182 let arguments = parse_arguments();
182 if !arguments.demo && arguments.database.is_none() {
183 if !arguments.demo && arguments.database.is_none() {
183 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
184 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
@@ -219,8 +220,24 @@ fn main() {
219 open_store(&path)
220 open_store(&path)
220 };
221 };
221 let store = Arc::new(store);
222 let store = Arc::new(store);
223 app_base::ui_locale::apply_locale(app_base::ui_locale::effective_locale(app_base::ui_locale::load(
224 &store,
225 )));
226 #[cfg(windows)]
227 let sign_in_title = format!(
228 "{} - {}",
229 app_base::APP_NAME,
230 app_base::ui_locale::tr("auth.sign_in")
231 );
222 let user_input = user_activity::UserInput::new();
232 let user_input = user_activity::UserInput::new();
223 let receiver = (!arguments.demo).then(|| {
233 let receiver = (!arguments.demo).then(|| {
234 #[cfg(windows)]
235 let transport = transport(
236 arguments.endpoint.as_deref(),
237 arguments.database.as_deref(),
238 sign_in_title.clone(),
239 );
240 #[cfg(not(windows))]
224 let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
241 let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
225 let activity = user_activity::track(user_input.clone());
242 let activity = user_activity::track(user_input.clone());
226 backend::start(store.clone(), transport, !arguments.read_only, activity)
243 backend::start(store.clone(), transport, !arguments.read_only, activity)
@@ -242,6 +259,7 @@ fn main() {
242 .detach();
259 .detach();
243 theme::load_fonts(cx);
260 theme::load_fonts(cx);
244 active_appearance::install(&store, cx);
261 active_appearance::install(&store, cx);
262 active_locale::install(&store, cx);
245 theme::apply(cx);
263 theme::apply(cx);
246 bind_keys(cx);
264 bind_keys(cx);
247 let state = cx.new(|_| {
265 let state = cx.new(|_| {
@@ -262,7 +280,7 @@ fn main() {
262 while let Some(event) = receiver.recv().await {
280 while let Some(event) = receiver.recv().await {
263 let kind = event.kind();
281 let kind = event.kind();
264 let started = std::time::Instant::now();
282 let started = std::time::Instant::now();
265 #[cfg(target_os = "linux")]
283 #[cfg(any(target_os = "linux", target_os = "macos"))]
266 linux_browser::note_backend_event(&event);
284 linux_browser::note_backend_event(&event);
267 state.update(cx, |state, cx| state.apply(event, cx));
285 state.update(cx, |state, cx| state.apply(event, cx));
268 app_base::diagnostics::record_if_slow(&kind, started.elapsed());
286 app_base::diagnostics::record_if_slow(&kind, started.elapsed());
@@ -309,7 +327,7 @@ fn main() {
309 .detach();
327 .detach();
310 });
328 });
311 presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
329 presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
312 #[cfg(target_os = "linux")]
330 #[cfg(any(target_os = "linux", target_os = "macos"))]
313 linux_browser::stop();
331 linux_browser::stop();
314 #[cfg(windows)]
332 #[cfg(windows)]
315 updater::exit_now();
333 updater::exit_now();
crates/browser/src/config.rs +131 −8
@@ -10,12 +10,18 @@ const CHROME_RELATIVE: &str = r"Google\Chrome\Application\chrome.exe";
10 10 const WINDOWS_VARIABLES: [&str; 4] = ["LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "TEMP"];
11 11 const LINUX_CHROME_NAMES: [&str; 5] =
12 12 ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome"];
13 const MACOS_CHROME_NAMES: [&str; 3] = ["google-chrome", "chromium", "chrome"];
14 const MACOS_CHROME_APP_PATHS: [&str; 2] = [
15 "Google Chrome.app/Contents/MacOS/Google Chrome",
16 "Chromium.app/Contents/MacOS/Chromium",
17 ];
13 18
14 19 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
15 20 pub enum Platform {
16 21 Wsl,
17 22 Windows,
18 23 Linux,
24 Macos,
19 25 }
20 26
21 27 impl Platform {
@@ -23,6 +29,9 @@ impl Platform {
23 29 if cfg!(windows) {
24 30 return Platform::Windows;
25 31 }
32 if cfg!(target_os = "macos") {
33 return Platform::Macos;
34 }
26 35 let proc_version = std::fs::read_to_string("/proc/version").ok();
27 36 Platform::from_proc_version(proc_version.as_deref())
28 37 }
@@ -33,12 +42,18 @@ impl Platform {
33 42 _ => Platform::Linux,
34 43 }
35 44 }
45
46 pub fn uses_unix_paths(self) -> bool {
47 matches!(self, Platform::Linux | Platform::Macos)
48 }
36 49 }
37 50
38 51 #[derive(Debug, Clone)]
39 52 pub(crate) enum ChromeSearch {
40 53 Files(Vec<PathBuf>),
41 54 Named(Vec<String>),
55 /// Absolute install paths first, then PATH names (macOS Application bundles + CLI).
56 FilesThenNamed { files: Vec<PathBuf>, names: Vec<String> },
42 57 }
43 58
44 59 #[derive(Debug, Clone)]
@@ -55,6 +70,7 @@ pub struct Config {
55 70 pub struct ConfigInputs<'a> {
56 71 pub windows_variables: HashMap<String, String>,
57 72 pub linux_data_dir: Option<PathBuf>,
73 pub home_dir: Option<PathBuf>,
58 74 pub to_local: &'a dyn Fn(&str) -> String,
59 75 }
60 76
@@ -62,14 +78,16 @@ impl Config {
62 78 pub fn detect() -> Result<Config, BrowserError> {
63 79 let platform = Platform::detect();
64 80 let windows_variables = match platform {
65 Platform::Linux => HashMap::new(),
81 Platform::Linux | Platform::Macos => HashMap::new(),
66 82 Platform::Windows => WINDOWS_VARIABLES
67 83 .iter()
68 84 .filter_map(|name| std::env::var(name).ok().map(|value| ((*name).to_owned(), value)))
69 85 .collect(),
70 86 Platform::Wsl => wsl_windows_variables()?,
71 87 };
72 let linux_data_dir = directories::BaseDirs::new().map(|dirs| dirs.data_dir().to_path_buf());
88 let base = directories::BaseDirs::new();
89 let linux_data_dir = base.as_ref().map(|dirs| dirs.data_dir().to_path_buf());
90 let home_dir = base.as_ref().map(|dirs| dirs.home_dir().to_path_buf());
73 91 let to_local = |windows_path: &str| match platform {
74 92 Platform::Wsl => wslpath(windows_path).unwrap_or_else(|| windows_path_to_wsl(windows_path)),
75 93 _ => windows_path.to_owned(),
@@ -77,7 +95,7 @@ impl Config {
77 95 Config::resolve(
78 96 platform,
79 97 DEFAULT_PORT,
80 &ConfigInputs { windows_variables, linux_data_dir, to_local: &to_local },
98 &ConfigInputs { windows_variables, linux_data_dir, home_dir, to_local: &to_local },
81 99 )
82 100 }
83 101
@@ -104,6 +122,32 @@ impl Config {
104 122 ),
105 123 }
106 124 }
125 Platform::Macos => {
126 let data_dir = inputs.linux_data_dir.clone().ok_or_else(|| {
127 BrowserError::Environment("no Application Support directory".into())
128 })?;
129 let mut files = Vec::new();
130 for root in [PathBuf::from("/Applications")]
131 .into_iter()
132 .chain(inputs.home_dir.iter().map(|home| home.join("Applications")))
133 {
134 for relative in MACOS_CHROME_APP_PATHS {
135 files.push(root.join(relative));
136 }
137 }
138 Config {
139 platform,
140 port,
141 profile: format!("{}/{}", path_text(&data_dir), PROFILE_NAME),
142 mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),
143 profile_parent: path_text(&data_dir),
144 mode_parent: data_dir,
145 chrome_search: ChromeSearch::FilesThenNamed {
146 files,
147 names: MACOS_CHROME_NAMES.iter().map(|name| (*name).to_owned()).collect(),
148 },
149 }
150 }
107 151 Platform::Windows | Platform::Wsl => {
108 152 let local = inputs.windows_variables.get("LOCALAPPDATA").ok_or_else(|| missing("LOCALAPPDATA"))?;
109 153 let candidates = ["PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"]
@@ -131,7 +175,7 @@ impl Config {
131 175 }
132 176
133 177 pub fn with_profile_name(mut self, name: &str) -> Config {
134 let separator = if self.platform == Platform::Linux { "/" } else { "\\" };
178 let separator = if self.platform.uses_unix_paths() { "/" } else { "\\" };
135 179 self.profile = format!("{}{separator}{name}", self.profile_parent);
136 180 self.mode_file = self.mode_parent.join(format!("{name}.mode"));
137 181 self
@@ -147,6 +191,16 @@ fn path_text(path: &Path) -> String {
147 191 path.to_string_lossy().into_owned()
148 192 }
149 193
194 fn find_named_chrome(
195 names: &[String],
196 path_variable: &std::ffi::OsStr,
197 exists: &dyn Fn(&Path) -> bool,
198 ) -> Option<PathBuf> {
199 std::env::split_paths(path_variable)
200 .flat_map(|directory| names.iter().map(move |name| directory.join(name)))
201 .find(|candidate| exists(candidate))
202 }
203
150 204 pub(crate) fn find_chrome(
151 205 search: &ChromeSearch,
152 206 path_variable: &std::ffi::OsStr,
@@ -158,10 +212,18 @@ pub(crate) fn find_chrome(
158 212 .find(|candidate| exists(candidate))
159 213 .cloned()
160 214 .ok_or_else(|| BrowserError::ChromeNotFound("not under Program Files or LocalAppData".into())),
161 ChromeSearch::Named(names) => std::env::split_paths(path_variable)
162 .flat_map(|directory| names.iter().map(move |name| directory.join(name)))
163 .find(|candidate| exists(candidate))
215 ChromeSearch::Named(names) => find_named_chrome(names, path_variable, exists)
164 216 .ok_or_else(|| BrowserError::ChromeNotFound(format!("none of {} on PATH", names.join(", ")))),
217 ChromeSearch::FilesThenNamed { files, names } => files
218 .iter()
219 .find(|candidate| exists(candidate))
220 .cloned()
221 .or_else(|| find_named_chrome(names, path_variable, exists))
222 .ok_or_else(|| {
223 BrowserError::ChromeNotFound(
224 "not under /Applications, ~/Applications, or PATH".into(),
225 )
226 }),
165 227 }
166 228 }
167 229
@@ -224,6 +286,7 @@ mod tests {
224 286 ConfigInputs {
225 287 windows_variables: variables.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect(),
226 288 linux_data_dir: None,
289 home_dir: None,
227 290 to_local,
228 291 }
229 292 }
@@ -283,6 +346,7 @@ mod tests {
283 346 let inputs = ConfigInputs {
284 347 windows_variables: [("LOCALAPPDATA".to_owned(), r"D:\L".to_owned())].into(),
285 348 linux_data_dir: None,
349 home_dir: None,
286 350 to_local: &to_local,
287 351 };
288 352 let config = Config::resolve(Platform::Windows, 9222, &inputs).unwrap();
@@ -305,6 +369,7 @@ mod tests {
305 369 let inputs = ConfigInputs {
306 370 windows_variables: HashMap::new(),
307 371 linux_data_dir: Some(PathBuf::from("/home/u/.local/share")),
372 home_dir: None,
308 373 to_local: &to_local,
309 374 };
310 375 let config = Config::resolve(Platform::Linux, 9222, &inputs).unwrap();
@@ -312,13 +377,71 @@ mod tests {
312 377 assert_eq!(config.mode_file, PathBuf::from("/home/u/.local/share/rusty-teams-chrome.mode"));
313 378 }
314 379
380 #[test]
381 fn resolves_macos_config_under_application_support() {
382 let to_local = |path: &str| path.to_owned();
383 let inputs = ConfigInputs {
384 windows_variables: HashMap::new(),
385 linux_data_dir: Some(PathBuf::from("/Users/joe/Library/Application Support")),
386 home_dir: Some(PathBuf::from("/Users/joe")),
387 to_local: &to_local,
388 };
389 let config = Config::resolve(Platform::Macos, 9222, &inputs).unwrap();
390 assert_eq!(
391 config.profile,
392 "/Users/joe/Library/Application Support/rusty-teams-chrome"
393 );
394 assert_eq!(
395 config.mode_file,
396 PathBuf::from("/Users/joe/Library/Application Support/rusty-teams-chrome.mode")
397 );
398 let ChromeSearch::FilesThenNamed { files, names } = &config.chrome_search else {
399 panic!("expected files then named")
400 };
401 assert_eq!(
402 files[0],
403 PathBuf::from("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
404 );
405 assert_eq!(
406 files[2],
407 PathBuf::from("/Users/joe/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
408 );
409 assert!(names.iter().any(|name| name == "google-chrome"));
410 assert_eq!(config.with_profile_name("x").profile, "/Users/joe/Library/Application Support/x");
411 }
412
315 413 #[test]
316 414 fn missing_localappdata_is_an_error() {
317 415 let to_local = |path: &str| path.to_owned();
318 let inputs = ConfigInputs { windows_variables: HashMap::new(), linux_data_dir: None, to_local: &to_local };
416 let inputs = ConfigInputs {
417 windows_variables: HashMap::new(),
418 linux_data_dir: None,
419 home_dir: None,
420 to_local: &to_local,
421 };
319 422 assert!(Config::resolve(Platform::Windows, 9222, &inputs).is_err());
320 423 }
321 424
425 #[test]
426 fn finds_macos_chrome_under_applications_before_path() {
427 let search = ChromeSearch::FilesThenNamed {
428 files: vec![
429 "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".into(),
430 "/Users/joe/Applications/Chromium.app/Contents/MacOS/Chromium".into(),
431 ],
432 names: vec!["google-chrome".into()],
433 };
434 let path = std::env::join_paths(["/usr/local/bin"]).unwrap();
435 let found = find_chrome(&search, &path, &|candidate| {
436 candidate.ends_with("Google Chrome") || candidate.ends_with("google-chrome")
437 })
438 .unwrap();
439 assert_eq!(
440 found,
441 PathBuf::from("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
442 );
443 }
444
322 445 #[test]
323 446 fn overrides_port_and_profile_name() {
324 447 let to_local = |path: &str| windows_path_to_wsl(path);
@@ -10,12 +10,18 @@ const CHROME_RELATIVE: &str = r"Google\Chrome\Application\chrome.exe";
10const WINDOWS_VARIABLES: [&str; 4] = ["LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "TEMP"];
10const WINDOWS_VARIABLES: [&str; 4] = ["LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "TEMP"];
11const LINUX_CHROME_NAMES: [&str; 5] =
11const LINUX_CHROME_NAMES: [&str; 5] =
12 ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome"];
12 ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome"];
13const MACOS_CHROME_NAMES: [&str; 3] = ["google-chrome", "chromium", "chrome"];
14const MACOS_CHROME_APP_PATHS: [&str; 2] = [
15 "Google Chrome.app/Contents/MacOS/Google Chrome",
16 "Chromium.app/Contents/MacOS/Chromium",
17];
13
18
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Platform {
20pub enum Platform {
16 Wsl,
21 Wsl,
17 Windows,
22 Windows,
18 Linux,
23 Linux,
24 Macos,
19}
25}
20
26
21impl Platform {
27impl Platform {
@@ -23,6 +29,9 @@ impl Platform {
23 if cfg!(windows) {
29 if cfg!(windows) {
24 return Platform::Windows;
30 return Platform::Windows;
25 }
31 }
32 if cfg!(target_os = "macos") {
33 return Platform::Macos;
34 }
26 let proc_version = std::fs::read_to_string("/proc/version").ok();
35 let proc_version = std::fs::read_to_string("/proc/version").ok();
27 Platform::from_proc_version(proc_version.as_deref())
36 Platform::from_proc_version(proc_version.as_deref())
28 }
37 }
@@ -33,12 +42,18 @@ impl Platform {
33 _ => Platform::Linux,
42 _ => Platform::Linux,
34 }
43 }
35 }
44 }
45
46 pub fn uses_unix_paths(self) -> bool {
47 matches!(self, Platform::Linux | Platform::Macos)
48 }
36}
49}
37
50
38#[derive(Debug, Clone)]
51#[derive(Debug, Clone)]
39pub(crate) enum ChromeSearch {
52pub(crate) enum ChromeSearch {
40 Files(Vec<PathBuf>),
53 Files(Vec<PathBuf>),
41 Named(Vec<String>),
54 Named(Vec<String>),
55 /// Absolute install paths first, then PATH names (macOS Application bundles + CLI).
56 FilesThenNamed { files: Vec<PathBuf>, names: Vec<String> },
42}
57}
43
58
44#[derive(Debug, Clone)]
59#[derive(Debug, Clone)]
@@ -55,6 +70,7 @@ pub struct Config {
55pub struct ConfigInputs<'a> {
70pub struct ConfigInputs<'a> {
56 pub windows_variables: HashMap<String, String>,
71 pub windows_variables: HashMap<String, String>,
57 pub linux_data_dir: Option<PathBuf>,
72 pub linux_data_dir: Option<PathBuf>,
73 pub home_dir: Option<PathBuf>,
58 pub to_local: &'a dyn Fn(&str) -> String,
74 pub to_local: &'a dyn Fn(&str) -> String,
59}
75}
60
76
@@ -62,14 +78,16 @@ impl Config {
62 pub fn detect() -> Result<Config, BrowserError> {
78 pub fn detect() -> Result<Config, BrowserError> {
63 let platform = Platform::detect();
79 let platform = Platform::detect();
64 let windows_variables = match platform {
80 let windows_variables = match platform {
65 Platform::Linux => HashMap::new(),
81 Platform::Linux | Platform::Macos => HashMap::new(),
66 Platform::Windows => WINDOWS_VARIABLES
82 Platform::Windows => WINDOWS_VARIABLES
67 .iter()
83 .iter()
68 .filter_map(|name| std::env::var(name).ok().map(|value| ((*name).to_owned(), value)))
84 .filter_map(|name| std::env::var(name).ok().map(|value| ((*name).to_owned(), value)))
69 .collect(),
85 .collect(),
70 Platform::Wsl => wsl_windows_variables()?,
86 Platform::Wsl => wsl_windows_variables()?,
71 };
87 };
72 let linux_data_dir = directories::BaseDirs::new().map(|dirs| dirs.data_dir().to_path_buf());
88 let base = directories::BaseDirs::new();
89 let linux_data_dir = base.as_ref().map(|dirs| dirs.data_dir().to_path_buf());
90 let home_dir = base.as_ref().map(|dirs| dirs.home_dir().to_path_buf());
73 let to_local = |windows_path: &str| match platform {
91 let to_local = |windows_path: &str| match platform {
74 Platform::Wsl => wslpath(windows_path).unwrap_or_else(|| windows_path_to_wsl(windows_path)),
92 Platform::Wsl => wslpath(windows_path).unwrap_or_else(|| windows_path_to_wsl(windows_path)),
75 _ => windows_path.to_owned(),
93 _ => windows_path.to_owned(),
@@ -77,7 +95,7 @@ impl Config {
77 Config::resolve(
95 Config::resolve(
78 platform,
96 platform,
79 DEFAULT_PORT,
97 DEFAULT_PORT,
80 &ConfigInputs { windows_variables, linux_data_dir, to_local: &to_local },
98 &ConfigInputs { windows_variables, linux_data_dir, home_dir, to_local: &to_local },
81 )
99 )
82 }
100 }
83
101
@@ -104,6 +122,32 @@ impl Config {
104 ),
122 ),
105 }
123 }
106 }
124 }
125 Platform::Macos => {
126 let data_dir = inputs.linux_data_dir.clone().ok_or_else(|| {
127 BrowserError::Environment("no Application Support directory".into())
128 })?;
129 let mut files = Vec::new();
130 for root in [PathBuf::from("/Applications")]
131 .into_iter()
132 .chain(inputs.home_dir.iter().map(|home| home.join("Applications")))
133 {
134 for relative in MACOS_CHROME_APP_PATHS {
135 files.push(root.join(relative));
136 }
137 }
138 Config {
139 platform,
140 port,
141 profile: format!("{}/{}", path_text(&data_dir), PROFILE_NAME),
142 mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),
143 profile_parent: path_text(&data_dir),
144 mode_parent: data_dir,
145 chrome_search: ChromeSearch::FilesThenNamed {
146 files,
147 names: MACOS_CHROME_NAMES.iter().map(|name| (*name).to_owned()).collect(),
148 },
149 }
150 }
107 Platform::Windows | Platform::Wsl => {
151 Platform::Windows | Platform::Wsl => {
108 let local = inputs.windows_variables.get("LOCALAPPDATA").ok_or_else(|| missing("LOCALAPPDATA"))?;
152 let local = inputs.windows_variables.get("LOCALAPPDATA").ok_or_else(|| missing("LOCALAPPDATA"))?;
109 let candidates = ["PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"]
153 let candidates = ["PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"]
@@ -131,7 +175,7 @@ impl Config {
131 }
175 }
132
176
133 pub fn with_profile_name(mut self, name: &str) -> Config {
177 pub fn with_profile_name(mut self, name: &str) -> Config {
134 let separator = if self.platform == Platform::Linux { "/" } else { "\\" };
178 let separator = if self.platform.uses_unix_paths() { "/" } else { "\\" };
135 self.profile = format!("{}{separator}{name}", self.profile_parent);
179 self.profile = format!("{}{separator}{name}", self.profile_parent);
136 self.mode_file = self.mode_parent.join(format!("{name}.mode"));
180 self.mode_file = self.mode_parent.join(format!("{name}.mode"));
137 self
181 self
@@ -147,6 +191,16 @@ fn path_text(path: &Path) -> String {
147 path.to_string_lossy().into_owned()
191 path.to_string_lossy().into_owned()
148}
192}
149
193
194fn find_named_chrome(
195 names: &[String],
196 path_variable: &std::ffi::OsStr,
197 exists: &dyn Fn(&Path) -> bool,
198) -> Option<PathBuf> {
199 std::env::split_paths(path_variable)
200 .flat_map(|directory| names.iter().map(move |name| directory.join(name)))
201 .find(|candidate| exists(candidate))
202}
203
150pub(crate) fn find_chrome(
204pub(crate) fn find_chrome(
151 search: &ChromeSearch,
205 search: &ChromeSearch,
152 path_variable: &std::ffi::OsStr,
206 path_variable: &std::ffi::OsStr,
@@ -158,10 +212,18 @@ pub(crate) fn find_chrome(
158 .find(|candidate| exists(candidate))
212 .find(|candidate| exists(candidate))
159 .cloned()
213 .cloned()
160 .ok_or_else(|| BrowserError::ChromeNotFound("not under Program Files or LocalAppData".into())),
214 .ok_or_else(|| BrowserError::ChromeNotFound("not under Program Files or LocalAppData".into())),
161 ChromeSearch::Named(names) => std::env::split_paths(path_variable)
215 ChromeSearch::Named(names) => find_named_chrome(names, path_variable, exists)
162 .flat_map(|directory| names.iter().map(move |name| directory.join(name)))
163 .find(|candidate| exists(candidate))
164 .ok_or_else(|| BrowserError::ChromeNotFound(format!("none of {} on PATH", names.join(", ")))),
216 .ok_or_else(|| BrowserError::ChromeNotFound(format!("none of {} on PATH", names.join(", ")))),
217 ChromeSearch::FilesThenNamed { files, names } => files
218 .iter()
219 .find(|candidate| exists(candidate))
220 .cloned()
221 .or_else(|| find_named_chrome(names, path_variable, exists))
222 .ok_or_else(|| {
223 BrowserError::ChromeNotFound(
224 "not under /Applications, ~/Applications, or PATH".into(),
225 )
226 }),
165 }
227 }
166}
228}
167
229
@@ -224,6 +286,7 @@ mod tests {
224 ConfigInputs {
286 ConfigInputs {
225 windows_variables: variables.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect(),
287 windows_variables: variables.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect(),
226 linux_data_dir: None,
288 linux_data_dir: None,
289 home_dir: None,
227 to_local,
290 to_local,
228 }
291 }
229 }
292 }
@@ -283,6 +346,7 @@ mod tests {
283 let inputs = ConfigInputs {
346 let inputs = ConfigInputs {
284 windows_variables: [("LOCALAPPDATA".to_owned(), r"D:\L".to_owned())].into(),
347 windows_variables: [("LOCALAPPDATA".to_owned(), r"D:\L".to_owned())].into(),
285 linux_data_dir: None,
348 linux_data_dir: None,
349 home_dir: None,
286 to_local: &to_local,
350 to_local: &to_local,
287 };
351 };
288 let config = Config::resolve(Platform::Windows, 9222, &inputs).unwrap();
352 let config = Config::resolve(Platform::Windows, 9222, &inputs).unwrap();
@@ -305,6 +369,7 @@ mod tests {
305 let inputs = ConfigInputs {
369 let inputs = ConfigInputs {
306 windows_variables: HashMap::new(),
370 windows_variables: HashMap::new(),
307 linux_data_dir: Some(PathBuf::from("/home/u/.local/share")),
371 linux_data_dir: Some(PathBuf::from("/home/u/.local/share")),
372 home_dir: None,
308 to_local: &to_local,
373 to_local: &to_local,
309 };
374 };
310 let config = Config::resolve(Platform::Linux, 9222, &inputs).unwrap();
375 let config = Config::resolve(Platform::Linux, 9222, &inputs).unwrap();
@@ -312,13 +377,71 @@ mod tests {
312 assert_eq!(config.mode_file, PathBuf::from("/home/u/.local/share/rusty-teams-chrome.mode"));
377 assert_eq!(config.mode_file, PathBuf::from("/home/u/.local/share/rusty-teams-chrome.mode"));
313 }
378 }
314
379
380 #[test]
381 fn resolves_macos_config_under_application_support() {
382 let to_local = |path: &str| path.to_owned();
383 let inputs = ConfigInputs {
384 windows_variables: HashMap::new(),
385 linux_data_dir: Some(PathBuf::from("/Users/joe/Library/Application Support")),
386 home_dir: Some(PathBuf::from("/Users/joe")),
387 to_local: &to_local,
388 };
389 let config = Config::resolve(Platform::Macos, 9222, &inputs).unwrap();
390 assert_eq!(
391 config.profile,
392 "/Users/joe/Library/Application Support/rusty-teams-chrome"
393 );
394 assert_eq!(
395 config.mode_file,
396 PathBuf::from("/Users/joe/Library/Application Support/rusty-teams-chrome.mode")
397 );
398 let ChromeSearch::FilesThenNamed { files, names } = &config.chrome_search else {
399 panic!("expected files then named")
400 };
401 assert_eq!(
402 files[0],
403 PathBuf::from("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
404 );
405 assert_eq!(
406 files[2],
407 PathBuf::from("/Users/joe/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
408 );
409 assert!(names.iter().any(|name| name == "google-chrome"));
410 assert_eq!(config.with_profile_name("x").profile, "/Users/joe/Library/Application Support/x");
411 }
412
315 #[test]
413 #[test]
316 fn missing_localappdata_is_an_error() {
414 fn missing_localappdata_is_an_error() {
317 let to_local = |path: &str| path.to_owned();
415 let to_local = |path: &str| path.to_owned();
318 let inputs = ConfigInputs { windows_variables: HashMap::new(), linux_data_dir: None, to_local: &to_local };
416 let inputs = ConfigInputs {
417 windows_variables: HashMap::new(),
418 linux_data_dir: None,
419 home_dir: None,
420 to_local: &to_local,
421 };
319 assert!(Config::resolve(Platform::Windows, 9222, &inputs).is_err());
422 assert!(Config::resolve(Platform::Windows, 9222, &inputs).is_err());
320 }
423 }
321
424
425 #[test]
426 fn finds_macos_chrome_under_applications_before_path() {
427 let search = ChromeSearch::FilesThenNamed {
428 files: vec![
429 "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".into(),
430 "/Users/joe/Applications/Chromium.app/Contents/MacOS/Chromium".into(),
431 ],
432 names: vec!["google-chrome".into()],
433 };
434 let path = std::env::join_paths(["/usr/local/bin"]).unwrap();
435 let found = find_chrome(&search, &path, &|candidate| {
436 candidate.ends_with("Google Chrome") || candidate.ends_with("google-chrome")
437 })
438 .unwrap();
439 assert_eq!(
440 found,
441 PathBuf::from("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
442 );
443 }
444
322 #[test]
445 #[test]
323 fn overrides_port_and_profile_name() {
446 fn overrides_port_and_profile_name() {
324 let to_local = |path: &str| windows_path_to_wsl(path);
447 let to_local = |path: &str| windows_path_to_wsl(path);
crates/browser/src/launch.rs +19 −7
@@ -56,7 +56,11 @@ pub fn chrome_arguments(spec: &ArgumentSpec) -> Vec<String> {
56 56 }
57 57
58 58 pub fn user_agent(platform: Platform, major: u32) -> String {
59 let system = if platform == Platform::Linux { "X11; Linux x86_64" } else { "Windows NT 10.0; Win64; x64" };
59 let system = match platform {
60 Platform::Linux => "X11; Linux x86_64",
61 Platform::Macos => "Macintosh; Intel Mac OS X 10_15_7",
62 Platform::Windows | Platform::Wsl => "Windows NT 10.0; Win64; x64",
63 };
60 64 format!("Mozilla/5.0 ({system}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36")
61 65 }
62 66
@@ -80,16 +84,21 @@ const FALLBACK_MAJOR: u32 = 150;
80 84
81 85 fn chrome_major(platform: Platform, executable: &Path) -> u32 {
82 86 let detected = match platform {
83 Platform::Linux => Command::new(executable)
87 Platform::Linux | Platform::Macos => Command::new(executable)
84 88 .arg("--version")
85 89 .output()
86 90 .ok()
87 91 .and_then(|output| major_from_version_output(&String::from_utf8_lossy(&output.stdout))),
88 _ => executable.parent().and_then(|parent| std::fs::read_dir(parent).ok()).and_then(|entries| {
89 let names: Vec<String> =
90 entries.flatten().map(|entry| entry.file_name().to_string_lossy().into_owned()).collect();
91 major_from_directory_names(names.iter().map(String::as_str))
92 }),
92 Platform::Windows | Platform::Wsl => executable
93 .parent()
94 .and_then(|parent| std::fs::read_dir(parent).ok())
95 .and_then(|entries| {
96 let names: Vec<String> = entries
97 .flatten()
98 .map(|entry| entry.file_name().to_string_lossy().into_owned())
99 .collect();
100 major_from_directory_names(names.iter().map(String::as_str))
101 }),
93 102 };
94 103 detected.unwrap_or(FALLBACK_MAJOR)
95 104 }
@@ -189,6 +198,9 @@ mod tests {
189 198 assert!(user_agent(Platform::Wsl, 154).contains("Windows NT 10.0; Win64; x64"));
190 199 assert!(user_agent(Platform::Windows, 154).contains("Chrome/154.0.0.0"));
191 200 assert!(user_agent(Platform::Linux, 140).contains("X11; Linux x86_64"));
201 assert!(user_agent(Platform::Macos, 154).contains("Macintosh; Intel Mac OS X 10_15_7"));
202 assert!(user_agent(Platform::Macos, 154).contains("Chrome/154.0.0.0"));
203 assert!(!user_agent(Platform::Macos, 154).contains("Windows NT"));
192 204 }
193 205
194 206 #[test]
@@ -56,7 +56,11 @@ pub fn chrome_arguments(spec: &ArgumentSpec) -> Vec<String> {
56}
56}
57
57
58pub fn user_agent(platform: Platform, major: u32) -> String {
58pub fn user_agent(platform: Platform, major: u32) -> String {
59 let system = if platform == Platform::Linux { "X11; Linux x86_64" } else { "Windows NT 10.0; Win64; x64" };
59 let system = match platform {
60 Platform::Linux => "X11; Linux x86_64",
61 Platform::Macos => "Macintosh; Intel Mac OS X 10_15_7",
62 Platform::Windows | Platform::Wsl => "Windows NT 10.0; Win64; x64",
63 };
60 format!("Mozilla/5.0 ({system}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36")
64 format!("Mozilla/5.0 ({system}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36")
61}
65}
62
66
@@ -80,16 +84,21 @@ const FALLBACK_MAJOR: u32 = 150;
80
84
81fn chrome_major(platform: Platform, executable: &Path) -> u32 {
85fn chrome_major(platform: Platform, executable: &Path) -> u32 {
82 let detected = match platform {
86 let detected = match platform {
83 Platform::Linux => Command::new(executable)
87 Platform::Linux | Platform::Macos => Command::new(executable)
84 .arg("--version")
88 .arg("--version")
85 .output()
89 .output()
86 .ok()
90 .ok()
87 .and_then(|output| major_from_version_output(&String::from_utf8_lossy(&output.stdout))),
91 .and_then(|output| major_from_version_output(&String::from_utf8_lossy(&output.stdout))),
88 _ => executable.parent().and_then(|parent| std::fs::read_dir(parent).ok()).and_then(|entries| {
92 Platform::Windows | Platform::Wsl => executable
89 let names: Vec<String> =
93 .parent()
90 entries.flatten().map(|entry| entry.file_name().to_string_lossy().into_owned()).collect();
94 .and_then(|parent| std::fs::read_dir(parent).ok())
91 major_from_directory_names(names.iter().map(String::as_str))
95 .and_then(|entries| {
92 }),
96 let names: Vec<String> = entries
97 .flatten()
98 .map(|entry| entry.file_name().to_string_lossy().into_owned())
99 .collect();
100 major_from_directory_names(names.iter().map(String::as_str))
101 }),
93 };
102 };
94 detected.unwrap_or(FALLBACK_MAJOR)
103 detected.unwrap_or(FALLBACK_MAJOR)
95}
104}
@@ -189,6 +198,9 @@ mod tests {
189 assert!(user_agent(Platform::Wsl, 154).contains("Windows NT 10.0; Win64; x64"));
198 assert!(user_agent(Platform::Wsl, 154).contains("Windows NT 10.0; Win64; x64"));
190 assert!(user_agent(Platform::Windows, 154).contains("Chrome/154.0.0.0"));
199 assert!(user_agent(Platform::Windows, 154).contains("Chrome/154.0.0.0"));
191 assert!(user_agent(Platform::Linux, 140).contains("X11; Linux x86_64"));
200 assert!(user_agent(Platform::Linux, 140).contains("X11; Linux x86_64"));
201 assert!(user_agent(Platform::Macos, 154).contains("Macintosh; Intel Mac OS X 10_15_7"));
202 assert!(user_agent(Platform::Macos, 154).contains("Chrome/154.0.0.0"));
203 assert!(!user_agent(Platform::Macos, 154).contains("Windows NT"));
192 }
204 }
193
205
194 #[test]
206 #[test]
crates/browser/src/process.rs +24 −1
@@ -21,6 +21,14 @@ pub(crate) fn parse_netstat_pid(output: &str, port: u16) -> Option<u32> {
21 21 })
22 22 }
23 23
24 /// First LISTEN row's PID column from `lsof -nP -iTCP:<port> -sTCP:LISTEN`.
25 pub(crate) fn parse_lsof_pid(output: &str) -> Option<u32> {
26 output.lines().skip(1).find_map(|line| {
27 let columns: Vec<&str> = line.split_whitespace().collect();
28 columns.get(1)?.parse().ok()
29 })
30 }
31
24 32 fn run(program: &str, arguments: &[&str]) -> Result<String, BrowserError> {
25 33 let output = Command::new(program).args(arguments).output()?;
26 34 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
@@ -29,6 +37,9 @@ fn run(program: &str, arguments: &[&str]) -> Result<String, BrowserError> {
29 37 fn listener_pid(platform: Platform, port: u16) -> Result<u32, BrowserError> {
30 38 let pid = match platform {
31 39 Platform::Linux => parse_ss_pid(&run("ss", &["-ltnpH", &format!("sport = :{port}")])?),
40 Platform::Macos => {
41 parse_lsof_pid(&run("lsof", &["-nP", &format!("-iTCP:{port}"), "-sTCP:LISTEN"])?)
42 }
32 43 Platform::Windows => parse_netstat_pid(&run("netstat", &["-ano", "-p", "TCP"])?, port),
33 44 Platform::Wsl => parse_netstat_pid(&run("netstat.exe", &["-ano", "-p", "TCP"])?, port),
34 45 };
@@ -38,6 +49,8 @@ fn listener_pid(platform: Platform, port: u16) -> Result<u32, BrowserError> {
38 49 pub(crate) fn is_chrome_image(image_name: &str) -> bool {
39 50 let lowered = image_name.trim().trim_matches('"').to_ascii_lowercase();
40 51 lowered.starts_with("chrome")
52 || lowered.starts_with("google chrome")
53 || lowered.starts_with("chromium")
41 54 }
42 55
43 56 fn process_image_name(platform: Platform, pid: &str) -> Result<String, BrowserError> {
@@ -45,6 +58,7 @@ fn process_image_name(platform: Platform, pid: &str) -> Result<String, BrowserEr
45 58 let csv_arguments = ["/FI", filter.as_str(), "/FO", "CSV", "/NH"];
46 59 let output = match platform {
47 60 Platform::Linux => std::fs::read_to_string(format!("/proc/{pid}/comm"))?,
61 Platform::Macos => run("ps", &["-p", pid, "-o", "comm="])?,
48 62 Platform::Windows => run("tasklist", &csv_arguments)?,
49 63 Platform::Wsl => run("tasklist.exe", &csv_arguments)?,
50 64 };
@@ -58,7 +72,7 @@ pub(crate) fn kill_listener(platform: Platform, port: u16) -> Result<(), Browser
58 72 return Err(BrowserError::Cdp(format!("port {port} is held by a non-Chrome process, not killing it")));
59 73 }
60 74 let (program, arguments): (&str, Vec<&str>) = match platform {
61 Platform::Linux => ("kill", vec!["-KILL", &pid]),
75 Platform::Linux | Platform::Macos => ("kill", vec!["-KILL", &pid]),
62 76 Platform::Windows => ("taskkill", vec!["/PID", &pid, "/T", "/F"]),
63 77 Platform::Wsl => ("taskkill.exe", vec!["/PID", &pid, "/T", "/F"]),
64 78 };
@@ -81,6 +95,8 @@ mod tests {
81 95 fn only_chrome_images_are_killable() {
82 96 assert!(is_chrome_image("\"chrome.exe\""));
83 97 assert!(is_chrome_image("chrome\n"));
98 assert!(is_chrome_image("Google Chrome"));
99 assert!(is_chrome_image("Chromium"));
84 100 assert!(!is_chrome_image("\"wslrelay.exe\""));
85 101 assert!(!is_chrome_image(""));
86 102 }
@@ -91,4 +107,11 @@ mod tests {
91 107 assert_eq!(parse_netstat_pid(table, 9222), Some(5150));
92 108 assert_eq!(parse_netstat_pid(table, 9333), None);
93 109 }
110
111 #[test]
112 fn reads_pid_from_lsof() {
113 let table = "COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME\nGoogle\\x20Ch 4242 joe 45u IPv4 0xabc 0t0 TCP 127.0.0.1:9222 (LISTEN)\n";
114 assert_eq!(parse_lsof_pid(table), Some(4242));
115 assert_eq!(parse_lsof_pid("COMMAND PID\n"), None);
116 }
94 117 }
@@ -21,6 +21,14 @@ pub(crate) fn parse_netstat_pid(output: &str, port: u16) -> Option<u32> {
21 })
21 })
22}
22}
23
23
24/// First LISTEN row's PID column from `lsof -nP -iTCP:<port> -sTCP:LISTEN`.
25pub(crate) fn parse_lsof_pid(output: &str) -> Option<u32> {
26 output.lines().skip(1).find_map(|line| {
27 let columns: Vec<&str> = line.split_whitespace().collect();
28 columns.get(1)?.parse().ok()
29 })
30}
31
24fn run(program: &str, arguments: &[&str]) -> Result<String, BrowserError> {
32fn run(program: &str, arguments: &[&str]) -> Result<String, BrowserError> {
25 let output = Command::new(program).args(arguments).output()?;
33 let output = Command::new(program).args(arguments).output()?;
26 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
34 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
@@ -29,6 +37,9 @@ fn run(program: &str, arguments: &[&str]) -> Result<String, BrowserError> {
29fn listener_pid(platform: Platform, port: u16) -> Result<u32, BrowserError> {
37fn listener_pid(platform: Platform, port: u16) -> Result<u32, BrowserError> {
30 let pid = match platform {
38 let pid = match platform {
31 Platform::Linux => parse_ss_pid(&run("ss", &["-ltnpH", &format!("sport = :{port}")])?),
39 Platform::Linux => parse_ss_pid(&run("ss", &["-ltnpH", &format!("sport = :{port}")])?),
40 Platform::Macos => {
41 parse_lsof_pid(&run("lsof", &["-nP", &format!("-iTCP:{port}"), "-sTCP:LISTEN"])?)
42 }
32 Platform::Windows => parse_netstat_pid(&run("netstat", &["-ano", "-p", "TCP"])?, port),
43 Platform::Windows => parse_netstat_pid(&run("netstat", &["-ano", "-p", "TCP"])?, port),
33 Platform::Wsl => parse_netstat_pid(&run("netstat.exe", &["-ano", "-p", "TCP"])?, port),
44 Platform::Wsl => parse_netstat_pid(&run("netstat.exe", &["-ano", "-p", "TCP"])?, port),
34 };
45 };
@@ -38,6 +49,8 @@ fn listener_pid(platform: Platform, port: u16) -> Result<u32, BrowserError> {
38pub(crate) fn is_chrome_image(image_name: &str) -> bool {
49pub(crate) fn is_chrome_image(image_name: &str) -> bool {
39 let lowered = image_name.trim().trim_matches('"').to_ascii_lowercase();
50 let lowered = image_name.trim().trim_matches('"').to_ascii_lowercase();
40 lowered.starts_with("chrome")
51 lowered.starts_with("chrome")
52 || lowered.starts_with("google chrome")
53 || lowered.starts_with("chromium")
41}
54}
42
55
43fn process_image_name(platform: Platform, pid: &str) -> Result<String, BrowserError> {
56fn process_image_name(platform: Platform, pid: &str) -> Result<String, BrowserError> {
@@ -45,6 +58,7 @@ fn process_image_name(platform: Platform, pid: &str) -> Result<String, BrowserEr
45 let csv_arguments = ["/FI", filter.as_str(), "/FO", "CSV", "/NH"];
58 let csv_arguments = ["/FI", filter.as_str(), "/FO", "CSV", "/NH"];
46 let output = match platform {
59 let output = match platform {
47 Platform::Linux => std::fs::read_to_string(format!("/proc/{pid}/comm"))?,
60 Platform::Linux => std::fs::read_to_string(format!("/proc/{pid}/comm"))?,
61 Platform::Macos => run("ps", &["-p", pid, "-o", "comm="])?,
48 Platform::Windows => run("tasklist", &csv_arguments)?,
62 Platform::Windows => run("tasklist", &csv_arguments)?,
49 Platform::Wsl => run("tasklist.exe", &csv_arguments)?,
63 Platform::Wsl => run("tasklist.exe", &csv_arguments)?,
50 };
64 };
@@ -58,7 +72,7 @@ pub(crate) fn kill_listener(platform: Platform, port: u16) -> Result<(), Browser
58 return Err(BrowserError::Cdp(format!("port {port} is held by a non-Chrome process, not killing it")));
72 return Err(BrowserError::Cdp(format!("port {port} is held by a non-Chrome process, not killing it")));
59 }
73 }
60 let (program, arguments): (&str, Vec<&str>) = match platform {
74 let (program, arguments): (&str, Vec<&str>) = match platform {
61 Platform::Linux => ("kill", vec!["-KILL", &pid]),
75 Platform::Linux | Platform::Macos => ("kill", vec!["-KILL", &pid]),
62 Platform::Windows => ("taskkill", vec!["/PID", &pid, "/T", "/F"]),
76 Platform::Windows => ("taskkill", vec!["/PID", &pid, "/T", "/F"]),
63 Platform::Wsl => ("taskkill.exe", vec!["/PID", &pid, "/T", "/F"]),
77 Platform::Wsl => ("taskkill.exe", vec!["/PID", &pid, "/T", "/F"]),
64 };
78 };
@@ -81,6 +95,8 @@ mod tests {
81 fn only_chrome_images_are_killable() {
95 fn only_chrome_images_are_killable() {
82 assert!(is_chrome_image("\"chrome.exe\""));
96 assert!(is_chrome_image("\"chrome.exe\""));
83 assert!(is_chrome_image("chrome\n"));
97 assert!(is_chrome_image("chrome\n"));
98 assert!(is_chrome_image("Google Chrome"));
99 assert!(is_chrome_image("Chromium"));
84 assert!(!is_chrome_image("\"wslrelay.exe\""));
100 assert!(!is_chrome_image("\"wslrelay.exe\""));
85 assert!(!is_chrome_image(""));
101 assert!(!is_chrome_image(""));
86 }
102 }
@@ -91,4 +107,11 @@ mod tests {
91 assert_eq!(parse_netstat_pid(table, 9222), Some(5150));
107 assert_eq!(parse_netstat_pid(table, 9222), Some(5150));
92 assert_eq!(parse_netstat_pid(table, 9333), None);
108 assert_eq!(parse_netstat_pid(table, 9333), None);
93 }
109 }
110
111 #[test]
112 fn reads_pid_from_lsof() {
113 let table = "COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME\nGoogle\\x20Ch 4242 joe 45u IPv4 0xabc 0t0 TCP 127.0.0.1:9222 (LISTEN)\n";
114 assert_eq!(parse_lsof_pid(table), Some(4242));
115 assert_eq!(parse_lsof_pid("COMMAND PID\n"), None);
116 }
94}
117}
crates/browser/tests/common/mod.rs +1 −0
@@ -271,6 +271,7 @@ pub async fn harness() -> Harness {
271 271 let inputs = ConfigInputs {
272 272 windows_variables: Default::default(),
273 273 linux_data_dir: Some(directory.path().to_path_buf()),
274 home_dir: None,
274 275 to_local: &to_local,
275 276 };
276 277 let config = Config::resolve(Platform::Linux, mock.port, &inputs).unwrap();
@@ -271,6 +271,7 @@ pub async fn harness() -> Harness {
271 let inputs = ConfigInputs {
271 let inputs = ConfigInputs {
272 windows_variables: Default::default(),
272 windows_variables: Default::default(),
273 linux_data_dir: Some(directory.path().to_path_buf()),
273 linux_data_dir: Some(directory.path().to_path_buf()),
274 home_dir: None,
274 to_local: &to_local,
275 to_local: &to_local,
275 };
276 };
276 let config = Config::resolve(Platform::Linux, mock.port, &inputs).unwrap();
277 let config = Config::resolve(Platform::Linux, mock.port, &inputs).unwrap();
crates/calling/src/mic_processing.rs +93 −25
@@ -9,7 +9,11 @@ pub enum NoiseSuppression {
9 9 }
10 10
11 11 impl NoiseSuppression {
12 pub const ALL: [NoiseSuppression; 3] = [NoiseSuppression::Auto, NoiseSuppression::Low, NoiseSuppression::Off];
12 pub const ALL: [NoiseSuppression; 3] = [
13 NoiseSuppression::Auto,
14 NoiseSuppression::Low,
15 NoiseSuppression::Off,
16 ];
13 17
14 18 pub fn label(self) -> &'static str {
15 19 match self {
@@ -28,7 +32,9 @@ impl NoiseSuppression {
28 32 }
29 33
30 34 pub fn from_key(key: &str) -> Option<NoiseSuppression> {
31 NoiseSuppression::ALL.into_iter().find(|level| level.key() == key)
35 NoiseSuppression::ALL
36 .into_iter()
37 .find(|level| level.key() == key)
32 38 }
33 39 }
34 40
@@ -48,36 +54,55 @@ pub struct ApmConfig {
48 54
49 55 impl ApmConfig {
50 56 pub fn is_passthrough(self) -> bool {
51 self == ApmConfig { echo_canceller: false, gain_controller: false, high_pass_filter: false, noise_suppression: false }
57 self == ApmConfig {
58 echo_canceller: false,
59 gain_controller: false,
60 high_pass_filter: false,
61 noise_suppression: false,
62 }
52 63 }
53 64
54 65 pub fn front_module(self) -> Option<AudioProcessingModule> {
55 (self.echo_canceller || self.noise_suppression)
56 .then(|| AudioProcessingModule::new(self.echo_canceller, false, false, self.noise_suppression))
66 (self.echo_canceller || self.noise_suppression).then(|| {
67 AudioProcessingModule::new(self.echo_canceller, false, false, self.noise_suppression)
68 })
57 69 }
58
59 70 }
60 71
61 72 impl MicSettings {
62 73 pub fn apm_config(self) -> ApmConfig {
63 74 if self.music_mode {
64 return ApmConfig { echo_canceller: true, gain_controller: false, high_pass_filter: false, noise_suppression: false };
75 return ApmConfig {
76 echo_canceller: true,
77 gain_controller: false,
78 high_pass_filter: false,
79 noise_suppression: false,
80 };
65 81 }
66 82 let on = self.noise_suppression != NoiseSuppression::Off;
67 83 let apm_noise_suppression = self.noise_suppression == NoiseSuppression::Low;
68 ApmConfig { echo_canceller: on, gain_controller: on, high_pass_filter: on, noise_suppression: apm_noise_suppression }
84 ApmConfig {
85 echo_canceller: on,
86 gain_controller: on,
87 high_pass_filter: on,
88 noise_suppression: apm_noise_suppression,
89 }
69 90 }
70 91
71 92 pub fn uses_device_track(self) -> bool {
72 93 self.uses_device_track_on(cfg!(windows))
73 94 }
74 95
75 /// On Linux, Auto and Low keep the Pulse ADM device track (same path Web Teams uses).
76 /// Music mode and Off still run the software chain; Windows always does.
96 /// On Linux and macOS, Auto and Low keep the platform ADM device track
97 /// (Pulse / CoreAudio — same path Web Teams uses). Music mode and Off still
98 /// run the software chain; Windows always does.
77 99 pub fn uses_device_track_on(self, windows: bool) -> bool {
78 100 !windows
79 101 && !self.music_mode
80 && matches!(self.noise_suppression, NoiseSuppression::Auto | NoiseSuppression::Low)
102 && matches!(
103 self.noise_suppression,
104 NoiseSuppression::Auto | NoiseSuppression::Low
105 )
81 106 }
82 107
83 108 pub fn ml_noise_suppression(self) -> bool {
@@ -90,51 +115,86 @@ mod tests {
90 115 use super::*;
91 116
92 117 #[test]
93 fn auto_uses_the_device_track_on_linux_and_keeps_ml_for_the_windows_chain() {
118 fn auto_uses_the_device_track_on_linux_and_macos_and_keeps_ml_for_the_windows_chain() {
94 119 let settings = MicSettings::default();
120 // Non-Windows (Pulse on Linux, CoreAudio on macOS) keeps the ADM track.
95 121 assert!(settings.uses_device_track_on(false));
96 122 assert!(!settings.uses_device_track_on(true));
97 123 assert!(settings.ml_noise_suppression());
98 124 assert_eq!(
99 125 settings.apm_config(),
100 ApmConfig { echo_canceller: true, gain_controller: true, high_pass_filter: true, noise_suppression: false }
126 ApmConfig {
127 echo_canceller: true,
128 gain_controller: true,
129 high_pass_filter: true,
130 noise_suppression: false
131 }
101 132 );
102 133 }
103 134
104 135 #[test]
105 fn low_keeps_the_device_track_with_the_apm_noise_suppression() {
106 let settings = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };
136 fn low_keeps_the_coreaudio_or_pulse_device_track_with_the_apm_noise_suppression() {
137 let settings = MicSettings {
138 noise_suppression: NoiseSuppression::Low,
139 music_mode: false,
140 };
107 141 assert!(settings.uses_device_track_on(false));
108 142 assert!(!settings.ml_noise_suppression());
109 143 assert_eq!(
110 144 settings.apm_config(),
111 ApmConfig { echo_canceller: true, gain_controller: true, high_pass_filter: true, noise_suppression: true }
145 ApmConfig {
146 echo_canceller: true,
147 gain_controller: true,
148 high_pass_filter: true,
149 noise_suppression: true
150 }
112 151 );
113 152 }
114 153
115 154 #[test]
116 155 fn only_auto_outside_music_mode_runs_the_ml_stage() {
117 156 assert!(MicSettings::default().ml_noise_suppression());
118 assert!(!MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false }.ml_noise_suppression());
119 assert!(!MicSettings { noise_suppression: NoiseSuppression::Auto, music_mode: true }.ml_noise_suppression());
157 assert!(
158 !MicSettings {
159 noise_suppression: NoiseSuppression::Off,
160 music_mode: false
161 }
162 .ml_noise_suppression()
163 );
164 assert!(
165 !MicSettings {
166 noise_suppression: NoiseSuppression::Auto,
167 music_mode: true
168 }
169 .ml_noise_suppression()
170 );
120 171 }
121 172
122 173 #[test]
123 174 fn windows_never_uses_the_device_track() {
124 175 for noise_suppression in NoiseSuppression::ALL {
125 176 for music_mode in [false, true] {
126 let settings = MicSettings { noise_suppression, music_mode };
177 let settings = MicSettings {
178 noise_suppression,
179 music_mode,
180 };
127 181 assert!(!settings.uses_device_track_on(true));
128 let linux_device = !music_mode
129 && matches!(noise_suppression, NoiseSuppression::Auto | NoiseSuppression::Low);
130 assert_eq!(settings.uses_device_track_on(false), linux_device);
182 let non_windows_device = !music_mode
183 && matches!(
184 noise_suppression,
185 NoiseSuppression::Auto | NoiseSuppression::Low
186 );
187 assert_eq!(settings.uses_device_track_on(false), non_windows_device);
131 188 }
132 189 }
133 190 }
134 191
135 192 #[test]
136 193 fn off_leaves_the_device_track_and_processes_nothing() {
137 let settings = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };
194 let settings = MicSettings {
195 noise_suppression: NoiseSuppression::Off,
196 music_mode: false,
197 };
138 198 assert!(!settings.uses_device_track());
139 199 assert!(settings.apm_config().is_passthrough());
140 200 assert!(settings.apm_config().front_module().is_none());
@@ -143,11 +203,19 @@ mod tests {
143 203 #[test]
144 204 fn music_mode_keeps_only_echo_cancellation_whatever_the_noise_choice() {
145 205 for noise_suppression in NoiseSuppression::ALL {
146 let settings = MicSettings { noise_suppression, music_mode: true };
206 let settings = MicSettings {
207 noise_suppression,
208 music_mode: true,
209 };
147 210 assert!(!settings.uses_device_track());
148 211 assert_eq!(
149 212 settings.apm_config(),
150 ApmConfig { echo_canceller: true, gain_controller: false, high_pass_filter: false, noise_suppression: false }
213 ApmConfig {
214 echo_canceller: true,
215 gain_controller: false,
216 high_pass_filter: false,
217 noise_suppression: false
218 }
151 219 );
152 220 }
153 221 }
@@ -9,7 +9,11 @@ pub enum NoiseSuppression {
9}
9}
10
10
11impl NoiseSuppression {
11impl NoiseSuppression {
12 pub const ALL: [NoiseSuppression; 3] = [NoiseSuppression::Auto, NoiseSuppression::Low, NoiseSuppression::Off];
12 pub const ALL: [NoiseSuppression; 3] = [
13 NoiseSuppression::Auto,
14 NoiseSuppression::Low,
15 NoiseSuppression::Off,
16 ];
13
17
14 pub fn label(self) -> &'static str {
18 pub fn label(self) -> &'static str {
15 match self {
19 match self {
@@ -28,7 +32,9 @@ impl NoiseSuppression {
28 }
32 }
29
33
30 pub fn from_key(key: &str) -> Option<NoiseSuppression> {
34 pub fn from_key(key: &str) -> Option<NoiseSuppression> {
31 NoiseSuppression::ALL.into_iter().find(|level| level.key() == key)
35 NoiseSuppression::ALL
36 .into_iter()
37 .find(|level| level.key() == key)
32 }
38 }
33}
39}
34
40
@@ -48,36 +54,55 @@ pub struct ApmConfig {
48
54
49impl ApmConfig {
55impl ApmConfig {
50 pub fn is_passthrough(self) -> bool {
56 pub fn is_passthrough(self) -> bool {
51 self == ApmConfig { echo_canceller: false, gain_controller: false, high_pass_filter: false, noise_suppression: false }
57 self == ApmConfig {
58 echo_canceller: false,
59 gain_controller: false,
60 high_pass_filter: false,
61 noise_suppression: false,
62 }
52 }
63 }
53
64
54 pub fn front_module(self) -> Option<AudioProcessingModule> {
65 pub fn front_module(self) -> Option<AudioProcessingModule> {
55 (self.echo_canceller || self.noise_suppression)
66 (self.echo_canceller || self.noise_suppression).then(|| {
56 .then(|| AudioProcessingModule::new(self.echo_canceller, false, false, self.noise_suppression))
67 AudioProcessingModule::new(self.echo_canceller, false, false, self.noise_suppression)
68 })
57 }
69 }
58
59}
70}
60
71
61impl MicSettings {
72impl MicSettings {
62 pub fn apm_config(self) -> ApmConfig {
73 pub fn apm_config(self) -> ApmConfig {
63 if self.music_mode {
74 if self.music_mode {
64 return ApmConfig { echo_canceller: true, gain_controller: false, high_pass_filter: false, noise_suppression: false };
75 return ApmConfig {
76 echo_canceller: true,
77 gain_controller: false,
78 high_pass_filter: false,
79 noise_suppression: false,
80 };
65 }
81 }
66 let on = self.noise_suppression != NoiseSuppression::Off;
82 let on = self.noise_suppression != NoiseSuppression::Off;
67 let apm_noise_suppression = self.noise_suppression == NoiseSuppression::Low;
83 let apm_noise_suppression = self.noise_suppression == NoiseSuppression::Low;
68 ApmConfig { echo_canceller: on, gain_controller: on, high_pass_filter: on, noise_suppression: apm_noise_suppression }
84 ApmConfig {
85 echo_canceller: on,
86 gain_controller: on,
87 high_pass_filter: on,
88 noise_suppression: apm_noise_suppression,
89 }
69 }
90 }
70
91
71 pub fn uses_device_track(self) -> bool {
92 pub fn uses_device_track(self) -> bool {
72 self.uses_device_track_on(cfg!(windows))
93 self.uses_device_track_on(cfg!(windows))
73 }
94 }
74
95
75 /// On Linux, Auto and Low keep the Pulse ADM device track (same path Web Teams uses).
96 /// On Linux and macOS, Auto and Low keep the platform ADM device track
76 /// Music mode and Off still run the software chain; Windows always does.
97 /// (Pulse / CoreAudio — same path Web Teams uses). Music mode and Off still
98 /// run the software chain; Windows always does.
77 pub fn uses_device_track_on(self, windows: bool) -> bool {
99 pub fn uses_device_track_on(self, windows: bool) -> bool {
78 !windows
100 !windows
79 && !self.music_mode
101 && !self.music_mode
80 && matches!(self.noise_suppression, NoiseSuppression::Auto | NoiseSuppression::Low)
102 && matches!(
103 self.noise_suppression,
104 NoiseSuppression::Auto | NoiseSuppression::Low
105 )
81 }
106 }
82
107
83 pub fn ml_noise_suppression(self) -> bool {
108 pub fn ml_noise_suppression(self) -> bool {
@@ -90,51 +115,86 @@ mod tests {
90 use super::*;
115 use super::*;
91
116
92 #[test]
117 #[test]
93 fn auto_uses_the_device_track_on_linux_and_keeps_ml_for_the_windows_chain() {
118 fn auto_uses_the_device_track_on_linux_and_macos_and_keeps_ml_for_the_windows_chain() {
94 let settings = MicSettings::default();
119 let settings = MicSettings::default();
120 // Non-Windows (Pulse on Linux, CoreAudio on macOS) keeps the ADM track.
95 assert!(settings.uses_device_track_on(false));
121 assert!(settings.uses_device_track_on(false));
96 assert!(!settings.uses_device_track_on(true));
122 assert!(!settings.uses_device_track_on(true));
97 assert!(settings.ml_noise_suppression());
123 assert!(settings.ml_noise_suppression());
98 assert_eq!(
124 assert_eq!(
99 settings.apm_config(),
125 settings.apm_config(),
100 ApmConfig { echo_canceller: true, gain_controller: true, high_pass_filter: true, noise_suppression: false }
126 ApmConfig {
127 echo_canceller: true,
128 gain_controller: true,
129 high_pass_filter: true,
130 noise_suppression: false
131 }
101 );
132 );
102 }
133 }
103
134
104 #[test]
135 #[test]
105 fn low_keeps_the_device_track_with_the_apm_noise_suppression() {
136 fn low_keeps_the_coreaudio_or_pulse_device_track_with_the_apm_noise_suppression() {
106 let settings = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };
137 let settings = MicSettings {
138 noise_suppression: NoiseSuppression::Low,
139 music_mode: false,
140 };
107 assert!(settings.uses_device_track_on(false));
141 assert!(settings.uses_device_track_on(false));
108 assert!(!settings.ml_noise_suppression());
142 assert!(!settings.ml_noise_suppression());
109 assert_eq!(
143 assert_eq!(
110 settings.apm_config(),
144 settings.apm_config(),
111 ApmConfig { echo_canceller: true, gain_controller: true, high_pass_filter: true, noise_suppression: true }
145 ApmConfig {
146 echo_canceller: true,
147 gain_controller: true,
148 high_pass_filter: true,
149 noise_suppression: true
150 }
112 );
151 );
113 }
152 }
114
153
115 #[test]
154 #[test]
116 fn only_auto_outside_music_mode_runs_the_ml_stage() {
155 fn only_auto_outside_music_mode_runs_the_ml_stage() {
117 assert!(MicSettings::default().ml_noise_suppression());
156 assert!(MicSettings::default().ml_noise_suppression());
118 assert!(!MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false }.ml_noise_suppression());
157 assert!(
119 assert!(!MicSettings { noise_suppression: NoiseSuppression::Auto, music_mode: true }.ml_noise_suppression());
158 !MicSettings {
159 noise_suppression: NoiseSuppression::Off,
160 music_mode: false
161 }
162 .ml_noise_suppression()
163 );
164 assert!(
165 !MicSettings {
166 noise_suppression: NoiseSuppression::Auto,
167 music_mode: true
168 }
169 .ml_noise_suppression()
170 );
120 }
171 }
121
172
122 #[test]
173 #[test]
123 fn windows_never_uses_the_device_track() {
174 fn windows_never_uses_the_device_track() {
124 for noise_suppression in NoiseSuppression::ALL {
175 for noise_suppression in NoiseSuppression::ALL {
125 for music_mode in [false, true] {
176 for music_mode in [false, true] {
126 let settings = MicSettings { noise_suppression, music_mode };
177 let settings = MicSettings {
178 noise_suppression,
179 music_mode,
180 };
127 assert!(!settings.uses_device_track_on(true));
181 assert!(!settings.uses_device_track_on(true));
128 let linux_device = !music_mode
182 let non_windows_device = !music_mode
129 && matches!(noise_suppression, NoiseSuppression::Auto | NoiseSuppression::Low);
183 && matches!(
130 assert_eq!(settings.uses_device_track_on(false), linux_device);
184 noise_suppression,
185 NoiseSuppression::Auto | NoiseSuppression::Low
186 );
187 assert_eq!(settings.uses_device_track_on(false), non_windows_device);
131 }
188 }
132 }
189 }
133 }
190 }
134
191
135 #[test]
192 #[test]
136 fn off_leaves_the_device_track_and_processes_nothing() {
193 fn off_leaves_the_device_track_and_processes_nothing() {
137 let settings = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };
194 let settings = MicSettings {
195 noise_suppression: NoiseSuppression::Off,
196 music_mode: false,
197 };
138 assert!(!settings.uses_device_track());
198 assert!(!settings.uses_device_track());
139 assert!(settings.apm_config().is_passthrough());
199 assert!(settings.apm_config().is_passthrough());
140 assert!(settings.apm_config().front_module().is_none());
200 assert!(settings.apm_config().front_module().is_none());
@@ -143,11 +203,19 @@ mod tests {
143 #[test]
203 #[test]
144 fn music_mode_keeps_only_echo_cancellation_whatever_the_noise_choice() {
204 fn music_mode_keeps_only_echo_cancellation_whatever_the_noise_choice() {
145 for noise_suppression in NoiseSuppression::ALL {
205 for noise_suppression in NoiseSuppression::ALL {
146 let settings = MicSettings { noise_suppression, music_mode: true };
206 let settings = MicSettings {
207 noise_suppression,
208 music_mode: true,
209 };
147 assert!(!settings.uses_device_track());
210 assert!(!settings.uses_device_track());
148 assert_eq!(
211 assert_eq!(
149 settings.apm_config(),
212 settings.apm_config(),
150 ApmConfig { echo_canceller: true, gain_controller: false, high_pass_filter: false, noise_suppression: false }
213 ApmConfig {
214 echo_canceller: true,
215 gain_controller: false,
216 high_pass_filter: false,
217 noise_suppression: false
218 }
151 );
219 );
152 }
220 }
153 }
221 }