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
#![doc = include_str!("../README.md")]
use image::{DynamicImage, GenericImageView, SubImage};
use std::{
    collections::HashMap,
    fmt::{Debug, Display},
};

pub type BrushMap = HashMap<u128, char>;

/// The main interface to image to text converion
#[derive(Default)]
pub struct Insa {
    background: Option<(u8, u8, u8)>,
    invert: bool,
    brushes: BrushMap,
}
impl Debug for Insa {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "Insa {{ background: {:?}, invert: {}, brushes:[\n",
            self.background, self.invert
        ))?;
        for (i, c) in self.brushes() {
            f.write_fmt(format_args!("  (0b{i:0128b},'{c}'),\n"))?;
        }
        f.write_str("] }\n")
    }
}
impl Insa {
    /// Initialize using just space brush, no fixed background.
    pub fn plain() -> Insa {
        Self {
            background: None,
            invert: false,
            brushes: [(0, ' ')].into(),
        }
    }
    /// Initialize using well known round chars on dark background
    pub fn simple_on_dark() -> Insa {
        Insa { background: Some((50,50,50)), invert: false, brushes: [
            (0b00000000000000000000000000000000001111000100001001000010010000100011110001000010010000100100001001000010001111000000000000000000,'8'),
            (0b00000000000000000000000000000000000000000000000000111100010000100100001001000010010000100100001001000010001111000000000000000000,'o'),
            (0b00000000000000000000000000000000000110000010010000100100000110000000000000000000000000000000000000000000000000000000000000000000,'°'),
            (0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011000000110000000000000000000,'.'),
            (0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,' '),
        ].into() }
    }
    /// Initialize using well known round chars on dark background
    pub fn simple_on_bright() -> Insa {
        let mut me = Self::simple_on_dark();
        me.invert = true;
        me.background = Some((200, 200, 200));
        me
    }
    /// Initialize using well known block drawing elements and using background
    pub fn blocks() -> Insa {
        Insa { background: None, invert:false, brushes: [
            (0b00000000000000000000000000000000111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,'▆'),
            (0b11110000111100001111000011110000111100001111000011110000111100000000111100001111000011110000111100001111000011110000111100001111,'▚'),
            (0b00000000000000000000000000000000000000000000000000000000000000001111000011110000111100001111000011110000111100001111000011110000,'▖'),
            (0b11111111111111101111111011111100111111001111100011111000111100001111000011100000111000001100000011000000100000001000000010000000,'◤'),
            (0b11111111111111111111111111111111111111111111111111111111111111110000111100001111000011110000111100001111000011110000111100001111,'▜'),
            (0b11110000111100001111000011110000111100001111000011110000111100001111111111111111111111111111111111111111111111111111111111111111,'▙'),
            (0b11110000111100001111000011110000111100001111000011110000111100001111000011110000111100001111000011110000111100001111000011110000,'▌'),
            (0b11000000110000001100000011000000110000001100000011000000110000001100000011000000110000001100000011000000110000001100000011000000,'▎'),
            (0b11111100111111001111110011111100111111001111110011111100111111001111110011111100111111001111110011111100111111001111110011111100,'▊'),
            (0b00000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,'▇'),
            (0b00000000000000000000000000000000000000000000000011111111111111111111111111111111111111111111111111111111111111111111111111111111,'▅'),
            (0b11111000111110001111100011111000111110001111100011111000111110001111100011111000111110001111100011111000111110001111100011111000,'▋'),
            (0b11111111111111111111111111111111111111111111111111111111111111111111000011110000111100001111000011110000111100001111000011110000,'▛'),
            (0b00000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111111111111111111111111111111,'▃'),
            (0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,' '),
            (0b00001111000011110000111100001111000011110000111100001111000011110000000000000000000000000000000000000000000000000000000000000000,'▝'),
            (0b11111110111111101111111011111110111111101111111011111110111111101111111011111110111111101111111011111110111111101111111011111110,'▉'),
            (0b00001111000011110000111100001111000011110000111100001111000011110000111100001111000011110000111100001111000011110000111100001111,'▐'),
            (0b00000000000000000000000000000000000000000000000000000000000000000000111100001111000011110000111100001111000011110000111100001111,'▗'),
            (0b00001111000011110000111100001111000011110000111100001111000011111111000011110000111100001111000011110000111100001111000011110000,'▞'),
            (0b00000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111,'▄'),
            (0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111,'▁'),
            (0b11111111011111110111111100111111001111110001111100011111000011110000111100000111000001110000001100000011000000010000000100000001,'◥'),
            (0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111111,'▂'),
            (0b11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,'█'),
            (0b11111111111111110000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,'▔'),
            (0b00001111000011110000111100001111000011110000111100001111000011111111111111111111111111111111111111111111111111111111111111111111,'▟'),
            (0b11100000111000001110000011100000111000001110000011100000111000001110000011100000111000001110000011100000111000001110000011100000,'▍'),
            (0b10000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000,'▏'),
            (0b00000001000000010000000100000011000000110000011100000111000011110000111100011111000111110011111100111111011111110111111111111111,'◢'),
            (0b10000000100000001000000011000000110000001110000011100000111100001111000011111000111110001111110011111100111111101111111011111111,'◣'),
            (0b11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000,'▀'),
            (0b11110000111100001111000011110000111100001111000011110000111100000000000000000000000000000000000000000000000000000000000000000000,'▘'),
            (0b00000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001,'▕'),
        ].into() }
    }

