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
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::fs;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};

use palette::luma::Luma;
use palette::{encoding, Srgb};
use structopt::StructOpt;

#[derive(StructOpt, Debug)]
#[structopt(name = "posterust")]
pub struct Opt {
    /// Input file
    #[structopt(
        short,
        long,
        parse(from_os_str),
        value_delimiter = ",",
        required = true,
        index = 1
    )]
    input: Vec<PathBuf>,

    /// Number of value steps to display.
    #[structopt(short, long, default_value = "5", required = false)]
    num_steps: u8,

    /// Specify user value steps, example: `1,5,9`. Maximum of 11 values.
    #[structopt(
        short,
        long,
        min_values = 2,
        max_values = 11,
        value_delimiter = ",",
        required = false
    )]
    values: Vec<u8>,

    /// Colors to use in place of greyscale. Maximum of 11 values, must match
    /// with corresponding amount of `values` or `num_steps`.
    #[structopt(
        short,
        long,
        min_values = 2,
        max_values = 11,
        value_delimiter = ",",
        required = false
    )]
    colors: Vec<String>,

    /// File extension of output.
    #[structopt(short, long = "ext", default_value = "png", required = false)]
    extension: String,

    /// Use values declared with `--values` to color image and determine buckets.
    #[structopt(short, long)]
    keep: bool,

    /// Debug flag, prints arguments and does not output image.
    #[structopt(short, long)]
    debug: bool,

    /// Output file. When input is multiple files, this string will be appended
    /// to the filename. File type extension can be declared here for `.jpg`.
    #[structopt(short, long, parse(from_os_str))]
    output: Option<PathBuf>,
}

pub fn run(opt: Opt) -> Result<(), Box<dyn Error>> {
    if opt.debug {
        println!("{:#?}", opt);
    }
    let files = opt.input;
    let files_len = files.len();
    let values_len = opt.values.len() as u8;
    let colors_len = opt.colors.len() as u8;
    let luma_vec;
    let generated_colors;
    match values_len {
        0 => {
            if colors_len == 0 {
                luma_vec = luma_threshold(opt.num_steps);
                generated_colors = get_greyscale_hashmap(&luma_vec);
            } else {
                luma_vec = luma_threshold(colors_len);
                generated_colors = get_color_hashmap(&opt.colors, &luma_vec)?;
            }
        }
        2..=11 => {
            if colors_len == 0 {
                if !opt.keep {
                    luma_vec = luma_threshold_custom(opt.values);
                } else {
                    let temp_luma_vec = luma_threshold_custom(opt.values);
                    luma_vec = luma_threshold_keep(&temp_luma_vec, values_len);
                }
                generated_colors = get_custom_greyscale_hashmap(&luma_vec);
            } else {
                if values_len != colors_len {
                    println!("Error: Number of values and colors do not match.");
                    return Ok(());
                }
                if !opt.keep {
                    luma_vec = luma_threshold_custom(opt.values);
                } else {
                    let temp_luma_vec = luma_threshold_custom(opt.values);
                    luma_vec = luma_threshold_keep(&temp_luma_vec, values_len);
                }
                generated_colors = get_color_hashmap_custom(&opt.colors, &luma_vec)?;
            }
        }
        _ => {
            // Should be unreachable by structopt `max_values = 11`
            panic!("Maximum of 11 values allowed, minimum of 2 values needed.");
        }
    }

    if opt.debug {
        println!("{:?}", &luma_vec);
    }

    for file in files {
        let img = image::open(&file)?.to_rgb();
        let imgx = img.dimensions().0;
        let imgy = img.dimensions().1;
        let mut imgbuf: image::RgbImage = image::ImageBuffer::new(imgx, imgy);

        for (x, y, out_pixel) in imgbuf.enumerate_pixels_mut() {
            let in_pixel = img.get_pixel(x, y);
            let luma = (Luma::<encoding::Srgb>::from(
                Srgb::from_components((in_pixel[0], in_pixel[1], in_pixel[2])).into_format::<f32>(),
            )
            .luma
                * 255.0)
                .round() as u8;
            let color_key = get_threshold_key(luma, &luma_vec);
            let out_rgb = generated_colors.get(&color_key).unwrap();
            *out_pixel = image::Rgb([out_rgb.red, out_rgb.green, out_rgb.blue]);
        }

        // If single file, use output provided or generate filename.
        // If multiple files, try using output filename with extension provided.
        let title;
        if files_len == 1 {
            match &opt.output {
                Some(x) => {
                    let mut temp = x.clone();
                    match temp.extension() {
                        Some(_) => {}
                        None => {
                            temp.set_extension(&opt.extension);
                        }
                    }
                    title = temp;
                }
                None => {
                    let mut temp = PathBuf::from(generate_filename(&file)?);
                    temp.set_extension(&opt.extension);
                    title = temp;
                }
            }
        } else {
            match &opt.output {
                Some(x) => {
                    let mut temp = x.clone();
                    let clone = temp.clone();
                    let ext;
                    match clone.extension() {
                        Some(y) => {
                            ext = y.to_str().unwrap();
                        }
                        None => {
                            ext = &opt.extension;
                        }
                    }
                    temp.set_file_name(format!(
                        "{}-{}",
                        &file.file_stem().unwrap().to_str().unwrap(),
                        &temp.file_stem().unwrap().to_str().unwrap()
                    ));
                    title = temp.with_extension(ext);
                }
                None => {
                    let mut temp = PathBuf::from(generate_filename(&file)?);
                    temp.set_extension(&opt.extension);
                    title = temp;
                }
            }
        }

        if opt.debug {
            return Ok(());
        }

        // Delete file that gets created but can't be written to.
        match imgbuf.save(&title) {
            Ok(_) => {}
            Err(err) => {
                println!("Error: {}.", err);
                fs::remove_file(&title)?;
            }
        }
    }

    Ok(())
}

