crabcamera 0.8.3

Advanced cross-platform camera integration for Tauri applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! Device monitoring and hot-plug detection
//!
//! Provides cross-platform device monitoring to detect camera connect/disconnect events
//! and enable automatic reconnection.

use crate::errors::CameraError;
use crate::types::{CameraDeviceInfo, Platform};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{mpsc, RwLock};

/// Device event types
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeviceEvent {
    Connected(String),    // Device ID
    Disconnected(String), // Device ID
    Modified(String),     // Device ID (settings changed)
}

/// Device monitor for detecting camera changes
pub struct DeviceMonitor {
    platform: Platform,
    active_devices: Arc<RwLock<HashMap<String, CameraDeviceInfo>>>,
    event_sender: mpsc::UnboundedSender<DeviceEvent>,
    event_receiver: Arc<RwLock<mpsc::UnboundedReceiver<DeviceEvent>>>,
    is_monitoring: Arc<RwLock<bool>>,
}

impl DeviceMonitor {
    /// Create a new device monitor
    pub fn new() -> Self {
        let (tx, rx) = mpsc::unbounded_channel();

        Self {
            platform: Platform::current(),
            active_devices: Arc::new(RwLock::new(HashMap::new())),
            event_sender: tx,
            event_receiver: Arc::new(RwLock::new(rx)),
            is_monitoring: Arc::new(RwLock::new(false)),
        }
    }

    /// Start monitoring for device changes
    pub async fn start_monitoring(&self) -> Result<(), CameraError> {
        let mut is_monitoring = self.is_monitoring.write().await;
        if *is_monitoring {
            return Ok(());
        }

        log::info!(
            "Starting device monitoring for platform: {:?}",
            self.platform
        );

        match self.platform {
            Platform::Windows => self.start_windows_monitoring().await?,
            Platform::MacOS => self.start_macos_monitoring().await?,
            Platform::Linux => self.start_linux_monitoring().await?,
            Platform::Unknown => {
                log::warn!("Device monitoring not supported on unknown platform");
                return Err(CameraError::InitializationError(
                    "Device monitoring not supported on this platform".to_string(),
                ));
            }
        }

        *is_monitoring = true;
        Ok(())
    }

    /// Stop monitoring for device changes
    pub async fn stop_monitoring(&self) -> Result<(), CameraError> {
        let mut is_monitoring = self.is_monitoring.write().await;
        if !*is_monitoring {
            return Ok(());
        }

        log::info!("Stopping device monitoring");
        *is_monitoring = false;
        Ok(())
    }

    /// Get next device event (non-blocking)
    pub async fn poll_event(&self) -> Option<DeviceEvent> {
        let mut rx = self.event_receiver.write().await;
        rx.try_recv().ok()
    }

    /// Wait for next device event (blocking)
    pub async fn wait_for_event(&self) -> Option<DeviceEvent> {
        let mut rx = self.event_receiver.write().await;
        rx.recv().await
    }

    /// Get list of currently active devices
    pub async fn get_active_devices(&self) -> Vec<CameraDeviceInfo> {
        let devices = self.active_devices.read().await;
        devices.values().cloned().collect()
    }

    /// Update active device list
    async fn update_active_devices(&self, new_devices: Vec<CameraDeviceInfo>) {
        let mut active = self.active_devices.write().await;
        let old_ids: Vec<String> = active.keys().cloned().collect();
        let new_ids: Vec<String> = new_devices.iter().map(|d| d.id.clone()).collect();

        // Detect disconnections
        for old_id in &old_ids {
            if !new_ids.contains(old_id) {
                log::info!("Device disconnected: {}", old_id);
                let _ = self
                    .event_sender
                    .send(DeviceEvent::Disconnected(old_id.clone()));
            }
        }

        // Detect connections
        for device in new_devices {
            if !old_ids.contains(&device.id) {
                log::info!("Device connected: {}", device.id);
                let _ = self
                    .event_sender
                    .send(DeviceEvent::Connected(device.id.clone()));
            }
            active.insert(device.id.clone(), device);
        }

        // Remove disconnected devices
        active.retain(|id, _| new_ids.contains(id));
    }

