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
pub mod gimp;
pub mod web_algorithms;
//use gimp;

#[cfg(feature = "labels")]
pub mod labels;

use cfg_if::cfg_if;
use image::{GenericImage, ImageBuffer, Rgba,RgbaImage};
use std::path::PathBuf;
use web_algorithms::{anomylize, blindMK, monochrome};

#[derive(Clone)]
pub enum RevBlind {
    Protan,
    Deutan,
    Tritan,
}

#[derive(Debug, PartialEq)]
pub struct CombineInfo {
    total_height: u32,
    total_width: u32,
    positions: Vec<(u32, u32)>,
}

pub struct Config {
    pub combine_output: bool,
    #[cfg(feature = "labels")]
    pub render_label: bool,
}

pub fn process(input: &PathBuf, config: &Config) -> Result<(), Box<dyn std::error::Error>> {
    let path = format!("{}", input.display());
    let img = image::open(&input)?.to_rgba();
    let (name, extension) = path.split_at(
        path.rfind(".")
            .expect("path does not contain a detectable extension"),
    );

    let filters: [(&str, Box<dyn Fn(&Rgba<u8>) -> Rgba<u8>>); 11] = [
        ("Achromatomaly", Box::new(|p| anomylize(p, monochrome(p)))),
        ("Achromatopsia", Box::new(|p| monochrome(p))),
        (
            "Deuteranomaly",
            Box::new(|p| anomylize(p, blindMK(p, RevBlind::Deutan))),
        ),
        ("Deuteranopia", Box::new(|p| blindMK(p, RevBlind::Deutan))),
        (
            "DeuteranopiaBVM97",
            Box::new(|p| gimp::bvm97(RevBlind::Deutan)(p)),
        ),
        (
            "Protanomaly",
            Box::new(|p| anomylize(p, blindMK(p, RevBlind::Protan))),
        ),
        ("Protanopia", Box::new(|p| blindMK(p, RevBlind::Protan))),
        (
            "ProtanopiaBVM97",
            Box::new(|p| gimp::bvm97(RevBlind::Protan)(p)),
        ),
        (
            "Tritanomaly",
            Box::new(|p| anomylize(p, blindMK(p, RevBlind::Tritan))),
        ),
        ("Tritanopia", Box::new(|p| blindMK(p, RevBlind::Tritan))),
        (
            "TritanopiaBVM97",
            Box::new(|p| gimp::bvm97(RevBlind::Tritan)(p)),
        ),
    ];

    let mut processed_images = vec![];
    if config.combine_output {
        let mut buffer = setup_buffer(&img, "Original", config);
        buffer.copy_from(&img, 0, 0);
        processed_images.push(buffer);
    }

    for (label, func) in filters.iter() {
        let out_filename = format!("{}_{}{}", name, label, extension);
        print!("preparing {:?} ... ", out_filename);
        flush()?;

        let mut buffer = setup_buffer(&img, &label, config);

        for (x, y, pixel) in img.enumerate_pixels() {
            buffer.put_pixel(x, y, func(pixel));
        }

        if config.combine_output {
            processed_images.push(buffer);
            println!("partial image complete");
        } else {
            print!("saving ... ");
            flush()?;
            buffer.save(out_filename)?;
            println!("done");
        }
    }

    if config.combine_output {
        assert!(processed_images.len() > 0, "no partial images found");
        let out_filename = format!("{}_combined{}", name, extension);

        let max_dimensions = processed_images.iter().fold((0,0), |b, i| b.max(i.dimensions()));
        let positions = calculate_combined_positions(max_dimensions, processed_images.len());

        print!("Combining {} images ...", processed_images.len());
        flush()?;
        let mut buffer: ImageBuffer<Rgba<u8>, _> =
            ImageBuffer::new(positions.total_width, positions.total_height);

        for (img, (x, y)) in processed_images.iter().zip(positions.positions.iter()) {
            buffer.copy_from(img, *x, *y);
        }

        print!("saving {} ... ", out_filename);
        flush()?;
        buffer.save(out_filename)?;
    }

    Ok(())
}

