crabcamera 0.9.2

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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! Configuration management for CrabCamera
//!
//! Provides configuration loading, saving, and management for camera settings,
//! quality thresholds, storage preferences, and other runtime options.

use crate::constants::{
    DEFAULT_BLUR_THRESHOLD, DEFAULT_DATE_FORMAT, DEFAULT_EXPOSURE_THRESHOLD,
    DEFAULT_FOCUS_STACK_STEPS, DEFAULT_FPS, DEFAULT_HDR_BRACKETS, DEFAULT_IMAGE_FORMAT,
    DEFAULT_JPEG_QUALITY, DEFAULT_MAX_RETRY_ATTEMPTS, DEFAULT_OUTPUT_DIRECTORY,
    DEFAULT_OVERALL_THRESHOLD, DEFAULT_RECONNECT_ATTEMPTS, DEFAULT_RECONNECT_DELAY_MS,
    DEFAULT_RESOLUTION_HEIGHT, DEFAULT_RESOLUTION_WIDTH, DEFAULT_RETRY_DELAY_MS,
};
use crate::errors::CameraError;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};

/// Root configuration structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrabCameraConfig {
    /// Camera hardware preferences and defaults.
    pub camera: CameraConfig,
    /// Image quality analysis thresholds.
    pub quality: QualityConfig,
    /// File storage paths and naming conventions.
    pub storage: StorageConfig,
    /// Experimental and advanced features.
    pub advanced: AdvancedConfig,
}

/// Camera-specific configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CameraConfig {
    /// Default camera resolution [width, height]
    pub default_resolution: [u32; 2],
    /// Default frames per second
    pub default_fps: u32,
    /// Auto-reconnect on device disconnect
    pub auto_reconnect: bool,
    /// Reconnect retry attempts
    pub reconnect_attempts: u32,
    /// Reconnect delay in milliseconds
    pub reconnect_delay_ms: u64,
}

/// Quality validation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityConfig {
    /// Enable automatic quality-based retry
    pub auto_retry_enabled: bool,
    /// Maximum retry attempts for quality capture
    pub max_retry_attempts: u32,
    /// Minimum acceptable blur threshold (0.0-1.0)
    pub min_blur_threshold: f32,
    /// Minimum acceptable exposure score (0.0-1.0)
    pub min_exposure_score: f32,
    /// Minimum overall quality score (0.0-1.0)
    pub min_overall_score: f32,
    /// Retry delay between attempts in milliseconds
    pub retry_delay_ms: u64,
}

/// Storage and file management configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageConfig {
    /// Default output directory for captures
    pub output_directory: String,
    /// Auto-organize files by date
    pub auto_organize_by_date: bool,
    /// Date format for organization (e.g., "YYYY-MM-DD")
    pub date_format: String,
    /// Default image format (jpeg, png, bmp)
    pub default_format: String,
    /// JPEG quality (0-100)
    pub jpeg_quality: u8,
    /// Auto-delete low quality captures
    pub auto_delete_low_quality: bool,
}

/// Advanced features configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdvancedConfig {
    /// Enable focus stacking
    pub focus_stacking_enabled: bool,
    /// Number of focus steps for stacking
    pub focus_stack_steps: u32,
    /// Enable HDR capture
    pub hdr_enabled: bool,
    /// Number of exposure brackets for HDR
    pub hdr_brackets: u32,
}

impl Default for CrabCameraConfig {
    fn default() -> Self {
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        // f32→u32: DEFAULT_FPS is a known positive constant (30.0)
        let default_fps_val = DEFAULT_FPS as u32;
        Self {
            camera: CameraConfig {
                default_resolution: [DEFAULT_RESOLUTION_WIDTH, DEFAULT_RESOLUTION_HEIGHT],
                default_fps: default_fps_val,
                auto_reconnect: true,
                reconnect_attempts: DEFAULT_RECONNECT_ATTEMPTS,
                reconnect_delay_ms: DEFAULT_RECONNECT_DELAY_MS,
            },
            quality: QualityConfig {
                auto_retry_enabled: true,
                max_retry_attempts: DEFAULT_MAX_RETRY_ATTEMPTS,
                min_blur_threshold: DEFAULT_BLUR_THRESHOLD,
                min_exposure_score: DEFAULT_EXPOSURE_THRESHOLD,
                min_overall_score: DEFAULT_OVERALL_THRESHOLD,
                retry_delay_ms: DEFAULT_RETRY_DELAY_MS,
            },
            storage: StorageConfig {
                output_directory: DEFAULT_OUTPUT_DIRECTORY.to_string(),
                auto_organize_by_date: true,
                date_format: DEFAULT_DATE_FORMAT.to_string(),
                default_format: DEFAULT_IMAGE_FORMAT.to_string(),
                jpeg_quality: DEFAULT_JPEG_QUALITY,
                auto_delete_low_quality: false,
            },
            advanced: AdvancedConfig {
                focus_stacking_enabled: false,
                focus_stack_steps: DEFAULT_FOCUS_STACK_STEPS,
                hdr_enabled: false,
                hdr_brackets: DEFAULT_HDR_BRACKETS,
            },
        }
    }
}

