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
//! Module for interaction through command line interface
//! purpose: reads from the flags and does a series of tests to assure that the data passed to the algorithm are usefull and existant

use super::error::config_error::*;
use super::hough_transform::circle::{CircleLimits, CircleOutputFormat};
use std::string::ToString;
use std::{ffi, fs, io, path, process, str};
use structopt::{clap, StructOpt};

/// The set-up of the program
#[derive(Debug, StructOpt)]
#[structopt(name = "hougse", about, author, rename_all = "kebab-case")]
pub struct Config {
    //{{{
    /// Image file to be searched
    #[structopt(name = "INPUT", short = "i", long = "input", parse(from_os_str))]
    pub image_path: Option<path::PathBuf>, // TODO: Make this accept Vec<path::PathBuf> of input images => the output_path would be enum OutputPath { path::PathBuf, format: String (for formating output based on the input files))} <06-10-20, kunzaatko> //

    /// Image file to draw the circle to or a `txt`/`npz`/`npy` file to write the circle parameters to _(does not work yet... prints to `/dev/stdout`)_
    #[structopt(name = "OUTPUT", short = "o", long = "output", parse(from_os_str))]
    pub output_path: Option<path::PathBuf>,

    #[structopt(skip = false)]
    // TODO: support output in .npy and .npz files using ndarray-npy <13-10-20, kunzaatko> //
    pub output_to_text: bool,

    /// Overwrite the output file, if it exists
    #[structopt(long = "overwrite")]
    overwrite: bool,

    /// Format of the output circles is an image type output _(does not work yet... does not support writing output to an image)_
    #[structopt(name = "FORMAT", short = "f", long = "format")]
    pub output_format: Option<CircleOutputFormat>,

    /// Limits to be applied to the search:
    /// 1) radius constraints (upper radius limit, lower radius limit) _(does not work yet...)_
    /// 2) limit to the distance of multiple found circles _(does not work yet...)_
    #[structopt(name = "LIMIT", short = "l", long = "limits")]
    pub circle_limits: Option<CircleLimits>,

    /// Generate shell completions (Defaults to /dev/stdout)
    #[structopt(name = "COMPLETION", long = "generate-completions")]
    pub completions: Option<Option<String>>,

    /// Path for the shell completion file generation
    #[structopt(name = "COMPLETION_PATH", long = "completion-path", parse(from_os_str))]
    pub completion_path: Option<path::PathBuf>,
} //}}}

impl Default for Config {
    //{{{
    fn default() -> Self {
        Self {
            image_path: None,
            output_path: None,
            output_to_text: false,
            overwrite: false,
            output_format: Some(CircleOutputFormat::default()),
            circle_limits: Some(CircleLimits::default()),
            completions: None,
            completion_path: None,
        }
    }
} //}}}

