dx-driven 0.1.0

Professional AI-assisted development orchestrator with binary-first architecture
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
//! # Camera Integration
//!
//! Camera capture and control for photo/video.
//!
//! ## Usage
//!
//! ```rust,ignore
//! use driven::integrations::camera::{CameraClient, CameraConfig};
//!
//! let config = CameraConfig::from_file("~/.dx/config/camera.sr")?;
//! let client = CameraClient::new(&config)?;
//!
//! // Capture a photo
//! let photo = client.capture_photo().await?;
//!
//! // List available cameras
//! let cameras = client.list_cameras().await?;
//! ```

use crate::error::{DrivenError, Result};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Camera configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CameraConfig {
    /// Whether camera integration is enabled
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Default camera device
    pub default_device: Option<String>,
    /// Output directory
    #[serde(default = "default_output_dir")]
    pub output_dir: PathBuf,
    /// Default photo quality (1-100)
    #[serde(default = "default_quality")]
    pub photo_quality: u8,
    /// Default video resolution
    #[serde(default = "default_resolution")]
    pub video_resolution: String,
    /// Default video FPS
    #[serde(default = "default_fps")]
    pub video_fps: u32,
}

fn default_true() -> bool {
    true
}

fn default_output_dir() -> PathBuf {
    dirs::picture_dir().unwrap_or_else(|| PathBuf::from("."))
}

fn default_quality() -> u8 {
    85
}

fn default_resolution() -> String {
    "1920x1080".to_string()
}

fn default_fps() -> u32 {
    30
}

impl Default for CameraConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            default_device: None,
            output_dir: default_output_dir(),
            photo_quality: default_quality(),
            video_resolution: default_resolution(),
            video_fps: default_fps(),
        }
    }
}

impl CameraConfig {
    /// Load from .sr config file
    pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self> {
        let content = std::fs::read_to_string(path.as_ref())
            .map_err(|e| DrivenError::Io(e))?;
        Self::parse_sr(&content)
    }

    fn parse_sr(_content: &str) -> Result<Self> {
        Ok(Self::default())
    }
}

/// Camera device
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CameraDevice {
    /// Device ID
    pub id: String,
    /// Device name
    pub name: String,
    /// Is default device
    pub is_default: bool,
    /// Supported resolutions
    pub resolutions: Vec<String>,
    /// Device type
    pub device_type: CameraType,
}

/// Camera type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CameraType {
    /// Built-in webcam
    Builtin,
    /// USB camera
    Usb,
    /// Virtual camera
    Virtual,
    /// Network camera
    Network,
    /// Unknown
    Unknown,
}