    #[cfg(feature = "fontdue")]
    /// Load additional brushes from a font
    ///
    /// ```
    /// let font = include_bytes!("../docs/unifont-15.0.01.ttf");
    /// let font = fontdue::Font::from_bytes(font.as_ref(), fontdue::FontSettings::default())
    ///  .expect("tried and tested included font");
    /// let mut insa = insa::Insa::default();
    /// insa.load_brushes(&font, ".oO8°");
    /// println!("{insa:?}")
    /// ```
    pub fn load_brushes(&mut self, font: &fontdue::Font, brushes: impl AsRef<str>) -> &mut Self {
        let brushes = brushes
            .as_ref()
            .chars()
            .map(|c| (rasterize_u128(font, c), c));
        self.brushes.extend(brushes);
        self
    }
    /// ref access the internal brush map
    pub fn brushes(&self) -> &BrushMap {
        &self.brushes
    }
    /// Mut access internal brush map
    pub fn brushes_mut(&mut self) -> &mut BrushMap {
        &mut self.brushes
    }
    /// Does Insa invert dark/light?
    pub fn invert(&self) -> bool {
        self.invert
    }
    /// Mut access to - does Insa invert dark/light?
    pub fn invert_mut(&mut self) -> &mut bool {
        &mut self.invert
    }
    /// Should Insa invert dark/light?
    pub fn set_invert(&mut self, invert: bool) -> &mut Self {
        self.invert = invert;
        self
    }
    /// Does Insa invert dark/light?
    pub fn fixed_background(&self) -> Option<(u8, u8, u8)> {
        self.background
    }
    /// Mut access to - does Insa invert dark/light?
    pub fn fixed_background_mut(&mut self) -> Option<&mut (u8, u8, u8)> {
        self.background.as_mut()
    }
    /// Should Insa invert dark/light?
    pub fn set_fixed_background(&mut self, invert: Option<(u8, u8, u8)>) -> &mut Self {
        self.background = invert;
        self
    }
    /// The width of the brush in pixels
    pub fn brush_width(&self) -> u8 {
        8
    }
    /// The height of the brush in pixels
    pub fn brush_height(&self) -> u8 {
        16
    }
    /// Convert a raster bitmap image to text.
    /// The returned iterator reveals the number of text columns and rows
    pub fn convert<'a>(&'a self, img: &'a DynamicImage) -> ConvertIterator<'a> {
        ConvertIterator::new(img, &self)
    }
    /// Convert a single symbol, assuming position 0,0 and the symbol width and height for input
    pub fn convert_symbol(&self, img: &SubImage<&DynamicImage>) -> Symbol {
        let (bitmap, mut front_color, mut back_color) = self.bitmap(img);
        let (mut brush, score) = self.get_brush(bitmap);
        if self.background.is_none() && score != u8::MAX {
            let (ibrush, iscore) = self.get_brush(!bitmap);
            if iscore > score {
                brush = ibrush;
                //score = iscore;
                std::mem::swap(&mut front_color, &mut back_color);
            }
        }
        let back_color = match self.background {
            Some(_) => None,
            None => Some(back_color),
        };
        let brush = *brush;
        Symbol {
            brush,
            front_color,
            back_color,
        }
    }
    fn get_brush(&self, bitmap: u128) -> (&char, u8) {
        if let Some(brush) = self.brushes.get(&bitmap) {
            return (brush, u8::MAX);
        }
        let mut my_brush = &' ';
        let mut my_score = 0;
        for (candidate, brush) in &self.brushes {
            let xor = candidate ^ bitmap;
            let new_score = 128 - xor.count_ones();
            if new_score >= my_score {
                my_score = new_score;
                my_brush = brush;
                if my_score >= 120 {
                    break;
                }
            }
        }

        (my_brush, my_score as u8)
    }
    fn bitmap(&self, img: &SubImage<&DynamicImage>) -> (u128, (u8, u8, u8), (u8, u8, u8)) {
        // get all the pixels, while at it, avg colors
        let ((tr, tg, tb), pixs) = (0..128).map(|idx| self.bit(idx, img)).fold(
            ((0, 0, 0), vec![]),
            |((tr, tg, tb), mut pixs), (r, g, b, a)| {
                pixs.push((r, g, b, a));
                ((tr + r as u16, tg + g as u16, tb + b as u16), pixs)
            },
        );

        // the average color
        let (ar, ag, ab) = ((tr / 128) as u8, (tg / 128) as u8, (tb / 128) as u8);

        // figure out the threshold
        let (tr, tg, tb) = match self.background {
            None => (ar, ag, ab),
            Some((br, bg, bb)) => (br, bg, bb),
        };

        // combine into bitmap
        let (bm, fr, fg, fb, br, bg, bb) = (0..128).map(|idx| (pixs[idx], idx)).fold(
            (0, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16),
            |(bm, fr, fg, fb, br, bg, bb), ((r, g, b, _a), idx)| {
                let mut distance =
                    r as isize - tr as isize + g as isize - tg as isize + b as isize - tb as isize;
                if self.invert {
                    distance = -distance;
                }
                let p = if distance > 0 { 1 } else { 0 };
                let front = p as u16;
                let back = (p ^ 1) as u16;
                (
                    bm | ((front as u128) << (127 - idx)),
                    fr + front * r as u16,
                    fg + front * g as u16,
                    fb + front * b as u16,
                    br + back * r as u16,
                    bg + back * g as u16,
                    bb + back * b as u16,
                )
            },
        );

        if let Some(bg) = self.background {
            (bm, (ar, ag, ab), bg)
        } else {
            let fs = bm.count_ones() as u16;
            let bs = bm.count_zeros() as u16;

            let mut front_color = if fs == 0 {
                (127, 127, 127)
            } else {
                (
                    (fr.saturating_div(fs)) as u8,
                    (fg.saturating_div(fs)) as u8,
                    (fb.saturating_div(fs)) as u8,
                )
            };
            let back_color = if bs == 0 {
                front_color
            } else {
                (
                    (br.saturating_div(bs)) as u8,
                    (bg.saturating_div(bs)) as u8,
                    (bb.saturating_div(bs)) as u8,
                )
            };
            if fs == 0 {
                front_color = back_color;
            }

            (bm, front_color, back_color)
        }
    }
    fn bit(&self, idx: u8, img: &SubImage<&DynamicImage>) -> (u8, u8, u8, u8) {
        assert!(idx < 128, "It's a u128");

        let x = (idx % self.brush_width()) as u32;
        let y = (idx / self.brush_height()) as u32;
        if x >= img.width() || y >= img.height() {
            return (0, 0, 0, 0);
        }
        let pix = img.get_pixel(x, y);
        let [r, g, b, a] = pix.0;
        (r, g, b, a)
    }
}

