codevis 0.8.4

A tool for turning your code into one large image
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
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
use crate::render::{BgColor, FgColor};
use bstr::ByteSlice;
use image::{ImageBuffer, Rgb};
use std::ops::{Deref, DerefMut};
use std::path::Path;
use syntect::highlighting::{Color, Style};
use unifont_bitmap::Unifont;

/// The result of processing a chunk.
pub struct Outcome {
    /// The longest line we encountered in unicode codepoints.
    pub longest_line_in_chars: usize,
    /// The last used background color
    pub background: Option<Rgb<u8>>,
}

pub struct Context {
    pub column_width: u32,
    pub line_height: u32,
    pub char_width: u32,
    pub total_line_count: u32,
    pub line_num: u32,
    pub lines_per_column: u32,

    pub fg_color: FgColor,
    pub bg_color: BgColor,
    pub highlight_truncated_lines: bool,

    pub file_index: usize,
    pub color_modulation: f32,
    pub tab_spaces: u32,
    pub readable: bool,
    pub show_filenames: bool,
    pub line_nums: bool,
}

/// Return the `(x, y)` offsets to apply to the given line, to wrap columns of lines into the
/// target image.
pub fn calc_offsets(
    line_num: u32,
    lines_per_column: u32,
    column_width: u32,
    line_height: u32,
) -> (u32, u32) {
    (
        (line_num / lines_per_column) * column_width,
        (line_num % lines_per_column) * line_height,
    )
}

/// Ensures a string has a minimum number of characters in it by
/// appending spaces to the beginging of the string if its characters
/// are too few. This is used for formatting the spacing of line_nums.
fn ensure_width(str: String, width: u32) -> String {
    let spaces_to_add = width as usize - str.len();
    let mut spaces = String::new();
    for _ in 0..spaces_to_add {
        spaces.push(' ');
    }
    spaces + &str
}