impl Config {
    //{{{
    // TODO: Implement Display <10-10-20, kunzaatko> //
    /// Supported input image file types
    pub const SUPPORTED_READ_IMAGE_TYPES: [&'static str; 6] =
        ["tiff", "tif", "png", "jpg", "webp", "gif"];
    /// Supported output file types
    pub const SUPPORTED_WRITE_IMAGE_TYPES: [&'static str; 6] =
        ["tiff", "tif", "png", "jpg", "webp", "gif"];
    /// Supported shells for completion generations
    pub const SUPPORTED_COMPLETION_SHELLS: [(&'static str, clap::Shell); 5] = [
        ("bash", clap::Shell::Bash),
        ("fish", clap::Shell::Fish),
        ("zsh", clap::Shell::Zsh),
        ("powershell", clap::Shell::PowerShell),
        ("elvish", clap::Shell::Elvish),
    ];

    /// New configuration from defaults
    pub fn new() -> Self {
        //{{{
        Self::default()
    } //}}}

    /// Check and return the configuration passed by command line flags
    pub fn parse() -> Result<Self, ConfigError> {
        //{{{
        let mut conf_from_cli = Config::from_args();

        if let Some(_) = &conf_from_cli.completions {
            if let Some(completion_path) = &conf_from_cli.completion_path {
                conf_from_cli.generate_completions(Some(&mut completion_path.clone()))?
            } else {
                conf_from_cli.generate_completions(None)?
            }
            process::exit(0) // TODO: Pass info to user, that there was nothing done except the generation of completions <13-10-20, kunzaatko> //
        }

        conf_from_cli.check_image_path()?;
        conf_from_cli.check_output_file()?;

        if let None = conf_from_cli.circle_limits {
            conf_from_cli.circle_limits = Some(CircleLimits::default());
        }

        Ok(conf_from_cli)
    } //}}}

    /// checks for possibilities:
    /// a) `image_path` exists
    /// b) the image has the supported extension for reading based on the `const SUPPORTED_READ_IMAGE_TYPES`
    fn check_image_path(&self) -> Result<(), InputImageError> {
        //{{{
        // check for image path.
        if let Some(file) = &self.image_path {
            // the image exists in fs
            if !(*file).exists() {
                return Err(InputImageError::ImageFileNotFound(file.to_path_buf()));
            }
            // the image has extension
            if let Some(ext) = (*file).extension() {
                // the extension is valid UTF
                if let Some(ext) = ext.to_str() {
                    // the image format is supported for read
                    if !Self::SUPPORTED_READ_IMAGE_TYPES
                        .iter()
                        .any(|ext_read| *ext_read == ext)
                    {
                        return Err(InputImageError::UnsupportedReadExtention(
                            file.to_path_buf(),
                            ffi::OsString::from(ext),
                        ));
                    }
                } else {
                    return Err(
                        InputImageError::InvalidExtension(
                            file.to_path_buf(),
                            ffi::OsString::from(ext),
                        ), // This is not so useful. Could me merged with `UnsupportedWriteExtention`
                    );
                }
            } else {
                return Err(InputImageError::NoExtention(file.to_path_buf()));
            };
        } else {
            return Err(InputImageError::NoFileGiven);
        }

        Ok(())
    } //}}}

    /// checks for possibilities:
    /// a) the image has the supported extension for writing based on the `const SUPPORTED_READ_IMAGE_TYPES`
    fn check_output_file(&mut self) -> Result<(), OutputFileError> {
        //{{{
        // generate output file from image file name
        self.generate_output();

        // has a supported extension
        // SAFETY: If the output_path did not exist, it has been generated with self.generate_output_if_not_provided()?
        if let Some(ext) = (&self.output_path).as_ref().unwrap().extension() {
            if !Self::SUPPORTED_WRITE_IMAGE_TYPES
                .iter()
                .any(|ext_write| *ext_write == ext)
                && !self.output_to_text
            {
                return Err(OutputFileError::UnsupportedWriteExtention(
                    (&self.output_path).as_ref().unwrap().to_path_buf(), // SAFETY: We can be sure that output path exists.
                    ffi::OsString::from(ext),
                ));
            }
        }

        // the output file exists already in the file system and not in overwrite mode
        if true == self.output_path.as_ref().unwrap().exists() && self.overwrite == false {
            return Err(
                OutputFileError::FileAlreadyExists(
                    (&self.output_path).as_ref().unwrap().to_path_buf(),
                ), // SAFETY: We can be sure that output path exists.
            );
        }
        Ok(())
    } //}}}

    /// checks whether the output is text or not from extension
    fn determine_output_to_text(&self) -> Result<bool, OutputFileError> {
        //{{{
        if let Some(output) = &self.output_path {
            match output.extension() {
                None => Ok(true), // The no file name case is not possible due to `self.output_path` being `Some`.
                Some(ext) if ext == "txt" => Ok(true),
                _ => Ok(false),
            }
        } else {
            Err(OutputFileError::NoFileGiven)
        }
    } //}}}

    /// Generates path to ".tiff" output image if no output file is provided
    fn generate_output(&mut self) {
        //{{{
        match self.determine_output_to_text() {
            Ok(to_text) => self.output_to_text = to_text,
            Err(e) if e == OutputFileError::NoFileGiven =>
            // If the output path is not set, set is as the input image plus "_out.tiff"
            {
                // TODO: support giving only extension <09-10-20, kunzaatko> //

                // SAFETY: There is no way the code could panic here since we already checked if the `image_file` exists as is non-None // TODO: Implement with returning `Result` value for more sturdiness <10-10-20, kunzaatko> //
                let mut output_path = self.image_path.clone().unwrap();
                output_path.set_extension("tiff");
                self.output_path = Some(output_path);
            }
            Err(_) => {} // This is not happening
        }
    } //}}}

    /// Generates shell completions in the directory `completion_path_opt` or to `/dev/stdout` if not provided
    fn generate_completions(
        &self,
        completion_path_opt: Option<&mut path::PathBuf>,
    ) -> Result<(), CompletionGenerationError> {
        //{{{
        // -> self.completions != None
        let mut app = Config::clap();
        // SAFETY: We check if there is None before calling function
        if let Some(shell_asked) = &self.completions.as_ref().unwrap() {
            let shell;

            // valid shell
            if let Some((shell_string, clap_shell)) = Config::SUPPORTED_COMPLETION_SHELLS
                .iter()
                .find(|(shell_string, clap_shell)| shell_string == shell_asked)
            {
                shell = *clap_shell;

                // valid completion path
                if let Some(completion_path) = completion_path_opt {
                    if completion_path.is_dir() {
                        // .is_dir() also checks for existence
                        // SAFETY: a valid path::PathBuf is just a String so this should never fail
                        app.gen_completions("houghse", shell, completion_path.to_str().unwrap());
                    } else if completion_path.is_file() {
                        // .is_file() also checks for existence
                        app.gen_completions_to(
                            "houghse",
                            shell,
                            // SAFETY: a valid path::PathBuf is just a String so this should never fail
                            &mut fs::File::create(completion_path.to_str().unwrap())?,
                        )
                    } else {
                        // -> !completion_path.exists()
                        return Err(CompletionGenerationError::CompletionPathNotFound(
                            completion_path.to_path_buf(),
                        ));
                    }
                } else {
                    app.gen_completions_to("houghse", shell, &mut io::stdout());
                }
            } else {
                // -> self.completions == Some(invalid_shell)
                return Err(CompletionGenerationError::InvalidShell(
                    shell_asked.to_string(),
                ));
            }
        // -> self.completions == Some(None)
        } else {
            // TODO: This should determine which shell to generate <11-10-20, kunzaatko> //
            todo!()
        }

        Ok(())
    } //}}}
} //}}}

impl std::fmt::Display for Config {
    //{{{
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", {
            if let Some(completion) = &self.completions {
                // Completion generation{{{
                if let Some(completion_path) = &self.completion_path {
                    format!(
                        "{} -> {}",
                        completion.as_ref().unwrap(),
                        completion_path.display()
                    )
                } else {
                    format!("{}", completion.as_ref().unwrap())
                }
            //}}}
            } else {
                // Transformation {{{
                format!(
                    "{}{}{}{}",
                    {
                        // Image path {{{
                        if let Some(image) = &self.image_path {
                            format!("Image path: {}\n", image.display())
                        } else {
                            "".to_string()
                        }
                    }, //}}}
                    {
                        // Output path {{{
                        if let Some(output) = &self.output_path {
                            format!("Output path: {}{}\n", output.display(), {
                                // Some output options{{{
                                if [self.overwrite, self.output_to_text].contains(&true) {
                                    format!(
                                        "{}{}",
                                        {
                                            // Overwrite {{{
                                            if self.overwrite {
                                                " (overwrite"
                                            } else {
                                                " ("
                                            }
                                        }, //}}}
                                        {
                                            // Output to text {{{
                                            if self.output_to_text && self.overwrite {
                                                ", text)"
                                            } else {
                                                "text)"
                                            }
                                        }, //}}}
                                    )
                                } else {
                                    "".to_string()
                                }
                            }) //}}}
                        } else {
                            // No output options {{{
                            "".to_string()
                        } //}}}
                    }, //}}}
                    {
                        // Output format {{{
                        if self.output_to_text {
                            "".to_string()
                        } else {
                            if let Some(format) = &self.output_format {
                                format!("  Output format:\n{}\n", format) // TODO: add whitespace correction <13-10-20, kunzaatko> //
                            } else {
                                format!("  Output format:\n{}", CircleOutputFormat::default())
                            }
                        }
                    }, //}}}
                    {
                        // Circle Limits {{{
                        if let Some(limits) = &self.circle_limits {
                            if limits != &CircleLimits::default() {
                                // TODO: Does this work or does it compare addresses?! <13-10-20, kunzaatko> //
                                format!("   Circle limits:\n{}\n", limits)
                            } else {
                                "no limits!".to_string()
                            }
                        } else {
                            "no limits!".to_string()
                        }
                    } //}}}
                )
            } //}}}
        })
    }
} //}}}