/// Generates the threshold buckets for `levels` to be divided into.
fn luma_threshold(num: u8) -> Vec<u8> {
    let step = 255 / num;
    let mut v = Vec::with_capacity(usize::from(num));
    for i in 0..num {
        v.push(i * step);
    }
    v
}

/// Generates user specified threshold buckets for `levels` to be divided into.
fn luma_threshold_custom(values: Vec<u8>) -> Vec<u8> {
    const BUCKET: u8 = 23;
    const LEN: usize = 11;
    let mut levels: Vec<u8> = Vec::with_capacity(11);
    let mut arr = [0; LEN];

    for val in values {
        if val < 11 {
            levels.push(val);
        } else {
            println!("Maximum value level is 10, {} will be clamped to 10.", val);
            levels.push(10);
        }
    }
    levels.sort();
    levels.dedup();

    let mut counter = 0;
    let mut next = *levels.get(1).unwrap();
    for (n, item) in arr.iter_mut().enumerate().take(LEN) {
        *item = *levels.get(counter).unwrap() * BUCKET;
        if n + 1 == usize::from(next) {
            counter += 1;
            if counter < levels.len() - 1 {
                next = *levels.get(counter + 1).unwrap()
            }
        }
    }
    arr.to_vec()
}

/// Replace user specified value colors in `luma_vec` with evenly spaced colors
/// as in `luma_threshold`.
fn luma_threshold_keep(vec: &[u8], num: u8) -> Vec<u8> {
    let step = 255 / num;
    let mut ret = Vec::with_capacity(11);
    let mut counter = 0;
    let mut curr = *vec.get(0).unwrap();
    for i in vec {
        if *i != curr {
            curr = *i;
            counter += 1;
        }
        ret.push(counter * step);
    }
    ret
}

/// Called when no output name is supplied. Appends a timestamp to the input
/// filename.
fn generate_filename(path: &PathBuf) -> Result<String, CliError> {
    let filename = path.file_stem().unwrap().to_str().unwrap().to_string();
    let now = SystemTime::now().duration_since(UNIX_EPOCH)?;
    let secs = now.as_secs();
    let millis = format!("{:03}", now.subsec_millis());
    Ok(filename + "-" + &secs.to_string() + &millis)
}

/// Generate the greyscale colors to fill in the image based on values calculated
/// from `custom_luma_threshold`.
fn get_greyscale_hashmap(luma_zones: &[u8]) -> HashMap<u8, Srgb<u8>> {
    let mut hash = HashMap::new();
    if let Some((last, elements)) = luma_zones.split_last() {
        for i in elements {
            let x = *i;
            hash.insert(x, Srgb::from_components((x, x, x)));
        }
        hash.insert(*last, Srgb::from_components((255, 255, 255)));
    }
    hash
}

