A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.
Rust archive-managerdesktop-appdual-paneexplorer-alternativefile-browserfile-explorerfile-managerfluent-designgpu-acceleratedgpuimacosmicaproductivityquick-lookrustrust-guitabswindowswindows-11windows-explorer
Control Centre: Bluetooth voice/music status and battery, Wi-Fi Connect automatically (issue 312)
Ruchir31756f479f3c17d
diff --git a/crates/rf-app/locales/_source.json b/crates/rf-app/locales/_source.jsonindex 8de0b403..14dc0872 100644--- a/crates/rf-app/locales/_source.json+++ b/crates/rf-app/locales/_source.json@@ -14999,5 +14999,29 @@"key": "İmleci ekranın en üstüne atıp sekmeye tıklayabilirsiniz. Kapalıyken sekmelerin üstündeki şerit pencereyi tutup çekmek için kalır.","tr": "İmleci ekranın en üstüne atıp sekmeye tıklayabilirsiniz. Kapalıyken sekmelerin üstündeki şerit pencereyi tutup çekmek için kalır.","en": "Throw the pointer to the very top of the screen and click a tab. Off, the strip above the tabs stays for grabbing the window."+ },+ {+ "id": "bd057a64",+ "key": "Bağlı · ses, müzik",+ "tr": "Bağlı · ses, müzik",+ "en": "Connected · voice, music"+ },+ {+ "id": "a9b57a82",+ "key": "Bağlı · ses",+ "tr": "Bağlı · ses",+ "en": "Connected · voice"+ },+ {+ "id": "4bfdd9d3",+ "key": "Bağlı · müzik",+ "tr": "Bağlı · müzik",+ "en": "Connected · music"+ },+ {+ "id": "9c595d54",+ "key": "Otomatik bağlan",+ "tr": "Otomatik bağlan",+ "en": "Connect automatically"}-]\ No newline at end of file+]diff --git a/crates/rf-app/src/dock/cc_model.rs b/crates/rf-app/src/dock/cc_model.rsindex 817f73af..254612b0 100644--- a/crates/rf-app/src/dock/cc_model.rs+++ b/crates/rf-app/src/dock/cc_model.rs@@ -734,6 +734,17 @@ pub fn bluetooth_tag(s: &BluetoothSnapshot) -> Option<String> {s.version.map(str::to_string)}+/// What a connected device's row says, as Windows words it: which of its sound can be used now, if that is known (a mouse has none,+/// and says only that it is connected). The key of the text (`i18n::t`).+pub fn bt_connected_key(voice: bool, music: bool) -> &'static str {+ match (voice, music) {+ (true, true) => "Bağlı · ses, müzik",+ (true, false) => "Bağlı · ses",+ (false, true) => "Bağlı · müzik",+ (false, false) => "Bağlı",+ }+}+/// "Bluetooth 5.4", or "Bluetooth".pub fn bluetooth_title(s: &BluetoothSnapshot) -> String {bluetooth_tag(s).map_or_else(|| "Bluetooth".into(), |t| format!("Bluetooth {t}"))@@ -1221,6 +1232,16 @@ mod tests {assert_eq!((Unfold::open().value(0), Unfold::open().settled(0), Unfold::open().opening()), (1.0, true, true));}+ #[test]+ fn a_connected_device_says_which_of_its_sound_can_be_used() {+ let keys = [(true, true), (true, false), (false, true), (false, false)].map(|(voice, music)| bt_connected_key(voice, music));+ assert_eq!(keys, ["Bağlı · ses, müzik", "Bağlı · ses", "Bağlı · müzik", "Bağlı"]);+ // each has its own English text+ for (key, english) in keys.iter().zip(["Connected · voice, music", "Connected · voice", "Connected · music", "Connected"]) {+ assert!(crate::i18n_en::EN.iter().any(|(tr, en)| tr == key && *en == english), "{key}");+ }+ }+#[test]fn the_height_is_the_sections_the_gaps_and_the_padding() {// nothing but the bottom rowdiff --git a/crates/rf-app/src/dock/control_centre.rs b/crates/rf-app/src/dock/control_centre.rsindex 9554a347..593407aa 100644--- a/crates/rf-app/src/dock/control_centre.rs+++ b/crates/rf-app/src/dock/control_centre.rs@@ -231,6 +231,8 @@ pub struct CcView {wifi_asking: Option<String>,wifi_input: Option<Entity<InputState>>,wifi_bad: bool,+ /// The "Connect automatically" row under the field: ticked each time a password is asked for.+ wifi_auto: bool,/// The Bluetooth device (its address) whose sound was asked to connect (`true`) or to let go, and when.bt_busy: Option<(String, bool, Instant)>,/// The slider being dragged right now.@@ -326,6 +328,7 @@ impl CcView {wifi_asking: None,wifi_input: None,wifi_bad: false,+ wifi_auto: true,bt_busy: None,drag: None,vol_drag: None,@@ -455,10 +458,11 @@ impl CcView {sound: !self.sound_sides(cx).is_empty(),brightness: if hidden("brightness", cx) { 0 } else { self.brightness.iter().filter(|b| b.available).count() },// (the mixer's rows are the programs that play now)- // (and the password's row in Wi-Fi's, while one is asked for)+ // (and the password's two rows in Wi-Fi's, while one is asked for)detail: self.detail_now().map(|d| {let mixer = if d == Detail::Mixer { cc_model::mixer_rows(self.mixer.len()) } else { 0 };- let asking = usize::from(d == Detail::Wifi && self.wifi_asking.is_some());+ // (two: the field, and "Connect automatically" under it)+ let asking = 2 * usize::from(d == Detail::Wifi && self.wifi_asking.is_some());(d, cc_model::detail_rows(d, audio.as_ref(), self.mic.as_ref(), wifi.as_ref(), bt.as_ref(), net.as_ref()) + mixer + asking)}),}@@ -766,6 +770,7 @@ impl CcView {});self.wifi_asking = Some(ssid.to_string());self.wifi_bad = false;+ self.wifi_auto = true;}self.refit(cx);} else {@@ -786,7 +791,7 @@ impl CcView {self.wifi_bad = true;return cx.notify();}- wifi::connect_with_password(&ssid, &password);+ wifi::connect_with_password(&ssid, &password, self.wifi_auto);input.update(cx, |s, cx| s.set_value("", window, cx));self.wifi_asking = None;self.joining = Some((ssid, Instant::now()));@@ -1656,6 +1661,12 @@ impl CcView {/// it is a choice (a keyboard stop, lit under the pointer); without, a line to read.#[allow(clippy::too_many_arguments)]fn detail_row(&self, id: (&'static str, usize), icon: Option<L>, text: String, note: Option<String>, mark: Option<L>, look: &Look, click: Option<RowClick>, cx: &mut Context<Self>) -> AnyElement {+ self.detail_row_body(id, icon, div().flex_1().min_w_0().truncate().child(text), note, mark, look, click, cx)+ }++ /// A [`Self::detail_row`] whose middle is `body` (it takes the room that is left).+ #[allow(clippy::too_many_arguments)]+ fn detail_row_body(&self, id: (&'static str, usize), icon: Option<L>, body: impl IntoElement, note: Option<String>, mark: Option<L>, look: &Look, click: Option<RowClick>, cx: &mut Context<Self>) -> AnyElement {let (hover, pressed) = (look.pal.hover_fill().hsla(), look.pal.pressed_fill().hsla());let secondary = look.pal.text_secondary().hsla();let ring = look.accent;@@ -1671,7 +1682,7 @@ impl CcView {.border_color(transparent_black()).text_sm().child(div().w(px(14.)).flex_shrink_0().children(icon.map(|i| Icon::new(i).size(px(14.)).text_color(look.pal.text().hsla()))))- .child(div().flex_1().min_w_0().truncate().child(text))+ .child(body).children(note.map(|n| div().flex_shrink_0().text_xs().text_color(secondary).child(n))).children(mark.map(|m| Icon::new(m).size(px(12.)).flex_shrink_0().text_color(secondary)));match click {@@ -1770,6 +1781,7 @@ impl CcView {// the network whose password is asked for: the field, right under its rowif self.wifi_asking.as_deref() == Some(n.ssid.as_str()) {rows.extend(self.wifi_password_row(look, cx));+ rows.push(self.wifi_auto_row(look, cx));}}}@@ -1778,6 +1790,22 @@ impl CcView {(self.detail_head(cc_model::wifi_title(&w), Some((RadioKind::WiFi, w.power)), look, cx), rows)}+ /// "Connect automatically", under the password's field. The field gets the keyboard back after a press: the row takes it, and+ /// Enter must still connect.+ fn wifi_auto_row(&self, look: &Look, cx: &mut Context<Self>) -> AnyElement {+ let click: RowClick = Rc::new(|this, window, cx| {+ this.wifi_auto = !this.wifi_auto;+ if let Some(input) = &this.wifi_input {+ input.update(cx, |s, cx| s.focus(window, cx));+ }+ cx.notify();+ });+ let mark = if self.wifi_auto { L::SquareCheck } else { L::Square };+ let body = div().flex_1().min_w_0().truncate().text_xs().child(t!("Otomatik bağlan"));+ // (measured on the user's screen: so the box stands under the left edge of the field above, and its text under the field's text)+ v_flex().flex_shrink_0().pl(px(20.)).child(self.detail_row_body(("cc-wifi-auto", 0), Some(mark), body, None, None, look, Some(click), cx)).into_any_element()+ }+/// The row with the field for a network's password, and the button that connects with it.fn wifi_password_row(&self, look: &Look, cx: &mut Context<Self>) -> Option<AnyElement> {let input = self.wifi_input.as_ref()?;@@ -1834,14 +1862,28 @@ impl CcView {let state = match busy {Some(true) => Some(t!("Bağlanıyor…")),Some(false) => Some(t!("Bağlantı kesiliyor…")),- None => d.connected.then_some(t!("Bağlı")),+ None => d.connected.then(|| crate::i18n::t(cc_model::bt_connected_key(d.voice, d.music))),};- let note: Vec<String> = d.battery.map(|level| (words.pct)(level)).into_iter().chain(state.map(str::to_string)).collect();+ // what it says goes under its name; the battery stands alone at the right, for a connected device only (Windows keeps+ // the last level of one that is gone, on a node that stays)+ let battery = d.battery.filter(|_| d.connected).map(|level| (words.pct)(level));let click: Option<RowClick> = d.address.clone().filter(|_| d.audio).map(|address| {let connected = d.connected;Rc::new(move |this: &mut Self, _: &mut Window, cx: &mut Context<Self>| this.choose_bt(&address, connected, cx)) as RowClick});- rows.push(self.detail_row(("cc-bt-device", i), Some(icon), d.name.clone(), (!note.is_empty()).then(|| note.join(" · ")), None, look, click, cx));+ let row = match state {+ Some(state) => {+ // (two lines in the height of one row, so that the card's height stays what `cc_model` counts)+ let body = v_flex()+ .flex_1()+ .min_w_0()+ .child(div().line_height(px(15.)).truncate().child(d.name.clone()))+ .child(div().text_size(px(11.)).line_height(px(13.)).text_color(look.pal.text_secondary().hsla()).truncate().child(state));+ self.detail_row_body(("cc-bt-device", i), Some(icon), body, battery, None, look, click, cx)+ }+ None => self.detail_row(("cc-bt-device", i), Some(icon), d.name.clone(), battery, None, look, click, cx),+ };+ rows.push(row);}}}diff --git a/crates/rf-app/src/i18n_en.rs b/crates/rf-app/src/i18n_en.rsindex d5979449..29fb9ea6 100644--- a/crates/rf-app/src/i18n_en.rs+++ b/crates/rf-app/src/i18n_en.rs@@ -2466,6 +2466,10 @@ pub const EN: &[(&str, &str)] = &[("Simgeleri kilitle", "Lock the icons"),("Dock'taki simgeler sürüklenince yer değiştirmez; yanlışlıkla bozulmaz.", "Dragging the dock's icons does not move them, so their order is not changed by accident."),("Yeni sürüm var:", "New version available:"),+ ("Bağlı · ses, müzik", "Connected · voice, music"),+ ("Bağlı · ses", "Connected · voice"),+ ("Bağlı · müzik", "Connected · music"),+ ("Otomatik bağlan", "Connect automatically"),("Simgeler büyürken ve sürüklenip bırakılınca yerine kayarken hedefini biraz geçip geri gelir, yay gibi.", "As the icons grow, and as a dragged icon slides into its place, they go a little past where they are going and spring back."),("Ctrl+1–9 ile sekmeler arasında geç", "Switch tabs with Ctrl+1–9"),("Ctrl+1–8 ilgili sekmeye geçer; Ctrl+9 son ya da 9. sekmeye geçer.", "Ctrl+1–8 jumps to that tab; Ctrl+9 jumps to the last or 9th tab."),diff --git a/crates/rf-win/src/sysstatus/bluetooth.rs b/crates/rf-win/src/sysstatus/bluetooth.rsindex 1f36e101..fac8b2e3 100644--- a/crates/rf-win/src/sysstatus/bluetooth.rs+++ b/crates/rf-win/src/sysstatus/bluetooth.rs@@ -9,7 +9,7 @@//!//! A machine without a Bluetooth radio (no adapter, or the driver is off) gives `available: false` and the tile is left out.-use std::sync::mpsc::{Sender, channel};+use std::sync::mpsc::{RecvTimeoutError, Sender, channel};use std::time::Duration;use windows::Devices::Bluetooth::{BluetoothConnectionStatus, BluetoothDevice, BluetoothLEDevice};@@ -32,20 +32,25 @@ pub struct Device {pub battery: Option<u8>,/// It has sound here (a headset, a speaker): its sound can be connected and let go (`btaudio::set_connected`).pub audio: bool,+ /// Its stereo side can be used now (what Windows calls "music"), and its microphone ("voice"): `btaudio::sound_links`.+ pub music: bool,+ pub voice: bool,}-/// The devices with what is known of each by its address: the battery it reports, whether it has sound.+/// The devices with what is known of each by its address: the battery it reports, whether it has sound, and of that sound whether+/// its music and its voice can be used (`sound`: (address, music, voice)).////// ONE ROW FOR ONE DEVICE. A phone (and many a headset) is listed twice by Windows, once as a classic device and once as a low/// energy one, with two names and the same address (seen with "Alex's iPhone", not connected, and "4", connected,/// both with the phone's battery). Two entries of one address are one device: connected if either is, under the longer of the two/// names (the short one is what the low energy side happens to call itself), where the first of them stood.-pub fn with_details(mut devices: Vec<Device>, addresses: &[(String, String)], batteries: &[(String, u8)], audio: &[String]) -> Vec<Device> {+pub fn with_details(mut devices: Vec<Device>, addresses: &[(String, String)], batteries: &[(String, u8)], audio: &[String], sound: &[(String, bool, bool)]) -> Vec<Device> {for d in &mut devices {d.address = addresses.iter().find(|(name, _)| *name == d.name).map(|(_, a)| a.clone());if let Some(a) = &d.address {d.battery = batteries.iter().find(|(b, _)| b == a).map(|(_, level)| *level);d.audio = audio.contains(a);+ (d.music, d.voice) = sound.iter().find(|(b, ..)| b == a).map_or((false, false), |&(_, music, voice)| (music, voice));}}let mut out: Vec<Device> = Vec::new();@@ -53,6 +58,9 @@ pub fn with_details(mut devices: Vec<Device>, addresses: &[(String, String)], bamatch out.iter_mut().find(|o| o.address.is_some() && o.address == d.address) {Some(first) => {first.connected |= d.connected;+ first.music |= d.music;+ first.voice |= d.voice;+ first.battery = first.battery.or(d.battery);if d.name.chars().count() > first.name.chars().count() {first.name = d.name;}@@ -105,6 +113,9 @@ enum Msg {const BURST: Duration = Duration::from_millis(200);+/// How often the list is read again while it is followed (only while the control centre is open).+const REFRESH: Duration = Duration::from_secs(3);+/// Follows Bluetooth (see the module docs): `callback` is called from the thread of its own, at once with the first reading and at/// every change after it.pub fn subscribe(callback: impl Fn(&BluetoothSnapshot) + Send + Sync + 'static) -> Subscription {@@ -116,12 +127,24 @@ pub fn subscribe(callback: impl Fn(&BluetoothSnapshot) + Send + Sync + 'static)let mut last: Option<BluetoothSnapshot> = None;let mut tell = |s: BluetoothSnapshot| {if last.as_ref() != Some(&s) {+ // (counts only: no name and no address goes into the log)+ let count = |has: fn(&Device) -> bool| s.devices.iter().filter(|d| has(d)).count();+ log::info!("bluetooth: {} connected, {} with music, {} with voice, {} with a battery", s.connected.len(), count(|d| d.music), count(|d| d.voice), count(|d| d.battery.is_some()));callback(&s);last = Some(s);}};tell(read());- while let Ok(msg) = rx.recv() {+ loop {+ let msg = match rx.recv_timeout(REFRESH) {+ Ok(msg) => msg,+ // (music or voice can come or go with no word from the connection watchers: look again; the same reading is not told)+ Err(RecvTimeoutError::Timeout) => {+ tell(read());+ continue;+ }+ Err(RecvTimeoutError::Disconnected) => break,+ };if matches!(msg, Msg::Quit) {break;}@@ -169,7 +192,9 @@ fn read() -> BluetoothSnapshot {let (connected, mut addresses) = found(selectors());let (paired, more) = found(paired_selectors());addresses.extend(more);- let devices = with_details(devices_of(paired, &connected), &addresses, &super::btaudio::battery_levels(), &super::btaudio::audio_addresses());+ // (one walk over the sound endpoints, which opens nothing on their drivers: this is read again every few seconds)+ let sounds = super::btaudio::sounds();+ let devices = with_details(devices_of(paired, &connected), &addresses, &super::btaudio::battery_levels(), &super::btaudio::audio_of(&sounds), &super::btaudio::sound_links(&sounds));// (the names the tile tells are the rows' own: a device listed twice is told once, by the name its row has)let connected = devices.iter().filter(|d| d.connected).map(|d| d.name.clone()).collect();BluetoothSnapshot { available: true, power, connected, devices, version }@@ -307,20 +332,39 @@ mod tests {let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();let list = devices_of(names(&["Kulaklık", "Fare", "Klavye"]), &names(&["Fare"]));let addresses = vec![("Fare".to_string(), "F00DCAFE0001".to_string()), ("Kulaklık".to_string(), "94DB56ABCDEF".to_string())];- let out = with_details(list, &addresses, &[("F00DCAFE0001".to_string(), 49)], &["94DB56ABCDEF".to_string()]);+ let out = with_details(list, &addresses, &[("F00DCAFE0001".to_string(), 49)], &["94DB56ABCDEF".to_string()], &[]);let shown: Vec<(&str, Option<u8>, bool, bool)> = out.iter().map(|d| (d.name.as_str(), d.battery, d.audio, d.address.is_some())).collect();assert_eq!(shown, [("Fare", Some(49), false, true), ("Klavye", None, false, false), ("Kulaklık", None, true, true)]);// a phone that Windows lists twice (classic and low energy, one address): one row, connected, under its longer namelet twice = devices_of(names(&["Alex's iPhone", "Klavye"]), &names(&["4"]));let phone = vec![("4".to_string(), "AABBCCDDEEFF".to_string()), ("Alex's iPhone".to_string(), "AABBCCDDEEFF".to_string())];- let out = with_details(twice, &phone, &[("AABBCCDDEEFF".to_string(), 49)], &[]);+ let out = with_details(twice, &phone, &[("AABBCCDDEEFF".to_string(), 49)], &[], &[]);let shown: Vec<(&str, bool, Option<u8>)> = out.iter().map(|d| (d.name.as_str(), d.connected, d.battery)).collect();assert_eq!(shown, [("Alex's iPhone", true, Some(49)), ("Klavye", false, None)]);// two devices without an address are two devices, whatever their names- let none = with_details(devices_of(names(&["a", "b"]), &[]), &[], &[], &[]);+ let none = with_details(devices_of(names(&["a", "b"]), &[]), &[], &[], &[], &[]);assert_eq!(none.len(), 2);}+ #[test]+ fn music_and_voice_go_to_the_row_of_the_address_and_survive_two_entries_becoming_one() {+ let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();+ let list = devices_of(names(&["Headset LE", "Mouse"]), &names(&["Headset"]));+ let addresses = vec![("Headset".to_string(), "A".to_string()), ("Headset LE".to_string(), "A".to_string()), ("Mouse".to_string(), "B".to_string())];+ let sound = [("A".to_string(), true, true), ("C".to_string(), true, false)];+ let out = with_details(list, &addresses, &[("A".to_string(), 40)], &["A".to_string()], &sound);+ let shown: Vec<(&str, bool, bool, Option<u8>)> = out.iter().map(|d| (d.name.as_str(), d.music, d.voice, d.battery)).collect();+ assert_eq!(shown, [("Headset LE", true, true, Some(40)), ("Mouse", false, false, None)]);+ // the flags and the battery of the second entry reach the one row, also when the first had none+ let two = vec![+ Device { name: "a".into(), connected: true, ..Default::default() },+ Device { name: "bb".into(), ..Default::default() },+ ];+ let one_address = vec![("a".to_string(), "A".to_string()), ("bb".to_string(), "A".to_string())];+ let out = with_details(two, &one_address, &[("A".to_string(), 7)], &[], &[("A".to_string(), false, true)]);+ assert_eq!((out.len(), out[0].music, out[0].voice, out[0].battery), (1, false, true, Some(7)));+ }+#[test]fn the_paired_devices_are_listed_once_with_the_connected_ones_first() {let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();diff --git a/crates/rf-win/src/sysstatus/btaudio.rs b/crates/rf-win/src/sysstatus/btaudio.rsindex 0f66d515..660a12ab 100644--- a/crates/rf-win/src/sysstatus/btaudio.rs+++ b/crates/rf-win/src/sysstatus/btaudio.rs@@ -5,7 +5,7 @@//! through two older doors, and both go by the device's ADDRESS (twelve hex digits), which is the one thing all the names share://!//! * THE BATTERY is a property of the device's node in the device tree (the same number Settings shows beside a mouse or a-//! headset), read with SetupAPI from the nodes of the Bluetooth class. Only devices that report one have it.+//! headset), read with SetupAPI from the nodes of the Bluetooth and the System classes. Only devices that report one have it.//! * CONNECT / DISCONNECT. Windows has no call that connects "a Bluetooth device"; a device is connected while one of its services//! is in use. For sound, the Bluetooth audio driver takes two requests on the audio endpoint's own filter, "reconnect" and//! "disconnect" (the kernel streaming property set `KSPROPSETID_BtAudio`): the Connect button of Windows' sound panel sends the@@ -15,15 +15,15 @@//! Everything here blocks for a moment: off the interface's thread. The two requests are the user's click and nothing else.use windows::Win32::Devices::DeviceAndDriverInstallation::{- DIGCF_PRESENT, GUID_DEVCLASS_BLUETOOTH, HDEVINFO, SP_DEVINFO_DATA, SetupDiDestroyDeviceInfoList, SetupDiEnumDeviceInfo, SetupDiGetClassDevsW, SetupDiGetDeviceInstanceIdW,- SetupDiGetDevicePropertyW,+ DIGCF_PRESENT, GUID_DEVCLASS_BLUETOOTH, GUID_DEVCLASS_SYSTEM, HDEVINFO, SP_DEVINFO_DATA, SetupDiCreateDeviceInfoList, SetupDiDestroyDeviceInfoList, SetupDiEnumDeviceInfo,+ SetupDiGetClassDevsW, SetupDiGetDeviceInstanceIdW, SetupDiGetDevicePropertyW, SetupDiOpenDeviceInfoW,};-use windows::Win32::Devices::Properties::{DEVPROP_TYPE_BYTE, DEVPROPTYPE};+use windows::Win32::Devices::Properties::{DEVPROP_TYPE_BYTE, DEVPROP_TYPE_GUID, DEVPROPTYPE};use windows::Win32::Foundation::DEVPROPKEY;-use windows::Win32::Media::Audio::{DEVICE_STATE, DEVICE_STATE_ACTIVE, DEVICE_STATE_UNPLUGGED, IDeviceTopology, IMMDeviceEnumerator, MMDeviceEnumerator, eAll};+use windows::Win32::Media::Audio::{DEVICE_STATE, DEVICE_STATE_ACTIVE, DEVICE_STATE_UNPLUGGED, IDeviceTopology, IMMDevice, IMMDeviceEnumerator, IMMEndpoint, MMDeviceEnumerator, eAll, eCapture};use windows::Win32::Media::KernelStreaming::{IKsControl, KSIDENTIFIER, KSIDENTIFIER_0, KSIDENTIFIER_0_0, KSPROPERTY_TYPE_GET};use windows::Win32::System::Com::{CLSCTX_ALL, CoCreateInstance, CoTaskMemFree};-use windows::core::{GUID, PCWSTR};+use windows::core::{GUID, Interface, PCWSTR};use super::init_mta;@@ -76,30 +76,33 @@ impl Drop for DevInfo {}/// The battery levels the Bluetooth devices that are there report: (address, percent). A device with several nodes that report-/// one is listed once.+/// one is listed once. Two classes are looked in: a headset's level can stand only on its hands-free node, which is of the+/// System class (the user's CMF Headphone Pro, 2026-11-29, issue 312).pub fn battery_levels() -> Vec<(String, u8)> {let mut out: Vec<(String, u8)> = Vec::new();- unsafe {- let Ok(set) = SetupDiGetClassDevsW(Some(&GUID_DEVCLASS_BLUETOOTH), PCWSTR::null(), None, DIGCF_PRESENT) else { return out };- let set = DevInfo(set);- for index in 0.. {- let mut dev = SP_DEVINFO_DATA { cbSize: size_of::<SP_DEVINFO_DATA>() as u32, ..Default::default() };- if SetupDiEnumDeviceInfo(set.0, index, &mut dev).is_err() {- break;- }- let (mut kind, mut level) = (DEVPROPTYPE::default(), [0u8; 1]);- if SetupDiGetDevicePropertyW(set.0, &dev, &BATTERY, &mut kind, Some(&mut level), None, 0).is_err() || kind != DEVPROP_TYPE_BYTE {- continue;- }- let mut id = [0u16; 512];- if SetupDiGetDeviceInstanceIdW(set.0, &dev, Some(&mut id), None).is_err() {- continue;- }- let id = String::from_utf16_lossy(&id[..id.iter().position(|c| *c == 0).unwrap_or(id.len())]);- if let Some(address) = address_in(&id)- && !out.iter().any(|(a, _)| *a == address)- {- out.push((address, level[0].min(100)));+ for class in [GUID_DEVCLASS_BLUETOOTH, GUID_DEVCLASS_SYSTEM] {+ unsafe {+ let Ok(set) = SetupDiGetClassDevsW(Some(&class), PCWSTR::null(), None, DIGCF_PRESENT) else { continue };+ let set = DevInfo(set);+ for index in 0.. {+ let mut dev = SP_DEVINFO_DATA { cbSize: size_of::<SP_DEVINFO_DATA>() as u32, ..Default::default() };+ if SetupDiEnumDeviceInfo(set.0, index, &mut dev).is_err() {+ break;+ }+ let (mut kind, mut level) = (DEVPROPTYPE::default(), [0u8; 1]);+ if SetupDiGetDevicePropertyW(set.0, &dev, &BATTERY, &mut kind, Some(&mut level), None, 0).is_err() || kind != DEVPROP_TYPE_BYTE {+ continue;+ }+ let mut id = [0u16; 512];+ if SetupDiGetDeviceInstanceIdW(set.0, &dev, Some(&mut id), None).is_err() {+ continue;+ }+ let id = String::from_utf16_lossy(&id[..id.iter().position(|c| *c == 0).unwrap_or(id.len())]);+ if let Some(address) = address_in(&id)+ && !out.iter().any(|(a, _)| *a == address)+ {+ out.push((address, level[0].min(100)));+ }}}}@@ -159,9 +162,79 @@ const BT_AUDIO: GUID = GUID::from_u128(0x7fa06c40_b8f6_4c7e_8556_e8c33a12e54d);const ONESHOT_RECONNECT: u32 = 0;const ONESHOT_DISCONNECT: u32 = 1;-/// The Bluetooth audio endpoints (there or unplugged): the address of the device each belongs to, and the filter that takes the-/// two requests.-fn endpoints() -> Vec<(String, IKsControl)> {+/// The advanced audio (stereo) service's number, in the id of the filter that plays music.+const A2DP: &str = "0000110b";++/// The id Windows gives all the parts of one device (`DEVPKEY_Device_ContainerId`).+const CONTAINER: DEVPROPKEY = DEVPROPKEY { fmtid: GUID::from_u128(0x8c7ed206_3f8a_4827_b3ab_ae9e1faefc6c), pid: 2 };++/// One audio endpoint of a Bluetooth device, as far as telling music and voice apart needs it.+#[derive(Clone, Debug, Default)]+pub struct Sound {+ /// The device's address, when the filter's id carries it. A hands-free filter's id can be without it+ /// (`BTHHFENUM\BTHHFPAUDIO\8&1ECA2556&0&97` on the user's PC): then only the container tells whose it is.+ pub address: Option<String>,+ /// The filter's id, in small letters.+ pub filter: String,+ /// A microphone (else something that plays).+ pub capture: bool,+ /// It can be used now: that side of the device is connected.+ pub active: bool,+ /// The container the endpoint's own node belongs to.+ pub container: Option<[u8; 16]>,+}++/// For every address among the endpoints: (address, music, voice). Music: a stereo endpoint that plays is usable. Voice: a+/// microphone of the same device is usable (Windows 11 has one output and one microphone for a headset, no matter the profile).+/// A device none of whose endpoints carries its address is not listed.+pub fn sound_links(ends: &[Sound]) -> Vec<(String, bool, bool)> {+ audio_of(ends)+ .into_iter()+ .map(|address| {+ let mine: Vec<&Sound> = ends.iter().filter(|e| e.address.as_ref() == Some(&address)).collect();+ let music = mine.iter().any(|e| !e.capture && e.active && e.filter.contains(A2DP));+ let voice = mine.iter().filter_map(|e| e.container).any(|c| ends.iter().any(|m| m.capture && m.active && m.container == Some(c)));+ (address, music, voice)+ })+ .collect()+}++/// The addresses of the devices that have sound here (a headset, a speaker): the ones [`set_connected`] can act on. Each once.+pub fn audio_of(ends: &[Sound]) -> Vec<String> {+ let mut out: Vec<String> = Vec::new();+ for address in ends.iter().filter_map(|e| e.address.as_ref()) {+ if !out.contains(address) {+ out.push(address.clone());+ }+ }+ out+}++/// Whose endpoint `end` is: the address in its own filter's id, else that of another endpoint of its container. A hands-free+/// filter's id can be without an address, and a request that missed it left the headset's microphone connected (issue 312's PC:+/// "Disconnect" took the music and left the voice).+pub fn owner<'a>(end: &'a Sound, ends: &'a [Sound]) -> Option<&'a str> {+ end.address.as_deref().or_else(|| {+ let container = end.container?;+ ends.iter().filter(|o| o.container == Some(container)).find_map(|o| o.address.as_deref())+ })+}++/// The container of an audio endpoint, read from the endpoint's own device node (`SWD\MMDEVAPI\<endpoint id>`).+unsafe fn container_of(endpoint_id: &str) -> Option<[u8; 16]> {+ unsafe {+ let set = DevInfo(SetupDiCreateDeviceInfoList(None, None).ok()?);+ let node = crate::wide::wide(&format!(r"SWD\MMDEVAPI\{endpoint_id}"));+ let mut dev = SP_DEVINFO_DATA { cbSize: size_of::<SP_DEVINFO_DATA>() as u32, ..Default::default() };+ SetupDiOpenDeviceInfoW(set.0, PCWSTR(node.as_ptr()), None, 0, Some(&mut dev)).ok()?;+ let (mut kind, mut id) = (DEVPROPTYPE::default(), [0u8; 16]);+ SetupDiGetDevicePropertyW(set.0, &dev, &CONTAINER, &mut kind, Some(&mut id), None, 0).ok()?;+ (kind == DEVPROP_TYPE_GUID).then_some(id)+ }+}++/// The Bluetooth audio endpoints (there or unplugged), each with the filter it hangs on. Opens nothing on the filter.+fn walk() -> Vec<(Sound, windows::core::Result<IMMDevice>)> {let mut out = Vec::new();init_mta();unsafe {@@ -172,44 +245,72 @@ fn endpoints() -> Vec<(String, IKsControl)> {let Ok(topology) = endpoint.Activate::<IDeviceTopology>(CLSCTX_ALL, None) else { continue };let Ok(connector) = topology.GetConnector(0) else { continue };let Ok(raw) = connector.GetDeviceIdConnectedTo() else { continue };- let id = raw.to_string().unwrap_or_default();+ let id = raw.to_string().unwrap_or_default().to_ascii_lowercase();let filter = en.GetDevice(PCWSTR(raw.0));CoTaskMemFree(Some(raw.0 as *const _));- // (only a filter of the Bluetooth audio drivers: its id names the Bluetooth enumerator and carries the address)- if !id.to_ascii_lowercase().contains("bth") {+ // (only a filter of the Bluetooth audio drivers: its id names the Bluetooth enumerator)+ if !id.contains("bth") {continue;}- let Some(address) = address_in(&id) else { continue };- let Ok(control) = filter.and_then(|f| f.Activate::<IKsControl>(CLSCTX_ALL, None)) else { continue };- out.push((address, control));+ let container = endpoint.GetId().ok().and_then(|own| {+ let text = own.to_string().ok();+ CoTaskMemFree(Some(own.0 as *const _));+ container_of(&text?)+ });+ let sound = Sound {+ address: address_in(&id),+ capture: endpoint.cast::<IMMEndpoint>().and_then(|e| e.GetDataFlow()).is_ok_and(|flow| flow == eCapture),+ active: endpoint.GetState().is_ok_and(|state| state == DEVICE_STATE_ACTIVE),+ filter: id,+ container,+ };+ out.push((sound, filter));}}out}-/// The addresses of the devices that have sound here (a headset, a speaker): the ones [`set_connected`] can act on. Each once.-pub fn audio_addresses() -> Vec<String> {- let mut out: Vec<String> = Vec::new();- for (address, _) in endpoints() {- if !out.contains(&address) {- out.push(address);- }- }- out+/// What the Bluetooth audio endpoints are now.+pub fn sounds() -> Vec<Sound> {+ walk().into_iter().map(|(sound, _)| sound).collect()+}++/// The endpoints that take the two requests: the address of the device each belongs to, and the filter's control.+fn endpoints() -> Vec<(String, IKsControl)> {+ let (sounds, filters): (Vec<Sound>, Vec<_>) = walk().into_iter().unzip();+ // (a speaker and a microphone can hang on one filter: it is asked once)+ let mut asked: Vec<&str> = Vec::new();+ filters+ .into_iter()+ .enumerate()+ .filter_map(|(i, filter)| {+ let address = owner(&sounds[i], &sounds)?.to_string();+ if asked.contains(&sounds[i].filter.as_str()) {+ return None;+ }+ asked.push(&sounds[i].filter);+ let control = filter.and_then(|f| unsafe { f.Activate::<IKsControl>(CLSCTX_ALL, None) }).ok()?;+ Some((address, control))+ })+ .collect()}/// The user clicked a headset or a speaker in the list: asks the Bluetooth audio driver to connect its sound, or to let it go. How/// many of the device's endpoints took the request (a headset has two: music, and calls); an error when none did.pub fn set_connected(address: &str, connect: bool) -> Result<usize, String> {let request = KSIDENTIFIER { Anonymous: KSIDENTIFIER_0 { Anonymous: KSIDENTIFIER_0_0 { Set: BT_AUDIO, Id: if connect { ONESHOT_RECONNECT } else { ONESHOT_DISCONNECT }, Flags: KSPROPERTY_TYPE_GET } } };- let (mut taken, mut refused) = (0usize, None);+ let (mut taken, mut failed, mut refused) = (0usize, 0usize, None);for (_, control) in endpoints().into_iter().filter(|(a, _)| a.eq_ignore_ascii_case(address)) {let mut returned = 0u32;match unsafe { control.KsProperty(&request, size_of::<KSIDENTIFIER>() as u32, std::ptr::null_mut(), 0, &mut returned) } {Ok(()) => taken += 1,- Err(e) => refused = Some(e.to_string()),+ Err(e) => {+ failed += 1;+ refused = Some(e.to_string());+ }}}+ log::info!("bluetooth: asked to {} the sound: {taken} took it, {failed} refused ({})", if connect { "connect" } else { "let go of" }, refused.as_deref().unwrap_or("no error"));if taken > 0 { Ok(taken) } else { Err(refused.unwrap_or_else(|| "the device has no sound endpoint here".to_string())) }}@@ -217,6 +318,53 @@ pub fn set_connected(address: &str, connect: bool) -> Result<usize, String> {mod tests {use super::*;+ fn end(address: Option<&str>, filter: &str, capture: bool, active: bool, container: Option<u8>) -> Sound {+ Sound { address: address.map(str::to_string), filter: filter.to_string(), capture, active, container: container.map(|c| [c; 16]) }+ }++ /// A headset as on issue 312's PC: the stereo filter has the address, the hands-free ones have none.+ fn headset(address: &str, container: u8, music: bool, voice: bool) -> Vec<Sound> {+ vec![+ end(Some(address), "bthenum#{0000110b-0000}", false, music, Some(container)),+ end(None, "bthhfenum#bthhfpaudio", false, voice, Some(container)),+ end(None, "bthhfenum#bthhfpaudio", true, voice, Some(container)),+ ]+ }++ #[test]+ fn music_is_the_stereo_side_and_voice_the_microphone_of_the_same_container() {+ let link = |m, v| vec![("A".to_string(), m, v)];+ assert_eq!(sound_links(&headset("A", 1, true, true)), link(true, true));+ assert_eq!(sound_links(&headset("A", 1, true, false)), link(true, false));+ assert_eq!(sound_links(&headset("A", 1, false, true)), link(false, true));+ assert_eq!(sound_links(&headset("A", 1, false, false)), link(false, false));+ }++ #[test]+ fn a_hands_free_end_without_an_address_belongs_to_the_headset_of_its_container() {+ let mut ends = headset("A", 1, true, true);+ ends.extend(headset("B", 2, true, true));+ let owners: Vec<Option<&str>> = ends.iter().map(|e| owner(e, &ends)).collect();+ assert_eq!(owners, [Some("A"), Some("A"), Some("A"), Some("B"), Some("B"), Some("B")]);+ // no container read, or none shared with an address: nobody's, so that no other device is ever asked+ let lone = [end(Some("A"), "bthenum#{0000110b}", false, true, Some(1)), end(None, "bthhfenum", true, true, None), end(None, "bthhfenum", true, true, Some(9))];+ assert_eq!(lone.iter().map(|e| owner(e, &lone)).collect::<Vec<_>>(), [Some("A"), None, None]);+ }++ #[test]+ fn two_headsets_do_not_take_each_others_microphone() {+ let mut ends = headset("A", 1, true, false);+ ends.extend(headset("B", 2, true, true));+ assert_eq!(sound_links(&ends), [("A".to_string(), true, false), ("B".to_string(), true, true)]);+ assert_eq!(audio_of(&ends), ["A", "B"]);+ }++ #[test]+ fn a_container_that_was_not_read_matches_nothing() {+ let ends = [end(Some("A"), "bthenum#{0000110b}", false, true, None), end(None, "bthhfenum", true, true, None)];+ assert_eq!(sound_links(&ends), [("A".to_string(), true, false)]);+ }+/// The core specification's table of LMP versions (the control centre's Bluetooth title, 2026-11-26).#[test]fn an_lmp_version_names_its_bluetooth_version() {@@ -247,6 +395,10 @@ mod tests {for none in [r"BTH\MS_BTHLE\7&1EBF1D05&0&4", r"SWD\MMDEVAPI\{0.0.0.00000000}.{6994ad04-93ef-11d0-a3cc-00a0c9223196}", r"USB\VID_046D&PID_C52B\5&1234", "", "DEV_12345"] {assert_eq!(address_in(none), None, "{none}");}+ // a headset's hands-free service, the node of the System class that carries its battery (issue 312's PC, address changed)+ assert_eq!(address_in(r"BTHENUM\{0000111E-0000-1000-8000-00805F9B34FB}_VID&000102B0_PID&0000\7&A2CD643&0&AABBCCDDEEFF_C00000000").as_deref(), Some("AABBCCDDEEFF"));+ // the hands-free audio filter's own id carries no address+ assert_eq!(address_in(r"BTHHFENUM\BTHHFPAUDIO\8&1ECA2556&0&97"), None);// thirteen digits are not twelveassert_eq!(address_in(r"X\DEV_F00DCAFE00012\1"), None);}@@ -256,6 +408,7 @@ mod tests {#[ignore = "reads the Bluetooth devices of the PC it runs on; run by hand"]fn what_this_pcs_devices_say() {let batteries = battery_levels();- println!("with a battery level: {} (the levels: {:?}); with sound: {}", batteries.len(), batteries.iter().map(|(_, l)| *l).collect::<Vec<_>>(), audio_addresses().len());+ let links = sound_links(&sounds());+ println!("with a battery level: {} (the levels: {:?}); with sound: {} (music, voice: {:?})", batteries.len(), batteries.iter().map(|(_, l)| *l).collect::<Vec<_>>(), links.len(), links.iter().map(|(_, m, v)| (*m, *v)).collect::<Vec<_>>());}}diff --git a/crates/rf-win/src/sysstatus/wifi.rs b/crates/rf-win/src/sysstatus/wifi.rsindex b86ff49b..4c05c3fd 100644--- a/crates/rf-win/src/sysstatus/wifi.rs+++ b/crates/rf-win/src/sysstatus/wifi.rs@@ -540,7 +540,7 @@ fn xml_text(s: &str) -> String {/// The profile Windows keeps for a home network: its name, how it lets a device in, the password. As Windows' own flyout writes/// it for a network the user ticked "connect automatically" on. `None` for a kind of network this does not connect.-pub fn profile_xml(ssid: &str, auth: Auth, password: &str) -> Option<String> {+pub fn profile_xml(ssid: &str, auth: Auth, password: &str, auto: bool) -> Option<String> {let authentication = match auth {Auth::Wpa2 => "WPA2PSK",Auth::Wpa3 => "WPA3SAE",@@ -548,9 +548,10 @@ pub fn profile_xml(ssid: &str, auth: Auth, password: &str) -> Option<String> {};let hex: String = ssid.bytes().map(|b| format!("{b:02X}")).collect();let (name, key) = (xml_text(ssid), xml_text(password));+ let mode = if auto { "auto" } else { "manual" };Some(format!("<?xml version=\"1.0\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>{name}</name><SSIDConfig><SSID><hex>{hex}</hex><name>{name}</name></SSID></SSIDConfig>\-<connectionType>ESS</connectionType><connectionMode>auto</connectionMode><MSM><security><authEncryption><authentication>{authentication}</authentication><encryption>AES</encryption>\+<connectionType>ESS</connectionType><connectionMode>{mode}</connectionMode><MSM><security><authEncryption><authentication>{authentication}</authentication><encryption>AES</encryption>\<useOneX>false</useOneX></authEncryption><sharedKey><keyType>passPhrase</keyType><protected>false</protected><keyMaterial>{key}</keyMaterial></sharedKey></security></MSM></WLANProfile>"))}@@ -558,12 +559,12 @@ pub fn profile_xml(ssid: &str, auth: Auth, password: &str) -> Option<String> {/// How long Windows is given to connect with a typed password before its profile is taken away again.const JOIN_WAIT: Duration = Duration::from_secs(15);-fn connect_with_password_blocking(ssid: &str, password: &str) -> Result<(), String> {+fn connect_with_password_blocking(ssid: &str, password: &str, auto: bool) -> Result<(), String> {let wlan = Wlan::open().ok_or("the Wi-Fi service did not answer")?;let guid = wlan.interface().ok_or("no Wi-Fi interface")?;let list = merged(wlan.networks(&guid).map_err(|c| format!("no list of networks ({c})"))?);let network = list.iter().find(|n| n.ssid == ssid).ok_or("the network is not in range any more")?;- let xml = profile_xml(ssid, network.auth, password).ok_or("this kind of network is not connected from here")?;+ let xml = profile_xml(ssid, network.auth, password, auto).ok_or("this kind of network is not connected from here")?;let (xml_w, name_w) = (crate::wide::wide(&xml), crate::wide::wide(ssid));let set = |flags: u32| {let mut reason = 0u32;@@ -606,10 +607,10 @@ fn connect_with_password_blocking(ssid: &str, password: &str) -> Result<(), Stri}/// The user typed a network's password in the panel: see the module docs. Returns at once; the list that follows tells whether it-/// is connected.-pub fn connect_with_password(ssid: &str, password: &str) {+/// is connected. `auto`: Windows connects to the network by itself from now on (else only when asked, here or in Windows).+pub fn connect_with_password(ssid: &str, password: &str, auto: bool) {let (ssid, password) = (ssid.to_string(), password.to_string());- on_a_thread("connect with a password", move || connect_with_password_blocking(&ssid, &password));+ on_a_thread("connect with a password", move || connect_with_password_blocking(&ssid, &password, auto));}fn on_a_thread(what: &'static str, work: impl FnOnce() -> Result<(), String> + Send + 'static) {@@ -664,17 +665,19 @@ mod tests {#[test]fn a_home_networks_profile_is_written_as_windows_writes_one() {- let xml = profile_xml("Ev Ağı", Auth::Wpa2, "gizli-şifre-1").unwrap();+ let xml = profile_xml("Ev Ağı", Auth::Wpa2, "gizli-şifre-1", true).unwrap();+ let by_hand = profile_xml("Ev Ağı", Auth::Wpa2, "gizli-şifre-1", false).unwrap();+ assert_eq!(by_hand, xml.replace("<connectionMode>auto</connectionMode>", "<connectionMode>manual</connectionMode>"));assert!(xml.starts_with("<?xml version=\"1.0\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\">"));assert!(xml.contains("<name>Ev Ağı</name><SSIDConfig><SSID><hex>45762041C49FC4B1</hex><name>Ev Ağı</name></SSID></SSIDConfig>"), "{xml}");assert!(xml.contains("<connectionType>ESS</connectionType><connectionMode>auto</connectionMode>"));assert!(xml.contains("<authentication>WPA2PSK</authentication><encryption>AES</encryption><useOneX>false</useOneX>"));assert!(xml.contains("<keyType>passPhrase</keyType><protected>false</protected><keyMaterial>gizli-şifre-1</keyMaterial>"));assert!(xml.ends_with("</WLANProfile>") && !xml.contains('\n'));- assert!(profile_xml("Ev", Auth::Wpa3, "12345678").unwrap().contains("<authentication>WPA3SAE</authentication>"));- assert_eq!(profile_xml("İş", Auth::Other, "12345678"), None);+ assert!(profile_xml("Ev", Auth::Wpa3, "12345678", true).unwrap().contains("<authentication>WPA3SAE</authentication>"));+ assert_eq!(profile_xml("İş", Auth::Other, "12345678", true), None);// what XML reads as its own is written as text- let odd = profile_xml("A&B <ev>", Auth::Wpa2, "p<a>&\"s's").unwrap();+ let odd = profile_xml("A&B <ev>", Auth::Wpa2, "p<a>&\"s's", true).unwrap();assert!(odd.contains("<name>A&B <ev></name>") && odd.contains("<keyMaterial>p<a>&"s's</keyMaterial>"), "{odd}");assert!(odd.contains("<hex>41264220 3C65763E".replace(' ', "").as_str()));// a password of a home network is 8 to 63 characters