// TODO - for parsing into configuration
impl str::FromStr for CircleOutputFormat {
    //{{{
    type Err = ConfigError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        todo!()
    }
} //}}}

// TODO - for parsing into configuration
impl str::FromStr for CircleLimits {
    //{{{
    type Err = ConfigError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        todo!()
    }
} //}}}

#[cfg(test)]
mod test_config {
    //{{{
    use super::super::error::config_error::{InputImageError, OutputFileError}; // TODO: make without those supers <14-10-20, kunzaatko> //
    use super::*;
    use std::path::PathBuf;
    use std::str::FromStr;

    // Image file in config is present in the file-system
    #[test]
    fn input_file_does_not_exist() {
        let mut test = Config::default();
        test.image_path = Some(PathBuf::from_str("does_not_exist").unwrap());
        assert_eq!(
            test.check_image_path().unwrap_err(),
            InputImageError::ImageFileNotFound(test.image_path.unwrap())
        )
    }

    // Image file in config is of a supported file type. see: `SUPPORTED_READ_IMAGE_TYPES`.
    #[test]
    fn invalid_read_extension() {
        let mut test = Config::default();
        test.image_path = Some(PathBuf::from_str("./tests/image.txt").unwrap());
        assert_eq!(
            test.check_image_path().unwrap_err(),
            InputImageError::UnsupportedReadExtention(
                test.image_path.unwrap(),
                ffi::OsString::from("txt")
            )
        )
    }

