text-image 0.2.0

A proc-macro to generate raw image from text and a font file, for embedded-graphics.
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
#![feature(iter_array_chunks)]

use ab_glyph::{Font, FontRef, PxScale, ScaleFont};
use image::{GenericImageView, GrayImage, Luma, Rgb};
use imageproc::drawing::{draw_text_mut, text_size};
use proc_macro::TokenStream;
use quote::quote;
use syn::parse::{Parse, ParseStream, Result};
use syn::{parse_macro_input, Ident, Lit, LitByteStr, Token};

#[derive(Debug)]
struct TextImageOptions {
    text: String,
    font: String,
    font_size: f32,
    inverse: bool,
    line_spacing: i32,
    // 2, 4, or 8
    gray_depth: i32,
}

impl Parse for TextImageOptions {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut opts = TextImageOptions {
            text: "".to_string(),
            font: "".to_string(),
            font_size: 16.0,
            inverse: false,
            line_spacing: 0,
            gray_depth: 1,
        };

        loop {
            let name: Ident = input.parse()?;

            match &*name.to_string() {
                "text" => {
                    input.parse::<Token![=]>()?;
                    let text: Lit = input.parse()?;

                    let text = if let Lit::Str(text) = &text {
                        text.value()
                    } else {
                        return Err(syn::Error::new_spanned(text, "expected a string literal"));
                    };

                    opts.text = text;
                }
                "font" => {
                    input.parse::<Token![=]>()?;
                    let font: Lit = input.parse()?;

                    let font = if let Lit::Str(font) = &font {
                        font.value()
                    } else {
                        return Err(syn::Error::new_spanned(font, "expected a string literal"));
                    };

                    opts.font = font;
                }
                "font_size" => {
                    input.parse::<Token![=]>()?;
                    let font_size: Lit = input.parse()?;

                    let font_size = if let Lit::Float(font_size) = &font_size {
                        font_size.base10_parse()?
                    } else {
                        return Err(syn::Error::new_spanned(
                            font_size,
                            "expected a float literal",
                        ));
                    };

                    opts.font_size = font_size;
                }
                "line_spacing" => {
                    input.parse::<Token![=]>()?;
                    let line_spacing: Lit = input.parse()?;

                    let line_spacing = if let Lit::Int(line_spacing) = &line_spacing {
                        line_spacing.base10_parse()?
                    } else {
                        return Err(syn::Error::new_spanned(
                            line_spacing,
                            "expected a integer literal",
                        ));
                    };

                    opts.line_spacing = line_spacing;
                }
                "inverse" => {
                    opts.inverse = true;
                }
                "Gray2" => {
                    opts.gray_depth = 2;
                }
                "Gray4" => {
                    opts.gray_depth = 4;
                }
                "Gray8" => {
                    opts.gray_depth = 8;
                }
                _ => {
                    return Err(syn::Error::new_spanned(
                        name,
                        "expected `text`, `font`, `font_size` or `inverse`",
                    ));
                }
            }

            let _ = input.parse::<Token![,]>();
            if input.is_empty() {
                break;
            }
        }

        // check required
        if opts.text.is_empty() {
            return Err(syn::Error::new_spanned(
                "text",
                "required option `text` is missing",
            ));
        }
        if opts.font.is_empty() {
            return Err(syn::Error::new_spanned(
                "font",
                "required option `font` is missing",
            ));
        }

        Ok(opts)
    }
}