impl CrabCameraConfig {
    /// Load configuration from TOML file
    ///
    /// # Errors
    /// Returns a [`CameraError::InitializationError`] if the config file
    /// cannot be read or if its contents cannot be parsed as TOML.
    pub fn load_from_file<P: AsRef<Path>>(path: P) -> Result<Self, CameraError> {
        let path = path.as_ref();

        if !path.exists() {
            log::info!(
                "Config file not found at {}, using defaults",
                path.display()
            );
            return Ok(Self::default());
        }

        let contents = fs::read_to_string(path).map_err(|e| {
            CameraError::InitializationError(format!("Failed to read config file: {e}"))
        })?;

        let config: CrabCameraConfig = toml::from_str(&contents).map_err(|e| {
            CameraError::InitializationError(format!("Failed to parse config file: {e}"))
        })?;

        log::info!("Loaded configuration from {}", path.display());
        Ok(config)
    }

    /// Save configuration to TOML file
    ///
    /// # Errors
    /// Returns a [`CameraError::InitializationError`] if the parent directory
    /// cannot be created, if the config cannot be serialized to TOML, or if the
    /// file cannot be written.
    pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<(), CameraError> {
        let path = path.as_ref();

        // Create parent directories if needed
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).map_err(|e| {
                CameraError::InitializationError(format!("Failed to create config directory: {e}"))
            })?;
        }

        let toml_string = toml::to_string_pretty(self).map_err(|e| {
            CameraError::InitializationError(format!("Failed to serialize config: {e}"))
        })?;

        fs::write(path, toml_string).map_err(|e| {
            CameraError::InitializationError(format!("Failed to write config file: {e}"))
        })?;

        log::info!("Saved configuration to {}", path.display());
        Ok(())
    }

    /// Get default config file path
    pub fn default_path() -> PathBuf {
        PathBuf::from("crabcamera.toml")
    }

    /// Load from default location or create with defaults
    pub fn load_or_default() -> Self {
        Self::load_from_file(Self::default_path()).unwrap_or_else(|e| {
            log::warn!("Failed to load config, using defaults: {e}");
            Self::default()
        })
    }

    /// Validate configuration values
    ///
    /// # Errors
    /// Returns an `Err` describing the first invalid value if any resolution,
    /// FPS, quality threshold, JPEG quality, focus-stack step count, or HDR
    /// bracket count is out of its allowed range.
    pub fn validate(&self) -> Result<(), String> {
        // Validate camera config
        if self.camera.default_resolution[0] == 0 || self.camera.default_resolution[1] == 0 {
            return Err("Invalid default resolution".to_string());
        }
        if self.camera.default_fps == 0 || self.camera.default_fps > 240 {
            return Err("Invalid default FPS (must be 1-240)".to_string());
        }

        // Validate quality config
        if !(0.0..=1.0).contains(&self.quality.min_blur_threshold) {
            return Err("Blur threshold must be between 0.0 and 1.0".to_string());
        }
        if !(0.0..=1.0).contains(&self.quality.min_exposure_score) {
            return Err("Exposure score must be between 0.0 and 1.0".to_string());
        }
        if !(0.0..=1.0).contains(&self.quality.min_overall_score) {
            return Err("Overall score must be between 0.0 and 1.0".to_string());
        }

        // Validate storage config
        if self.storage.jpeg_quality == 0 || self.storage.jpeg_quality > 100 {
            return Err("JPEG quality must be between 1 and 100".to_string());
        }

        // Validate advanced config
        if self.advanced.focus_stack_steps == 0 || self.advanced.focus_stack_steps > 100 {
            return Err("Focus stack steps must be between 1 and 100".to_string());
        }
        if self.advanced.hdr_brackets == 0 || self.advanced.hdr_brackets > 10 {
            return Err("HDR brackets must be between 1 and 10".to_string());
        }

        Ok(())
    }
}

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

    #[test]
    fn test_default_config() {
        let config = CrabCameraConfig::default();
        assert_eq!(config.camera.default_resolution, [1920, 1080]);
        assert_eq!(config.camera.default_fps, 30);
        assert!(config.quality.auto_retry_enabled);
    }

    #[test]
    fn test_config_validation() {
        let config = CrabCameraConfig::default();
        assert!(config.validate().is_ok());

        let mut bad_config = config.clone();
        bad_config.camera.default_resolution = [0, 0];
        assert!(bad_config.validate().is_err());

        let mut bad_quality = CrabCameraConfig::default();
        bad_quality.quality.min_blur_threshold = 1.5;
        assert!(bad_quality.validate().is_err());
    }

    #[test]
    fn test_config_save_and_load() {
        let temp_dir = std::env::temp_dir();
        let config_path = temp_dir.join("test_crabcamera.toml");

        // Clean up any existing test file
        let _ = fs::remove_file(&config_path);

        let config = CrabCameraConfig::default();
        assert!(config.save_to_file(&config_path).is_ok());

        let loaded = CrabCameraConfig::load_from_file(&config_path).expect("load saved config");
        assert_eq!(loaded.camera.default_fps, config.camera.default_fps);
        assert_eq!(
            loaded.quality.max_retry_attempts,
            config.quality.max_retry_attempts
        );

        // Clean up
        let _ = fs::remove_file(&config_path);
    }

    #[test]
    fn test_config_toml_format() {
        let config = CrabCameraConfig::default();
        let toml_string = toml::to_string_pretty(&config).expect("serialize config to TOML");

        // Verify TOML contains expected sections
        assert!(toml_string.contains("[camera]"));
        assert!(toml_string.contains("[quality]"));
        assert!(toml_string.contains("[storage]"));
        assert!(toml_string.contains("[advanced]"));
        assert!(toml_string.contains("default_resolution"));
        assert!(toml_string.contains("auto_retry_enabled"));
    }

    #[test]
    fn test_load_nonexistent_file() {
        let result = CrabCameraConfig::load_from_file("nonexistent_file.toml");
        assert!(result.is_ok()); // Should return default
        assert_eq!(result.expect("load default config").camera.default_fps, 30);
    }

    #[test]
    fn test_validate_all_remaining_error_branches() {
        let mut cfg = CrabCameraConfig::default();

        cfg.camera.default_fps = 0;
        assert_eq!(
            cfg.validate().expect_err("fps=0 should fail"),
            "Invalid default FPS (must be 1-240)"
        );

        cfg = CrabCameraConfig::default();
        cfg.camera.default_fps = 241;
        assert_eq!(
            cfg.validate().expect_err("fps>240 should fail"),
            "Invalid default FPS (must be 1-240)"
        );

        cfg = CrabCameraConfig::default();
        cfg.quality.min_exposure_score = 1.2;
        assert_eq!(
            cfg.validate().expect_err("exposure>1 should fail"),
            "Exposure score must be between 0.0 and 1.0"
        );

        cfg = CrabCameraConfig::default();
        cfg.quality.min_overall_score = -0.1;
        assert_eq!(
            cfg.validate().expect_err("overall<0 should fail"),
            "Overall score must be between 0.0 and 1.0"
        );

        cfg = CrabCameraConfig::default();
        cfg.storage.jpeg_quality = 0;
        assert_eq!(
            cfg.validate().expect_err("jpeg quality 0 should fail"),
            "JPEG quality must be between 1 and 100"
        );

        cfg = CrabCameraConfig::default();
        cfg.storage.jpeg_quality = 101;
        assert_eq!(
            cfg.validate().expect_err("jpeg quality >100 should fail"),
            "JPEG quality must be between 1 and 100"
        );

        cfg = CrabCameraConfig::default();
        cfg.advanced.focus_stack_steps = 0;
        assert_eq!(
            cfg.validate().expect_err("focus stack 0 should fail"),
            "Focus stack steps must be between 1 and 100"
        );

        cfg = CrabCameraConfig::default();
        cfg.advanced.focus_stack_steps = 101;
        assert_eq!(
            cfg.validate().expect_err("focus stack >100 should fail"),
            "Focus stack steps must be between 1 and 100"
        );

        cfg = CrabCameraConfig::default();
        cfg.advanced.hdr_brackets = 0;
        assert_eq!(
            cfg.validate().expect_err("hdr 0 should fail"),
            "HDR brackets must be between 1 and 10"
        );

        cfg = CrabCameraConfig::default();
        cfg.advanced.hdr_brackets = 11;
        assert_eq!(
            cfg.validate().expect_err("hdr >10 should fail"),
            "HDR brackets must be between 1 and 10"
        );
    }

    #[test]
    fn test_default_path_and_load_or_default() {
        assert_eq!(
            CrabCameraConfig::default_path(),
            PathBuf::from("crabcamera.toml")
        );

        // Ensure missing default file path still returns a usable default.
        let loaded = CrabCameraConfig::load_or_default();
        assert_eq!(
            loaded.camera.default_fps,
            CrabCameraConfig::default().camera.default_fps
        );
    }

    #[test]
    fn test_load_from_file_parse_error() {
        let temp_dir = std::env::temp_dir();
        let bad_path = temp_dir.join("test_crabcamera_invalid.toml");

        let _ = fs::remove_file(&bad_path);
        fs::write(&bad_path, "this-is-not-valid-toml = = =").expect("write invalid toml");

        let result = CrabCameraConfig::load_from_file(&bad_path);
        assert!(result.is_err());
        let msg = result.expect_err("invalid toml should error").to_string();
        assert!(msg.contains("Failed to parse config file"));

        let _ = fs::remove_file(&bad_path);
    }

    #[test]
    fn test_save_to_file_create_parent_directory() {
        let base = std::env::temp_dir().join("crabcamera_config_nested_test");
        let nested = base.join("deep").join("crabcamera.toml");
        let _ = fs::remove_dir_all(&base);

        let cfg = CrabCameraConfig::default();
        cfg.save_to_file(&nested)
            .expect("save should create parent dirs");
        assert!(nested.exists());

        let loaded = CrabCameraConfig::load_from_file(&nested).expect("load saved config");
        assert_eq!(loaded.storage.default_format, cfg.storage.default_format);

        let _ = fs::remove_dir_all(&base);
    }
}