| 1 | use std::time::Duration; |
| 2 | |
| 3 | use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel}; |
| 4 | use tokio::time::Instant; |
| 5 | |
| 6 | pub const DEVICE_CHANGE_QUIET: Duration = Duration::from_millis(500); |
| 7 | |
| 8 | #[derive(Debug, Default)] |
| 9 | pub struct Debounce { |
| 10 | deadline: Option<Instant>, |
| 11 | } |
| 12 | |
| 13 | impl Debounce { |
| 14 | pub fn signal(&mut self, now: Instant) { |
| 15 | self.deadline = Some(now + DEVICE_CHANGE_QUIET); |
| 16 | } |
| 17 | |
| 18 | pub fn deadline(&self) -> Option<Instant> { |
| 19 | self.deadline |
| 20 | } |
| 21 | |
| 22 | pub fn take_due(&mut self, now: Instant) -> bool { |
| 23 | let due = self.deadline.is_some_and(|deadline| now >= deadline); |
| 24 | if due { |
| 25 | self.deadline = None; |
| 26 | } |
| 27 | due |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | pub struct DeviceWatcher { |
| 32 | #[cfg(windows)] |
| 33 | _stop: std::sync::mpsc::Sender<()>, |
| 34 | } |
| 35 | |
| 36 | pub fn watch() -> (DeviceWatcher, UnboundedReceiver<()>) { |
| 37 | let (sender, receiver) = unbounded_channel(); |
| 38 | (platform::start(sender), receiver) |
| 39 | } |
| 40 | |
| 41 | #[cfg(windows)] |
| 42 | mod platform { |
| 43 | use tokio::sync::mpsc::UnboundedSender; |
| 44 | use windows::Win32::Foundation::PROPERTYKEY; |
| 45 | use windows::Win32::Media::Audio::{ |
| 46 | DEVICE_STATE, EDataFlow, ERole, IMMDeviceEnumerator, IMMNotificationClient, |
| 47 | IMMNotificationClient_Impl, MMDeviceEnumerator, eCommunications, |
| 48 | }; |
| 49 | use windows::Win32::System::Com::{ |
| 50 | CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize, |
| 51 | }; |
| 52 | use windows::core::PCWSTR; |
| 53 | use windows_core::implement; |
| 54 | |
| 55 | use super::DeviceWatcher; |
| 56 | |
| 57 | #[implement(IMMNotificationClient)] |
| 58 | struct Client { |
| 59 | sender: UnboundedSender<()>, |
| 60 | } |
| 61 | |
| 62 | impl IMMNotificationClient_Impl for Client_Impl { |
| 63 | fn OnDeviceStateChanged( |
| 64 | &self, |
| 65 | _device_id: &PCWSTR, |
| 66 | _state: DEVICE_STATE, |
| 67 | ) -> windows::core::Result<()> { |
| 68 | let _ = self.sender.send(()); |
| 69 | Ok(()) |
| 70 | } |
| 71 | |
| 72 | fn OnDeviceAdded(&self, _device_id: &PCWSTR) -> windows::core::Result<()> { |
| 73 | let _ = self.sender.send(()); |
| 74 | Ok(()) |
| 75 | } |
| 76 | |
| 77 | fn OnDeviceRemoved(&self, _device_id: &PCWSTR) -> windows::core::Result<()> { |
| 78 | let _ = self.sender.send(()); |
| 79 | Ok(()) |
| 80 | } |
| 81 | |
| 82 | fn OnDefaultDeviceChanged( |
| 83 | &self, |
| 84 | _flow: EDataFlow, |
| 85 | role: ERole, |
| 86 | _device_id: &PCWSTR, |
| 87 | ) -> windows::core::Result<()> { |
| 88 | if role == eCommunications { |
| 89 | let _ = self.sender.send(()); |
| 90 | } |
| 91 | Ok(()) |
| 92 | } |
| 93 | |
| 94 | fn OnPropertyValueChanged( |
| 95 | &self, |
| 96 | _device_id: &PCWSTR, |
| 97 | _key: &PROPERTYKEY, |
| 98 | ) -> windows::core::Result<()> { |
| 99 | Ok(()) |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | pub fn start(sender: UnboundedSender<()>) -> DeviceWatcher { |
| 104 | let (stop, stopped) = std::sync::mpsc::channel::<()>(); |
| 105 | std::thread::spawn(move || unsafe { |
| 106 | let initialized = CoInitializeEx(None, COINIT_MULTITHREADED).is_ok(); |
| 107 | if let Ok(enumerator) = |
| 108 | CoCreateInstance::<_, IMMDeviceEnumerator>(&MMDeviceEnumerator, None, CLSCTX_ALL) |
| 109 | { |
| 110 | let client: IMMNotificationClient = Client { sender }.into(); |
| 111 | if enumerator |
| 112 | .RegisterEndpointNotificationCallback(&client) |
| 113 | .is_ok() |
| 114 | { |
| 115 | let _ = stopped.recv(); |
| 116 | let _ = enumerator.UnregisterEndpointNotificationCallback(&client); |
| 117 | } |
| 118 | } |
| 119 | if initialized { |
| 120 | CoUninitialize(); |
| 121 | } |
| 122 | }); |
| 123 | DeviceWatcher { _stop: stop } |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | #[cfg(not(windows))] |
| 128 | mod platform { |
| 129 | use tokio::sync::mpsc::UnboundedSender; |
| 130 | |
| 131 | use super::DeviceWatcher; |
| 132 | |
| 133 | pub fn start(_sender: UnboundedSender<()>) -> DeviceWatcher { |
| 134 | DeviceWatcher {} |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | #[cfg(test)] |
| 139 | mod tests { |
| 140 | use super::*; |
| 141 | |
| 142 | #[test] |
| 143 | fn a_burst_of_events_fires_once_after_the_quiet_period() { |
| 144 | let start = Instant::now(); |
| 145 | let mut debounce = Debounce::default(); |
| 146 | assert!(!debounce.take_due(start)); |
| 147 | debounce.signal(start); |
| 148 | debounce.signal(start + Duration::from_millis(300)); |
| 149 | assert!(!debounce.take_due(start + Duration::from_millis(600))); |
| 150 | assert!(debounce.take_due(start + Duration::from_millis(800))); |
| 151 | assert!(!debounce.take_due(start + Duration::from_millis(900))); |
| 152 | assert_eq!(debounce.deadline(), None); |
| 153 | } |
| 154 | } |