/// Generate a text image.
///
/// Usage:
///
/// ```rust
/// use text_image::text_image;
///
/// use embedded_graphics::{image::ImageRaw, pixelcolor::Gray8};
///
/// fn main() {
///   let (w, h, raw) = text_image!(
///     text = "Hello, world!哈哈这样也行",
///     font = "LXGWWenKaiScreen.ttf",
///     font_size = 48.0,
///     inverse,
///     Gray4,
///   );
///   let raw_image = ImageRaw::<Gray8>::new(raw, w);
/// }
///
/// ````
#[proc_macro]
pub fn text_image(input: TokenStream) -> TokenStream {
    let opts = parse_macro_input!(input as TextImageOptions);
    println!("text_image: {:#?}", opts);

    let font_raw = std::fs::read(opts.font).expect("Can not read font file");
    let font = FontRef::try_from_slice(&font_raw).expect("Can not load font");

    let scale = PxScale {
        x: opts.font_size,
        y: opts.font_size,
    };

    // let metric = font.v_metrics(scale);
    let sfont = font.as_scaled(scale);
    let line_height = (sfont.ascent() - sfont.descent() + sfont.line_gap())
        .abs()
        .ceil() as i32;

    let mut h = 0;
    let mut w = 0;
    let mut lines = 0;

    for line in opts.text.lines() {
        let (lw, _lh) = text_size(scale, &font, line);
        // println!("lh => {}", _lh);
        w = w.max(lw);
        h += line_height;
        lines += 1;
    }
    w += 1;
    h += opts.line_spacing as i32 * (lines - 1);

    // align to byte
    if w % 8 != 0 {
        w = (w / 8 + 1) * 8;
    }
    println!("text_image: result size {}x{}, {} lines", w, h, lines);

    let mut image: image::ImageBuffer<Luma<u8>, Vec<u8>> = GrayImage::new(w as _, h as _);

    let mut luma = 0xFF;
    if opts.inverse {
        image.fill(0xFF);
        luma = 0x00;
    }

    for (i, line) in opts.text.lines().enumerate() {
        // 1 px offset for blending
        draw_text_mut(
            &mut image,
            Luma([luma]),
            1,
            (line_height + opts.line_spacing) * (i as i32) - 1,
            scale,
            &font,
            &line,
        );
    }

    let raw = image.into_raw();

    // convert depth
    let raw: Vec<u8> = match opts.gray_depth {
        8 => raw,
        4 => raw
            .chunks(2)
            .map(|ch| (ch[1] >> 4) | (ch[0] & 0xF0))
            .collect(),
        2 => {
            let mut ret = Vec::with_capacity(raw.len() / 4);
            for ch in raw.chunks(4) {
                ret.push(
                    (ch[3] >> 6) | ((ch[2] >> 4) & 0x0C) | ((ch[1] >> 2) & 0x30) | (ch[0] & 0xC0),
                );
            }
            ret
        }
        1 => {
            let mut ret = Vec::with_capacity(raw.len() / 8);
            for ch in raw.chunks(8) {
                ret.push(
                    (ch[7] >> 7)
                        | ((ch[6] >> 6) & 0x02)
                        | ((ch[5] >> 5) & 0x04)
                        | ((ch[4] >> 4) & 0x08)
                        | ((ch[3] >> 3) & 0x10)
                        | ((ch[2] >> 2) & 0x20)
                        | ((ch[1] >> 1) & 0x40)
                        | (ch[0] & 0x80),
                );
            }
            ret
        }
        _ => unreachable!(),
    };

    // convert from 8-bit grayscale to 1-bit compressed bytes

    let raw_bytes = Lit::ByteStr(LitByteStr::new(&raw, proc_macro2::Span::call_site()));

    let w = w as u32;
    let h = h as u32;

    // TODO: binary support https://github.com/image-rs/image/issues/640

    let expanded = quote! {
        (#w, #h, #raw_bytes)
    };

    TokenStream::from(expanded)
}

#[derive(Debug)]
struct ImageOptions {
    image: String,
    /// index of the channel to use
    channel: u8,
    gray_depth: i32,
}

impl Parse for ImageOptions {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut opts = ImageOptions {
            image: "".to_string(),
            channel: 0,
            gray_depth: 1,
        };

        let name: Lit = input.parse()?;

        let image = if let Lit::Str(image) = &name {
            image.value()
        } else {
            return Err(syn::Error::new_spanned(
                "image",
                "expected a string literal",
            ));
        };
        opts.image = image;

        while let Ok(_) = input.parse::<Token![,]>() {
            if input.is_empty() {
                break;
            }

            let name: Ident = input.parse()?;

            match &*name.to_string() {
                "channel" => {
                    input.parse::<Token![=]>()?;
                    let channel: Lit = input.parse()?;

                    let channel = if let Lit::Int(channel) = &channel {
                        channel.base10_parse()?
                    } else {
                        return Err(syn::Error::new_spanned(
                            channel,
                            "expected a integer literal",
                        ));
                    };

                    opts.channel = channel;
                }
                "Gray2" => {
                    opts.gray_depth = 2;
                }
                "Gray4" => {
                    opts.gray_depth = 4;
                }
                "Gray8" => {
                    opts.gray_depth = 8;
                }
                _ => {
                    return Err(syn::Error::new_spanned(
                        name,
                        "expected `palette` or `channel`",
                    ));
                }
            }
        }

        Ok(opts)
    }
}