/// Renders text onto an existing image.
///
/// Images of proper dimensions must be pre-allocated before calling this function.
/// This function can be used to render one file/string of text, to a single image,
/// or called repeatedly on different files/strings, and passed the same image, to
/// render different bodies of text in different areas of the same image.
pub fn process<C>(
    filepath: &Path,
    content: &str,
    img: &mut ImageBuffer<Rgb<u8>, C>,
    mut highlight: impl FnMut(&str) -> Result<Vec<(Style, &str)>, syntect::Error>,
    Context {
        column_width,
        line_height,
        char_width,
        total_line_count,
        highlight_truncated_lines,
        mut line_num,
        lines_per_column,
        fg_color,
        bg_color,
        file_index,
        color_modulation,
        tab_spaces,
        readable,
        show_filenames,
        line_nums,
    }: Context,
) -> anyhow::Result<Outcome>
where
    C: Deref<Target = [u8]>,
    C: DerefMut,
{
    let mut unifont = Unifont::open();

    let largest_line_num_width = if line_nums {
        format!("{}", content.lines().count()).len() + 1
    } else {
        // We don't need it for rendering.
        // So pass default value.
        0
    };

    let style = highlight(" ")?[0].0;
    let initial_forground_color = Rgb([style.foreground.r, style.foreground.g, style.foreground.b]);

    // write the filename
    if show_filenames {
        // get background color
        // let style = highlight(" ")?[0].0;
        // println!("style: {:#?}", style);
        let mut background = None::<Rgb<u8>>;
        let background =
            background.get_or_insert_with(|| bg_color.to_rgb(style, file_index, color_modulation));

        // figure out where in the image to write
        let actual_line = line_num % total_line_count;
        let (cur_column_x_offset, cur_y) = calc_offsets(
            actual_line,
            lines_per_column,
            column_width * char_width,
            line_height,
        );

        // write filename on image
        // let char_color = Rgb([255, 255, 255]);
        let mut cur_line_x = 0;
        for chr in filepath.to_str().unwrap().chars() {
            if readable {
                put_readable_char_in_image(
                    chr,
                    &mut unifont,
                    cur_column_x_offset + cur_line_x * char_width,
                    cur_y,
                    img,
                    &background,
                    &initial_forground_color,
                    &mut cur_line_x,
                );
            } else {
                // Fill the char space with a solid color.
                let img_x = cur_column_x_offset + cur_line_x;
                put_solid_char_in_image(
                    img_x,
                    cur_y,
                    img,
                    initial_forground_color,
                    line_height,
                    char_width,
                    &mut cur_line_x,
                );
            }
        }

        // Fill the rest of the line with the background color.
        if readable {
            while cur_line_x < column_width {
                put_readable_char_in_image(
                    ' ',
                    &mut unifont,
                    cur_column_x_offset + cur_line_x * char_width,
                    cur_y,
                    img,
                    background,
                    background,
                    &mut cur_line_x,
                );
            }
        } else {
            while cur_line_x < column_width * char_width {
                // Fill the char space with a solid color.
                let img_x = cur_column_x_offset + cur_line_x;
                put_solid_char_in_image(
                    img_x,
                    cur_y,
                    img,
                    *background,
                    line_height,
                    char_width,
                    &mut cur_line_x,
                );
            }
        }

        line_num += 1;
    }

    // render all lines in `content` to image
    let mut longest_line_in_chars = 0;
    let mut background = None::<Rgb<u8>>;
    for (file_line_num, line) in content.as_bytes().lines_with_terminator().enumerate() {
        // make file_line_num that of the file.
        let file_line_num = file_line_num + 1;

        let (line, truncated_line) = {
            let line = line.to_str().expect("UTF-8 was source");
            let mut num_chars = 0;
            let mut chars = line.chars();
            let bytes_till_char_limit: usize = chars
                .by_ref()
                .take(column_width as usize)
                .map(|c| {
                    num_chars += 1;
                    c.len_utf8()
                })
                .sum();
            num_chars += chars.count();
            longest_line_in_chars = longest_line_in_chars.max(num_chars);
            let possibly_truncated_line = (num_chars >= column_width as usize)
                .then(|| &line[..bytes_till_char_limit])
                .unwrap_or(line);
            (
                if highlight_truncated_lines {
                    possibly_truncated_line
                } else {
                    line
                },
                possibly_truncated_line,
            )
        };

        let actual_line = line_num % total_line_count;
        let (cur_column_x_offset, cur_y) = calc_offsets(
            actual_line,
            lines_per_column,
            column_width * char_width,
            line_height,
        );
        let storage;
        let array_storage;

        let regions: &[_] = if line.len() > 1024 * 16 {
            array_storage = [(default_bg_color(background), truncated_line)];
            &array_storage
        } else {
            storage = highlight(line)?;
            &storage
        };
        let background = background
            .get_or_insert_with(|| bg_color.to_rgb(regions[0].0, file_index, color_modulation));
        let mut cur_line_x = 0;

        // draw file_line_num for this line
        if line_nums {
            let line_num_string =
                ensure_width(format!("{}", file_line_num), largest_line_num_width as u32) + " ";

            let file_line_num_char_color = initial_forground_color;
            // let file_line_num_char_color = Rgb([255, 255, 255]);
            for chr in line_num_string.chars() {
                if readable {
                    put_readable_char_in_image(
                        chr,
                        &mut unifont,
                        cur_column_x_offset + cur_line_x * char_width,
                        cur_y,
                        img,
                        background,
                        &file_line_num_char_color,
                        &mut cur_line_x,
                    );
                } else {
                    let color = if chr == ' ' {
                        *background
                    } else {
                        file_line_num_char_color
                    };
                    // Fill the char space with a solid color.
                    let img_x = cur_column_x_offset + cur_line_x;
                    put_solid_char_in_image(
                        img_x,
                        cur_y,
                        img,
                        color,
                        line_height,
                        char_width,
                        &mut cur_line_x,
                    );
                }
            }
        }

        // Draw the line on the image.
        for (style, region) in regions {
            if cur_line_x >= column_width * char_width {
                break;
            }
            if region.is_empty() {
                continue;
            }

            for chr in region.chars() {
                if cur_line_x >= column_width * char_width {
                    break;
                }

                let char_color: Rgb<u8> = match fg_color {
                    FgColor::Style => {
                        Rgb([style.foreground.r, style.foreground.g, style.foreground.b])
                    }
                    FgColor::StyleAsciiBrightness => {
                        let fg_byte = (chr as usize) & 0xff;
                        let boost = 2.4;
                        Rgb([
                            (((fg_byte * style.foreground.r as usize) as f32 / u16::MAX as f32)
                                * boost
                                * 256.0) as u8,
                            (((fg_byte * style.foreground.g as usize) as f32 / u16::MAX as f32)
                                * boost
                                * 256.0) as u8,
                            (((fg_byte * style.foreground.b as usize) as f32 / u16::MAX as f32)
                                * boost
                                * 256.0) as u8,
                        ])
                    }
                };

                if chr == ' ' || chr == '\n' || chr == '\r' {
                    if readable {
                        put_readable_char_in_image(
                            ' ',
                            &mut unifont,
                            cur_column_x_offset + cur_line_x * char_width,
                            cur_y,
                            img,
                            background,
                            &char_color,
                            &mut cur_line_x,
                        );
                    } else {
                        // Fill the char space with a solid color.
                        let img_x = cur_column_x_offset + cur_line_x;
                        put_solid_char_in_image(
                            img_x,
                            cur_y,
                            img,
                            *background,
                            line_height,
                            char_width,
                            &mut cur_line_x,
                        );
                    }
                } else if chr == '\t' {
                    let spaces_to_add = tab_spaces - (cur_line_x % tab_spaces);

                    for _ in 0..spaces_to_add {
                        if cur_line_x >= column_width * char_width {
                            break;
                        }

                        if readable {
                            put_readable_char_in_image(
                                ' ',
                                &mut unifont,
                                cur_column_x_offset + cur_line_x * char_width,
                                cur_y,
                                img,
                                background,
                                &char_color,
                                &mut cur_line_x,
                            );
                        } else {
                            // Fill the char space with a solid color.
                            let img_x = cur_column_x_offset + cur_line_x;
                            put_solid_char_in_image(
                                img_x,
                                cur_y,
                                img,
                                *background,
                                line_height,
                                char_width,
                                &mut cur_line_x,
                            );
                        }
                    }
                } else if readable {
                    put_readable_char_in_image(
                        chr,
                        &mut unifont,
                        cur_column_x_offset + cur_line_x * char_width,
                        cur_y,
                        img,
                        background,
                        &char_color,
                        &mut cur_line_x,
                    );
                } else {
                    // Fill the char space with a solid color.
                    let img_x = cur_column_x_offset + cur_line_x;
                    put_solid_char_in_image(
                        img_x,
                        cur_y,
                        img,
                        char_color,
                        line_height,
                        char_width,
                        &mut cur_line_x,
                    );
                }
            }
        }

        // Fill the rest of the line with the background color.
        if readable {
            while cur_line_x < column_width {
                put_readable_char_in_image(
                    ' ',
                    &mut unifont,
                    cur_column_x_offset + cur_line_x * char_width,
                    cur_y,
                    img,
                    background,
                    background,
                    &mut cur_line_x,
                );
            }
        } else {
            while cur_line_x < column_width * char_width {
                // Fill the char space with a solid color.
                let img_x = cur_column_x_offset + cur_line_x;
                put_solid_char_in_image(
                    img_x,
                    cur_y,
                    img,
                    *background,
                    line_height,
                    char_width,
                    &mut cur_line_x,
                );
            }
        }

        line_num += 1;
    }

    Ok(Outcome {
        longest_line_in_chars,
        background,
    })
}