/// Generate the user colors to fill in the image based on values calculated
/// from `custom_luma_threshold`.
fn get_custom_greyscale_hashmap(luma_zones: &[u8]) -> HashMap<u8, Srgb<u8>> {
    let mut hash = HashMap::new();
    for i in luma_zones {
        let x = *i;
        hash.insert(x, Srgb::from_components((x, x, x)));
    }
    hash
}

/// Retrieve corresponding luma bucket key value.
fn get_threshold_key(in_color: u8, luma_vec: &[u8]) -> u8 {
    let mut key = luma_vec[0];
    for i in luma_vec {
        if in_color <= *i {
            return key;
        }
        key = *i;
    }
    key
}

/// Generate the user colors to fill in the image based on number of values
/// specified in `opt.colors`.
fn get_color_hashmap(
    colors: &[String],
    luma_zones: &[u8],
) -> Result<HashMap<u8, Srgb<u8>>, CliError> {
    let mut hash = HashMap::new();
    let iter = colors.iter().zip(luma_zones.iter());
    for (color, luma) in iter {
        let c = color.trim_start_matches("#");
        let x = *luma;
        hash.insert(x, parse_color(&c)?);
    }
    Ok(hash)
}

/// Generate the user colors to fill in the image based on values specified in
/// in `-v` and colors in `opt.colors`. Similar to `luma_threshold_keep`.
fn get_color_hashmap_custom(
    colors: &[String],
    luma_zones: &[u8],
) -> Result<HashMap<u8, Srgb<u8>>, CliError> {
    let mut hash = HashMap::new();
    let mut counter = 0;
    let mut curr = luma_zones[0];
    for luma in luma_zones.iter() {
        if *luma != curr {
            curr = *luma;
            counter += 1;
        }
        let c = colors[counter].trim_start_matches("#");
        let x = *luma;
        hash.insert(x, parse_color(&c)?);
    }
    Ok(hash)
}

fn parse_color(c: &str) -> Result<Srgb<u8>, CliError> {
    let red = u8::from_str_radix(
        match &c.get(0..2) {
            Some(x) => x,
            None => {
                println!("Invalid color: {}", c);
                return Err(CliError::InvalidHex);
            }
        },
        16,
    )?;
    let green = u8::from_str_radix(
        match &c.get(2..4) {
            Some(x) => x,
            None => {
                println!("Invalid color: {}", c);
                return Err(CliError::InvalidHex);
            }
        },
        16,
    )?;
    let blue = u8::from_str_radix(
        match &c.get(4..6) {
            Some(x) => x,
            None => {
                println!("Invalid color: {}", c);
                return Err(CliError::InvalidHex);
            }
        },
        16,
    )?;
    Ok(Srgb::new(red, green, blue))
}

#[derive(Debug)]
pub enum CliError {
    File(std::io::Error),
    Parse(std::num::ParseIntError),
    Time(std::time::SystemTimeError),
    InvalidHex,
}

impl From<std::io::Error> for CliError {
    fn from(err: std::io::Error) -> CliError {
        CliError::File(err)
    }
}

impl From<std::num::ParseIntError> for CliError {
    fn from(err: std::num::ParseIntError) -> CliError {
        CliError::Parse(err)
    }
}

impl From<std::time::SystemTimeError> for CliError {
    fn from(err: std::time::SystemTimeError) -> CliError {
        CliError::Time(err)
    }
}

impl fmt::Display for CliError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            CliError::File(ref err) => write!(f, "File error: {}", err),
            CliError::InvalidHex => {
                write!(f, "Error: Invalid hex color length, must be 6 characters.")
            }
            CliError::Parse(ref err) => write!(f, "Parse error: {}", err),
            CliError::Time(ref err) => write!(f, "Time error: {}", err),
        }
    }
}

impl Error for CliError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            CliError::File(err) => Some(err),
            CliError::InvalidHex => None,
            CliError::Parse(err) => Some(err),
            CliError::Time(err) => Some(err),
        }
    }
}