struct BWR;

impl BWR {
    fn map_palette(&self, c: &Rgb<u8>) -> u8 {
        let palette = vec![0x000000, 0xFFFFFF, 0xFF0000];
        let mut min = 0;
        let mut min_dist = 0x7FFF_FFFF;
        for (i, p) in palette.iter().enumerate() {
            let dist = (c.0[0] as i32 - (p >> 16) as i32).pow(2)
                + (c.0[1] as i32 - ((p >> 8) & 0xFF) as i32).pow(2)
                + (c.0[2] as i32 - (p & 0xFF) as i32).pow(2);
            if dist < min_dist {
                min_dist = dist;
                min = i;
            }
        }
        min as u8
    }
}

impl image::imageops::colorops::ColorMap for BWR {
    type Color = Rgb<u8>;

    fn index_of(&self, color: &Self::Color) -> usize {
        let palette = vec![0x000000, 0xFFFFFF, 0xFF0000];
        let mut min = 0;
        let mut min_dist = 0x7FFF_FFFF;
        for (i, p) in palette.iter().enumerate() {
            let dist = (color.0[0] as i32 - (p >> 16) as i32).pow(2)
                + (color.0[1] as i32 - ((p >> 8) & 0xFF) as i32).pow(2)
                + (color.0[2] as i32 - (p & 0xFF) as i32).pow(2);
            if dist < min_dist {
                min_dist = dist;
                min = i;
            }
        }
        min
    }
    fn map_color(&self, color: &mut Self::Color) {
        let idx = self.index_of(color);
        let palette = [
            Rgb([0x00, 0x00, 0x00]),
            Rgb([0xFF, 0xFF, 0xFF]),
            Rgb([0xFF, 0x00, 0x00]),
        ];
        *color = palette[idx];
    }
}