cfg_if! {
    if #[cfg(feature = "labels")] {
        fn setup_buffer(img: &RgbaImage, label: &str, config: &Config) -> RgbaImage {
            let mut width = img.width();
            let mut height = img.height();
                let label = if config.render_label {
                    let label = labels::render(label);
                    height += label.height();
                    width = width.max(label.width());
                    Some(label)
                } else {
                    None
                };
            let mut buffer = ImageBuffer::new(width, height);
                if let Some(label) = label {
                    // centering text
                    let x = width.saturating_sub(label.width()) / 2;
                    buffer.copy_from(&label, x, img.height());
            }
            buffer
        }
    } else {
        fn setup_buffer(img: &RgbaImage, _label: &str, _: &Config) -> RgbaImage {
            ImageBuffer::new(img.width(), img.height())
        }
    }
}

fn flush() -> std::io::Result<()> {
    use std::io::Write;
    std::io::stdout().flush()
}

/// Calculate a grid with collapsed margins
fn calculate_combined_positions((width, height): (u32, u32), n_pictures: usize) -> CombineInfo {
    let margin = 25;
    assert!(n_pictures > 0, "n_pictures must be non-zero");

    let sqrt = (n_pictures as f64).sqrt();
    let columns = sqrt.ceil() as u32;
    let rows = sqrt.floor() as u32;
    println!("columns: {}; rows: {};", columns, rows);

    let mut positions = vec![];
    for y in 0..rows {
        for x in 0..columns {
            positions.push((
                margin + x * (width + margin),
                margin + y * (height + margin),
            ));
        }
    }
    assert_eq!(n_pictures, positions.len());

    CombineInfo {
        total_width: margin + (margin + width) * columns,
        total_height: margin + (margin + height) * rows,
        positions,
    }
}

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

    const MARGIN: u32 = 25;

    #[test]
    fn single() {
        let positions = calculate_combined_positions((20, 10), 1);
        assert_eq!(positions.total_width, MARGIN + 20 + MARGIN);
        assert_eq!(positions.total_height, MARGIN + 10 + MARGIN);
        assert_eq!(positions.positions, [(MARGIN, MARGIN)]);
    }

    #[test]
    fn four() {
        let positions = calculate_combined_positions((20, 10), 4);
        assert_eq!(
            CombineInfo {
                total_width: MARGIN + 2 * (20 + MARGIN),
                total_height: MARGIN + 2 * (10 + MARGIN),
                positions: vec![
                    (MARGIN, MARGIN),
                    (MARGIN + 20 + MARGIN, MARGIN), // expect a 2x2 matrix
                    (MARGIN, MARGIN + 10 + MARGIN),
                    (MARGIN + 20 + MARGIN, MARGIN + 10 + MARGIN),
                ],
            },
            positions
        );
    }

    #[test]
    fn twelfe() {
        let positions = calculate_combined_positions((20, 10), 12);
        let row1 = MARGIN + 10 + MARGIN;
        let row2 = MARGIN + 2 * (10 + MARGIN);
        assert_eq!(
            CombineInfo {
                total_width: MARGIN + 4 * (20 + MARGIN),
                total_height: MARGIN + 3 * (10 + MARGIN),
                positions: vec![
                    (MARGIN + 0 * 45, MARGIN),
                    (MARGIN + 1 * 45, MARGIN),
                    (MARGIN + 2 * 45, MARGIN),
                    (MARGIN + 3 * 45, MARGIN), // expect a 4x3 matrix
                    (MARGIN + 0 * 45, row1),
                    (MARGIN + 1 * 45, row1),
                    (MARGIN + 2 * 45, row1),
                    (MARGIN + 3 * 45, row1), // row 2
                    (MARGIN + 0 * 45, row2),
                    (MARGIN + 1 * 45, row2),
                    (MARGIN + 2 * 45, row2),
                    (MARGIN + 3 * 45, row2)
                ],
            },
            positions
        );
    }
}