    /// Windows-specific device monitoring
    #[cfg(target_os = "windows")]
    async fn start_windows_monitoring(&self) -> Result<(), CameraError> {
        use std::time::Duration;

        log::info!("Starting Windows device monitoring via polling");

        // Initial device scan
        let initial_devices = self.scan_devices_sync()?;
        self.update_active_devices(initial_devices).await;

        // Spawn polling task
        let active_devices = self.active_devices.clone();
        let event_sender = self.event_sender.clone();
        let is_monitoring = self.is_monitoring.clone();

        tokio::spawn(async move {
            while *is_monitoring.read().await {
                tokio::time::sleep(Duration::from_secs(2)).await;

                if let Ok(devices) = DeviceMonitor::scan_devices_windows() {
                    let mut active = active_devices.write().await;
                    let old_ids: Vec<String> = active.keys().cloned().collect();
                    let new_ids: Vec<String> = devices.iter().map(|d| d.id.clone()).collect();

                    // Check for changes
                    for old_id in &old_ids {
                        if !new_ids.contains(old_id) {
                            log::info!("Device disconnected: {}", old_id);
                            let _ = event_sender.send(DeviceEvent::Disconnected(old_id.clone()));
                        }
                    }

                    for device in devices {
                        if !old_ids.contains(&device.id) {
                            log::info!("Device connected: {}", device.id);
                            let _ = event_sender.send(DeviceEvent::Connected(device.id.clone()));
                        }
                        active.insert(device.id.clone(), device);
                    }

                    active.retain(|id, _| new_ids.contains(id));
                }
            }
        });

        Ok(())
    }

    #[cfg(not(target_os = "windows"))]
    async fn start_windows_monitoring(&self) -> Result<(), CameraError> {
        Err(CameraError::InitializationError(
            "Not on Windows".to_string(),
        ))
    }

    /// macOS-specific device monitoring
    #[cfg(target_os = "macos")]
    async fn start_macos_monitoring(&self) -> Result<(), CameraError> {
        use std::time::Duration;

        log::info!("Starting macOS device monitoring via polling");

        // Initial device scan
        let initial_devices = self.scan_devices_sync()?;
        self.update_active_devices(initial_devices).await;

        // Spawn polling task
        let active_devices = self.active_devices.clone();
        let event_sender = self.event_sender.clone();
        let is_monitoring = self.is_monitoring.clone();

        tokio::spawn(async move {
            while *is_monitoring.read().await {
                tokio::time::sleep(Duration::from_secs(2)).await;

                if let Ok(devices) = DeviceMonitor::scan_devices_macos() {
                    let mut active = active_devices.write().await;
                    let old_ids: Vec<String> = active.keys().cloned().collect();
                    let new_ids: Vec<String> = devices.iter().map(|d| d.id.clone()).collect();

                    for old_id in &old_ids {
                        if !new_ids.contains(old_id) {
                            log::info!("Device disconnected: {}", old_id);
                            let _ = event_sender.send(DeviceEvent::Disconnected(old_id.clone()));
                        }
                    }

                    for device in devices {
                        if !old_ids.contains(&device.id) {
                            log::info!("Device connected: {}", device.id);
                            let _ = event_sender.send(DeviceEvent::Connected(device.id.clone()));
                        }
                        active.insert(device.id.clone(), device);
                    }

                    active.retain(|id, _| new_ids.contains(id));
                }
            }
        });

        Ok(())
    }

    #[cfg(not(target_os = "macos"))]
    async fn start_macos_monitoring(&self) -> Result<(), CameraError> {
        Err(CameraError::InitializationError("Not on macOS".to_string()))
    }

    /// Linux-specific device monitoring
    #[cfg(target_os = "linux")]
    async fn start_linux_monitoring(&self) -> Result<(), CameraError> {
        use std::time::Duration;

        log::info!("Starting Linux device monitoring via polling");

        // Initial device scan
        let initial_devices = self.scan_devices_sync()?;
        self.update_active_devices(initial_devices).await;

        // Spawn polling task
        let active_devices = self.active_devices.clone();
        let event_sender = self.event_sender.clone();
        let is_monitoring = self.is_monitoring.clone();

        tokio::spawn(async move {
            while *is_monitoring.read().await {
                tokio::time::sleep(Duration::from_secs(2)).await;

                if let Ok(devices) = DeviceMonitor::scan_devices_linux() {
                    let mut active = active_devices.write().await;
                    let old_ids: Vec<String> = active.keys().cloned().collect();
                    let new_ids: Vec<String> = devices.iter().map(|d| d.id.clone()).collect();

                    for old_id in &old_ids {
                        if !new_ids.contains(old_id) {
                            log::info!("Device disconnected: {}", old_id);
                            let _ = event_sender.send(DeviceEvent::Disconnected(old_id.clone()));
                        }
                    }

                    for device in devices {
                        if !old_ids.contains(&device.id) {
                            log::info!("Device connected: {}", device.id);
                            let _ = event_sender.send(DeviceEvent::Connected(device.id.clone()));
                        }
                        active.insert(device.id.clone(), device);
                    }

                    active.retain(|id, _| new_ids.contains(id));
                }
            }
        });

        Ok(())
    }