/// Captured photo
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapturedPhoto {
    /// File path
    pub path: PathBuf,
    /// Width
    pub width: u32,
    /// Height
    pub height: u32,
    /// File size in bytes
    pub size: u64,
    /// MIME type
    pub mime_type: String,
    /// Timestamp
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

/// Video recording
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoRecording {
    /// File path
    pub path: PathBuf,
    /// Duration in seconds
    pub duration: f64,
    /// Width
    pub width: u32,
    /// Height
    pub height: u32,
    /// FPS
    pub fps: u32,
    /// File size in bytes
    pub size: u64,
    /// MIME type
    pub mime_type: String,
    /// Timestamp
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

/// Recording state
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecordingState {
    Idle,
    Recording,
    Paused,
    Processing,
}

/// Camera client
pub struct CameraClient {
    config: CameraConfig,
    recording_state: RecordingState,
    current_recording: Option<PathBuf>,
}

impl CameraClient {
    /// Create a new camera client
    pub fn new(config: &CameraConfig) -> Result<Self> {
        // Ensure output directory exists
        std::fs::create_dir_all(&config.output_dir)
            .map_err(|e| DrivenError::Io(e))?;

        Ok(Self {
            config: config.clone(),
            recording_state: RecordingState::Idle,
            current_recording: None,
        })
    }

    /// Check if camera is available
    pub fn is_available(&self) -> bool {
        self.config.enabled
    }

    /// List available cameras
    pub async fn list_cameras(&self) -> Result<Vec<CameraDevice>> {
        #[cfg(target_os = "macos")]
        {
            self.list_cameras_macos().await
        }

        #[cfg(target_os = "windows")]
        {
            self.list_cameras_windows().await
        }

        #[cfg(target_os = "linux")]
        {
            self.list_cameras_linux().await
        }

        #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
        {
            Ok(Vec::new())
        }
    }

    #[cfg(target_os = "macos")]
    async fn list_cameras_macos(&self) -> Result<Vec<CameraDevice>> {
        use tokio::process::Command;

        // Use system_profiler to list cameras
        let output = Command::new("system_profiler")
            .args(["SPCameraDataType", "-json"])
            .output()
            .await
            .map_err(|e| DrivenError::Process(e.to_string()))?;

        if !output.status.success() {
            return Ok(Vec::new());
        }

        let json: serde_json::Value = serde_json::from_slice(&output.stdout)
            .map_err(|e| DrivenError::Parse(e.to_string()))?;

        let mut cameras = Vec::new();

        if let Some(camera_data) = json["SPCameraDataType"].as_array() {
            for (idx, cam) in camera_data.iter().enumerate() {
                cameras.push(CameraDevice {
                    id: format!("camera_{}", idx),
                    name: cam["_name"].as_str().unwrap_or("Unknown").to_string(),
                    is_default: idx == 0,
                    resolutions: vec!["1920x1080".to_string(), "1280x720".to_string()],
                    device_type: CameraType::Builtin,
                });
            }
        }

        Ok(cameras)
    }

    #[cfg(target_os = "windows")]
    async fn list_cameras_windows(&self) -> Result<Vec<CameraDevice>> {
        // Use PowerShell to list video devices
        use tokio::process::Command;

        let script = r#"
            Get-CimInstance Win32_PnPEntity | 
            Where-Object { $_.PNPClass -eq 'Camera' -or $_.PNPClass -eq 'Image' } |
            Select-Object Name, DeviceID |
            ConvertTo-Json
        "#;

        let output = Command::new("powershell")
            .args(["-Command", script])
            .output()
            .await
            .map_err(|e| DrivenError::Process(e.to_string()))?;

        if !output.status.success() {
            return Ok(Vec::new());
        }

        let json_str = String::from_utf8_lossy(&output.stdout);
        let devices: Vec<serde_json::Value> = serde_json::from_str(&json_str)
            .unwrap_or_else(|_| Vec::new());

        let cameras = devices
            .into_iter()
            .enumerate()
            .map(|(idx, d)| CameraDevice {
                id: d["DeviceID"].as_str().unwrap_or_default().to_string(),
                name: d["Name"].as_str().unwrap_or("Unknown").to_string(),
                is_default: idx == 0,
                resolutions: vec!["1920x1080".to_string(), "1280x720".to_string()],
                device_type: CameraType::Usb,
            })
            .collect();

        Ok(cameras)
    }

    #[cfg(target_os = "linux")]
    async fn list_cameras_linux(&self) -> Result<Vec<CameraDevice>> {
        use tokio::process::Command;

        // List video devices
        let output = Command::new("v4l2-ctl")
            .args(["--list-devices"])
            .output()
            .await;

        if let Ok(output) = output {
            if output.status.success() {
                let stdout = String::from_utf8_lossy(&output.stdout);
                let mut cameras = Vec::new();
                let mut current_name = String::new();

                for line in stdout.lines() {
                    if !line.starts_with('\t') && !line.is_empty() {
                        current_name = line.trim_end_matches(':').to_string();
                    } else if line.contains("/dev/video") {
                        let device = line.trim();
                        cameras.push(CameraDevice {
                            id: device.to_string(),
                            name: current_name.clone(),
                            is_default: cameras.is_empty(),
                            resolutions: vec!["1920x1080".to_string(), "1280x720".to_string()],
                            device_type: CameraType::Usb,
                        });
                    }
                }

                return Ok(cameras);
            }
        }

        Ok(Vec::new())
    }

    /// Capture a photo
    pub async fn capture_photo(&self) -> Result<CapturedPhoto> {
        let filename = format!(
            "photo_{}.jpg",
            chrono::Utc::now().format("%Y%m%d_%H%M%S")
        );
        let path = self.config.output_dir.join(&filename);

        #[cfg(target_os = "macos")]
        {
            self.capture_photo_macos(&path).await
        }

        #[cfg(target_os = "windows")]
        {
            self.capture_photo_windows(&path).await
        }

        #[cfg(target_os = "linux")]
        {
            self.capture_photo_linux(&path).await
        }

        #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
        {
            Err(DrivenError::Unsupported("Camera not supported on this platform".into()))
        }
    }

    #[cfg(target_os = "macos")]
    async fn capture_photo_macos(&self, path: &std::path::Path) -> Result<CapturedPhoto> {
        use tokio::process::Command;

        // Use imagesnap on macOS (needs to be installed: brew install imagesnap)
        let mut cmd = Command::new("imagesnap");
        cmd.arg("-q");
        cmd.arg(path);

        if let Some(ref device) = self.config.default_device {
            cmd.arg("-d").arg(device);
        }

        let status = cmd
            .status()
            .await
            .map_err(|e| DrivenError::Process(format!("Failed to capture photo: {}", e)))?;

        if !status.success() {
            return Err(DrivenError::Process("Photo capture failed".into()));
        }

        let metadata = tokio::fs::metadata(path)
            .await
            .map_err(|e| DrivenError::Io(e))?;

        Ok(CapturedPhoto {
            path: path.to_path_buf(),
            width: 1920, // Would need image library to get actual dimensions
            height: 1080,
            size: metadata.len(),
            mime_type: "image/jpeg".to_string(),
            timestamp: chrono::Utc::now(),
        })
    }

    #[cfg(target_os = "windows")]
    async fn capture_photo_windows(&self, path: &std::path::Path) -> Result<CapturedPhoto> {
        use tokio::process::Command;

        // Use ffmpeg on Windows
        let status = Command::new("ffmpeg")
            .args([
                "-f", "dshow",
                "-i", "video=0",
                "-frames:v", "1",
                "-y",
                path.to_str().unwrap(),
            ])
            .status()
            .await
            .map_err(|e| DrivenError::Process(format!("Failed to capture photo: {}", e)))?;

        if !status.success() {
            return Err(DrivenError::Process("Photo capture failed".into()));
        }

        let metadata = tokio::fs::metadata(path)
            .await
            .map_err(|e| DrivenError::Io(e))?;

        Ok(CapturedPhoto {
            path: path.to_path_buf(),
            width: 1920,
            height: 1080,
            size: metadata.len(),
            mime_type: "image/jpeg".to_string(),
            timestamp: chrono::Utc::now(),
        })
    }

    #[cfg(target_os = "linux")]
    async fn capture_photo_linux(&self, path: &std::path::Path) -> Result<CapturedPhoto> {
        use tokio::process::Command;

        let device = self.config.default_device.clone()
            .unwrap_or_else(|| "/dev/video0".to_string());

        // Use fswebcam or ffmpeg on Linux
        let status = Command::new("fswebcam")
            .args([
                "-d", &device,
                "-r", "1920x1080",
                "--jpeg", &self.config.photo_quality.to_string(),
                "--no-banner",
                path.to_str().unwrap(),
            ])
            .status()
            .await
            .map_err(|e| DrivenError::Process(format!("Failed to capture photo: {}", e)))?;

        if !status.success() {
            return Err(DrivenError::Process("Photo capture failed".into()));
        }

        let metadata = tokio::fs::metadata(path)
            .await
            .map_err(|e| DrivenError::Io(e))?;

        Ok(CapturedPhoto {
            path: path.to_path_buf(),
            width: 1920,
            height: 1080,
            size: metadata.len(),
            mime_type: "image/jpeg".to_string(),
            timestamp: chrono::Utc::now(),
        })
    }

    /// Start video recording
    pub async fn start_recording(&mut self) -> Result<PathBuf> {
        if self.recording_state == RecordingState::Recording {
            return Err(DrivenError::Conflict("Already recording".into()));
        }

        let filename = format!(
            "video_{}.mp4",
            chrono::Utc::now().format("%Y%m%d_%H%M%S")
        );
        let path = self.config.output_dir.join(&filename);

        self.recording_state = RecordingState::Recording;
        self.current_recording = Some(path.clone());

        // Note: Actual recording would need to spawn a background process
        // This is a simplified implementation
        
        Ok(path)
    }

    /// Stop video recording
    pub async fn stop_recording(&mut self) -> Result<Option<VideoRecording>> {
        if self.recording_state != RecordingState::Recording {
            return Ok(None);
        }

        self.recording_state = RecordingState::Processing;

        let path = self.current_recording.take();
        self.recording_state = RecordingState::Idle;

        if let Some(p) = path {
            if p.exists() {
                let metadata = tokio::fs::metadata(&p)
                    .await
                    .map_err(|e| DrivenError::Io(e))?;

                return Ok(Some(VideoRecording {
                    path: p,
                    duration: 0.0, // Would need ffprobe to get actual duration
                    width: 1920,
                    height: 1080,
                    fps: self.config.video_fps,
                    size: metadata.len(),
                    mime_type: "video/mp4".to_string(),
                    timestamp: chrono::Utc::now(),
                }));
            }
        }

        Ok(None)
    }

    /// Get recording state
    pub fn recording_state(&self) -> RecordingState {
        self.recording_state
    }
}

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

    #[test]
    fn test_default_config() {
        let config = CameraConfig::default();
        assert!(config.enabled);
        assert_eq!(config.photo_quality, 85);
        assert_eq!(config.video_fps, 30);
    }
}