    // If there is no output file specified in the config, generate output file from input file name.
    #[test]
    fn output_file_generation() {
        let mut test = Config::default();
        test.image_path = Some(PathBuf::from_str("./tests/generate.tif").unwrap());
        test.generate_output();
        assert_ne!(test.output_path, None);
        assert_eq!(
            Some(path::PathBuf::from("./tests/generate.tiff")),
            test.output_path
        );
    }

    // If the output file has no extention, set to text output.
    #[test]
    fn test_output_to_text_no_extension() {
        let mut test = Config::default();
        test.output_path = Some(PathBuf::from_str("./tests/image.tif").unwrap());
        test.output_path = Some(PathBuf::from_str("./tests/text").unwrap());
        test.generate_output();
        assert_eq!(test.output_to_text, true);
    }

    // If the output file has extention 'txt', set to text output.
    #[test]
    fn test_output_to_text_with_extension() {
        let mut test = Config::default();
        test.image_path = Some(PathBuf::from_str("./tests/image.tif").unwrap());
        test.output_path = Some(PathBuf::from_str("./tests/text.txt").unwrap());
        test.generate_output();
        assert_eq!(test.output_to_text, true);
    }

    // Output file in configuration is of a supported file type. see: `SUPPORTED_WRITE_IMAGE_TYPES`.
    #[test]
    fn unsupported_output_format() {
        let mut test = Config::default();
        test.image_path = Some(PathBuf::from_str("./tests/image.tif").unwrap());
        test.output_path = Some(PathBuf::from_str("./tests/output.unsupported_ext").unwrap());
        test.generate_output();
        assert_eq!(
            test.check_output_file(),
            Err(OutputFileError::UnsupportedWriteExtention(
                test.output_path.unwrap(),
                ffi::OsString::from("unsupported_ext"),
            ))
        )
    }

    #[test]
    fn output_file_exists_and_not_set_to_overwrite() {
        let mut test = Config::default();
        test.image_path = Some(PathBuf::from_str("./tests/image.tif").unwrap());
        test.output_path = Some(PathBuf::from_str("./tests/exists.tif").unwrap());
        test.generate_output();
        assert_eq!(
            test.check_output_file(),
            Err(OutputFileError::FileAlreadyExists(
                test.output_path.unwrap()
            ))
        )
    }

    #[test]
    fn output_file_exists_and_set_to_overwrite() {
        let mut test = Config::default();
        test.image_path = Some(PathBuf::from_str("./tests/image.tif").unwrap());
        test.output_path = Some(PathBuf::from_str("./tests/exists.tif").unwrap());
        test.overwrite = true;
        test.generate_output();
        assert_eq!(test.check_output_file(), Ok(()))
    }

    #[test]
    fn shell_completion_gen_file_created() {
        let mut test = Config::default();
        test.completions = Some(Some(String::from("zsh")));
    }
} //}}}