fn put_readable_char_in_image<C>(
    chr: char,
    unifont: &mut Unifont,
    img_x: u32,
    img_y: u32,
    img: &mut ImageBuffer<Rgb<u8>, C>,
    background_color: &Rgb<u8>,
    text_color: &Rgb<u8>,
    cur_line_x: &mut u32,
) where
    C: Deref<Target = [u8]>,
    C: DerefMut,
{
    let bitmap = unifont.load_bitmap(chr.into());

    // get bitmap dimensions
    let char_height = 16;
    // let standard_char_width = 8;
    let char_width = if bitmap.is_wide() { 16 } else { 8 };

    // add bitmap to image
    for y in 0..char_height as usize {
        for x in 0..char_width {
            let pixel_x = img_x + x;
            let pixel_y = img_y + y as u32;

            // get pixel from bitmap
            let should_pixel = if bitmap.is_wide() {
                bitmap.get_bytes()[y * 2 + x as usize / 8] & (1 << (7 - x % 8)) != 0
            } else {
                bitmap.get_bytes()[y] & (1 << (7 - x)) != 0
            };

            // if not in image bounds
            if pixel_x >= img.width() || pixel_y >= img.height() {
                // println!(
                //     "Skipping pixel. out of bounds: {}, {}",
                //     img_x + x,
                //     img_y + y as u32
                // );
                continue;
            } else {
                // set pixel in image
                if should_pixel {
                    img.put_pixel(pixel_x, pixel_y, *text_color);
                } else {
                    img.put_pixel(pixel_x, pixel_y, *background_color);
                }
            }
        }
    }

    if bitmap.is_wide() {
        *cur_line_x += 2;
    } else {
        *cur_line_x += 1;
    }
}

/// Fill the char space with a solid color.
fn put_solid_char_in_image<C>(
    img_x: u32,
    img_y: u32,
    img: &mut ImageBuffer<Rgb<u8>, C>,
    color: Rgb<u8>,
    line_height: u32,
    char_width: u32,
    cur_line_x: &mut u32,
) where
    C: Deref<Target = [u8]>,
    C: DerefMut,
{
    // println!("placeing char");
    // Fill the char space with a solid color.
    for y_pos in img_y..img_y + line_height {
        // println!("placing y");
        for x_pos in img_x..img_x + char_width {
            // println!("placing x");
            img.put_pixel(x_pos, y_pos, color);
        }
    }
    *cur_line_x += char_width;
}

fn default_bg_color(background: Option<Rgb<u8>>) -> Style {
    Style {
        foreground: Color {
            r: 200,
            g: 200,
            b: 200,
            a: u8::MAX,
        },
        background: background
            .map(|c| Color {
                r: c.0[0],
                g: c.0[1],
                b: c.0[2],
                a: u8::MAX,
            })
            .unwrap_or(Color::BLACK),
        font_style: Default::default(),
    }
}