#[proc_macro]
pub fn monochrome_image(input: TokenStream) -> TokenStream {
    let opts = parse_macro_input!(input as ImageOptions);
    println!("text_image: {:#?}", opts);

    let im = image::open(&opts.image).expect("Can not read image file");
    let (mut w, h) = im.dimensions();

    let mut im = im.to_rgb8();

    // Floyd-Steinberg dithering
    image::imageops::colorops::dither(&mut im, &BWR);

    let mut ret = vec![];

    // convert each 8 pixel to a compressed byte
    for (y, row) in im.enumerate_rows() {
        let mut n = 0u8;
        for (x, (_, _, px)) in row.enumerate() {
            let ix = BWR.map_palette(px);
            if ix == opts.channel {
                n |= 1 << (7 - x % 8);
            }
            if x % 8 == 7 {
                ret.push(n);
                n = 0;
            }
        }
        if w % 8 != 0 {
            ret.push(n);
        }
    }

    w = (w / 8 + if w % 8 != 0 { 1 } else { 0 }) * 8;

    let raw_bytes = Lit::ByteStr(LitByteStr::new(&ret, proc_macro2::Span::call_site()));

    let expanded = quote! {
        (#w, #h, #raw_bytes)
    };

    TokenStream::from(expanded)
}

struct BWYR;

impl BWYR {
    fn map_palette(&self, c: &Rgb<u8>) -> u8 {
        let palette = vec![0x000000, 0xFFFFFF, 0xFF0000, 0xFFFF00];
        let mut min = 0;
        let mut min_dist = 0x7FFF_FFFF;
        for (i, p) in palette.iter().enumerate() {
            let dist = (c.0[0] as i32 - (p >> 16) as i32).pow(2)
                + (c.0[1] as i32 - ((p >> 8) & 0xFF) as i32).pow(2)
                + (c.0[2] as i32 - (p & 0xFF) as i32).pow(2);
            if dist < min_dist {
                min_dist = dist;
                min = i;
            }
        }
        min as u8
    }
}

impl image::imageops::colorops::ColorMap for BWYR {
    type Color = Rgb<u8>;

    fn index_of(&self, color: &Self::Color) -> usize {
        let palette = vec![0x000000, 0xFFFFFF, 0xFFFF00, 0xFF0000];
        let mut min = 0;
        let mut min_dist = 0x7FFF_FFFF;
        for (i, p) in palette.iter().enumerate() {
            let dist = (color.0[0] as i32 - (p >> 16) as i32).abs()
                + (color.0[1] as i32 - ((p >> 8) & 0xFF) as i32).abs()
                + (color.0[2] as i32 - (p & 0xFF) as i32).abs();
            if dist < min_dist {
                min_dist = dist;
                min = i;
            }
        }
        min
    }
    fn map_color(&self, color: &mut Self::Color) {
        let idx = self.index_of(color);
        let palette = [
            Rgb([0x00, 0x00, 0x00]),
            Rgb([0xFF, 0xFF, 0xFF]),
            Rgb([0xFF, 0x00, 0x00]),
            Rgb([0xFF, 0xFF, 0x00]),
        ];
        *color = palette[idx];
    }
}

// for BWRY palette
#[proc_macro]
pub fn quadcolor_image(input: TokenStream) -> TokenStream {
    let opts = parse_macro_input!(input as ImageOptions);
    println!("text_image: {:#?}", opts);

    let im = image::open(&opts.image).expect("Can not read image file");
    let (w, h) = im.dimensions();

    let mut im = im.to_rgb8();

    // Floyd-Steinberg dithering
    image::imageops::colorops::dither(&mut im, &BWYR);

    let mut ret = vec![];

    for pixels in im.pixels().array_chunks::<4>() {
        let mut n = 0u8;
        for pix in pixels {
            let ix = BWYR.map_palette(pix);
            if ix != 0 && ix != 1 && ix != 2 {
                println!("ix => {}", ix);
            }
            n = (n << 2) | (ix & 0b11);
        }
        ret.push(n);
    }

    let raw_bytes = Lit::ByteStr(LitByteStr::new(&ret, proc_macro2::Span::call_site()));

    let expanded = quote! {
        (#w, #h, #raw_bytes)
    };

    TokenStream::from(expanded)
}

/// Load a image and compress it to grayscale image of specified depth.
///
/// ```
/// let (w, h, img_raw) = text_image::gray_image!("pattern128x128.png", Gray4);
/// let image: ImageRaw<Gray4, LittleEndian> = ImageRaw::new(img_raw, w);
/// image.draw(&mut fb).unwrap();
/// ```
#[proc_macro]
pub fn gray_image(input: TokenStream) -> TokenStream {
    let opts = parse_macro_input!(input as ImageOptions);
    println!("text_image: {:#?}", opts);

    let im = image::open(&opts.image).expect("Can not read image file");
    let (w, h) = im.dimensions();

    let im = im.to_luma8();

    let mut ret = vec![];

    let steps_per_pixel = 8 / opts.gray_depth;
    let shift_per_pixel = match opts.gray_depth {
        8 => 0,
        4 => 4,
        2 => 6,
        1 => 7,
        _ => unreachable!(),
    };

    let mut c = 0;
    let mut n = 0u8;
    for pixel in im.pixels() {
        let val = pixel.0[0];

        n = (n << opts.gray_depth) | (val >> shift_per_pixel);
        c += 1;

        if c == steps_per_pixel {
            ret.push(n);
            n = 0;
            c = 0;
        }
    }

    let raw_bytes = Lit::ByteStr(LitByteStr::new(&ret, proc_macro2::Span::call_site()));

    let expanded = quote! {
        (#w, #h, #raw_bytes)
    };

    TokenStream::from(expanded)
}