    #[cfg(not(target_os = "linux"))]
    async fn start_linux_monitoring(&self) -> Result<(), CameraError> {
        Err(CameraError::InitializationError("Not on Linux".to_string()))
    }

    /// Synchronous device scan helper
    fn scan_devices_sync(&self) -> Result<Vec<CameraDeviceInfo>, CameraError> {
        match self.platform {
            Platform::Windows => Self::scan_devices_windows(),
            Platform::MacOS => Self::scan_devices_macos(),
            Platform::Linux => Self::scan_devices_linux(),
            Platform::Unknown => Ok(Vec::new()),
        }
    }

    /// Scan Windows devices
    #[cfg(target_os = "windows")]
    fn scan_devices_windows() -> Result<Vec<CameraDeviceInfo>, CameraError> {
        use nokhwa::query;

        let cameras = query(nokhwa::utils::ApiBackend::Auto).map_err(|e| {
            CameraError::InitializationError(format!("Failed to query cameras: {}", e))
        })?;

        Ok(cameras
            .into_iter()
            .map(|info| {
                CameraDeviceInfo::new(
                    format!("{}", info.index().as_index().unwrap_or(0)),
                    info.human_name().to_string(),
                )
            })
            .collect())
    }

    #[cfg(not(target_os = "windows"))]
    fn scan_devices_windows() -> Result<Vec<CameraDeviceInfo>, CameraError> {
        Ok(Vec::new())
    }

    /// Scan macOS devices
    #[cfg(target_os = "macos")]
    fn scan_devices_macos() -> Result<Vec<CameraDeviceInfo>, CameraError> {
        use nokhwa::query;

        let cameras = query(nokhwa::utils::ApiBackend::Auto).map_err(|e| {
            CameraError::InitializationError(format!("Failed to query cameras: {}", e))
        })?;

        Ok(cameras
            .into_iter()
            .map(|info| {
                CameraDeviceInfo::new(
                    format!("{}", info.index().as_index().unwrap_or(0)),
                    info.human_name().to_string(),
                )
            })
            .collect())
    }

    #[cfg(not(target_os = "macos"))]
    fn scan_devices_macos() -> Result<Vec<CameraDeviceInfo>, CameraError> {
        Ok(Vec::new())
    }

    /// Scan Linux devices
    #[cfg(target_os = "linux")]
    fn scan_devices_linux() -> Result<Vec<CameraDeviceInfo>, CameraError> {
        use nokhwa::query;

        let cameras = query(nokhwa::utils::ApiBackend::Auto).map_err(|e| {
            CameraError::InitializationError(format!("Failed to query cameras: {}", e))
        })?;

        Ok(cameras
            .into_iter()
            .map(|info| {
                CameraDeviceInfo::new(
                    format!("{}", info.index().as_index().unwrap_or(0)),
                    info.human_name().to_string(),
                )
            })
            .collect())
    }

    #[cfg(not(target_os = "linux"))]
    fn scan_devices_linux() -> Result<Vec<CameraDeviceInfo>, CameraError> {
        Ok(Vec::new())
    }
}

impl Default for DeviceMonitor {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_device_monitor_creation() {
        let monitor = DeviceMonitor::new();
        assert!(!*monitor.is_monitoring.read().await);
    }

    #[tokio::test]
    async fn test_start_stop_monitoring() {
        let monitor = DeviceMonitor::new();

        // Start monitoring
        let result = monitor.start_monitoring().await;
        // May fail on CI without cameras, but should not panic
        let _ = result;

        // Stop monitoring
        let stop_result = monitor.stop_monitoring().await;
        assert!(stop_result.is_ok());
    }

    #[test]
    fn test_device_event_types() {
        let event1 = DeviceEvent::Connected("test".to_string());
        let event2 = DeviceEvent::Disconnected("test".to_string());
        let event3 = DeviceEvent::Modified("test".to_string());

        assert_ne!(event1, event2);
        assert_ne!(event2, event3);
    }
}