pub struct ConvertIterator<'a> {
    img: &'a image::DynamicImage,
    insa: &'a Insa,
    bwidth: u32,
    bheight: u32,
    rows: u32,
    cols: u32,
    idx: u32,
}
impl<'a> ConvertIterator<'a> {
    pub fn cols(&self) -> u32 {
        self.cols
    }
    pub fn rows(&self) -> u32 {
        self.rows
    }
}
impl<'a> ConvertIterator<'a> {
    pub fn new(img: &'a image::DynamicImage, insa: &'a Insa) -> Self {
        let bwidth = insa.brush_width() as u32;
        let bheight = insa.brush_height() as u32;
        let cols = img.width() / bwidth;
        let rows = img.height() / bheight;
        Self {
            img,
            insa,
            bwidth,
            bheight,
            rows,
            cols,
            idx: 0,
        }
    }
}
impl<'a> Iterator for ConvertIterator<'a> {
    type Item = ((u32, u32), Symbol);
    fn next(&mut self) -> Option<Self::Item> {
        // 0 = not iterated yet, 1 = first item, so we reduce idx by 1 for c*r
        self.idx = self.idx.checked_add(1)?;
        let c = (self.idx - 1) % self.cols;
        let r = (self.idx - 1) / self.cols;
        if r >= self.rows {
            return None;
        }

        let x = c * self.bwidth;
        let y = r * self.bheight;
        let w = (self.img.width() - x).clamp(0, self.bwidth);
        let h = (self.img.height() - y).clamp(0, self.bheight);

        let spot = self.img.view(x, y, w, h);

        Some(((c, r), self.insa.convert_symbol(&spot)))
    }
}
#[cfg(feature = "fontdue")]
/// Rasterize a font character into a u128 bitmap.
/// This is used for matching brushes.
pub fn rasterize_u128(font: &fontdue::Font, c: char) -> u128 {
    let mut bitmap = 0u128;
    let (metrics, pixs) = font.rasterize(c, 16.0);

    const WIDTH: isize = 8;
    const HEIGHT: isize = WIDTH * 2;
    const PIX_THRESHOLD: u8 = 50;

    for (i, pix) in pixs.into_iter().enumerate() {
        let x = (i % metrics.width) as isize;
        let y = (i / metrics.width) as isize;

        let x = x + metrics.xmin as isize;
        let y = y + HEIGHT - metrics.height as isize - metrics.ymin as isize - HEIGHT / 6;
        if x < 0 || y < 0 || x >= WIDTH || y >= HEIGHT {
            continue;
        }
        let pix = if pix >= PIX_THRESHOLD {
            1 << (WIDTH - 1 - x) << ((HEIGHT - 1 - y) * WIDTH)
        } else {
            0
        };
        bitmap = bitmap | pix;
    }
    bitmap
}

pub fn dump_bitmap_u128(bitmap: u128) -> String {
    let mut dump = String::default();
    for row in 0..16 {
        let row = 0b11111111 & (bitmap >> 8 * (15 - row));
        dump += &format!("{row:#010b}\n");
    }
    dump
}
pub struct Symbol {
    pub brush: char,
    pub front_color: (u8, u8, u8),
    pub back_color: Option<(u8, u8, u8)>,
}

impl Display for Symbol {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let Self {
            brush,
            front_color: (fr, fg, fb),
            back_color,
        } = &self;

        // ESC[ 38;2;⟨r⟩;⟨g⟩;⟨b⟩ m Select RGB foreground color
        // ESC[ 48;2;⟨r⟩;⟨g⟩;⟨b⟩ m Select RGB background color
        if let Some((br, bg, bb)) = back_color {
            write!(f, "\x1b[48;2;{br};{bg};{bb}m")?;
        }
        write!(f, "\x1b[38;2;{fr};{fg};{fb}m")?;
        write!(f, "\x1b[1m")?;
        write!(f, "{brush}")
    }
}