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
use std::ffi::CString;
use std::path::Path;

use crate::c;

/// The Rust handle for LedFont.
pub struct LedFont {
    pub(crate) handle: *mut c::LedFont,
}

impl LedFont {
    /// Creates a new `LedFont` instance with the given bdf filepath, if it exists.
    pub fn new(bdf_file: &Path) -> Result<LedFont, &'static str> {
        let string = match bdf_file.to_str() {
            Some(s) => s,
            None => return Err("Couldn't convert path to str"),
        };
        let cstring = CString::new(string).unwrap();

        let handle = unsafe { c::load_font(cstring.as_ptr()) };

        if handle.is_null() {
            Err("Couldn't load font")
        } else {
            Ok(LedFont { handle })
        }
    }
}

impl Drop for LedFont {
    fn drop(&mut self) {
        unsafe { c::delete_font(self.handle) }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{LedColor, LedMatrix};
    use std::{thread, time};

    #[test]
    fn draw_text() {
        let matrix = LedMatrix::new(None, None).unwrap();
        let mut canvas = matrix.canvas();
        let font = LedFont::new(Path::new("/usr/share/fonts/misc/10x20.bdf")).unwrap();
        let color = LedColor {
            red: 0,
            green: 127,
            blue: 0,
        };
        let (width, height) = canvas.canvas_size();
        let text_width = 10 * 9;
        let baseline = height / 2;

        canvas = matrix.offscreen_canvas();
        for x in 0..(2 * width) {
            let x = x % (10 * 9);
            canvas.clear();
            canvas.draw_text(&font, "Mah boy! ", x, baseline, &color, 0, false);
            canvas.draw_text(
                &font,
                "Mah boy! ",
                x - text_width,
                baseline,
                &color,
                0,
                false,
            );
            canvas.draw_text(
                &font,
                "Mah boy! ",
                x + text_width,
                baseline,
                &color,
                0,
                false,
            );
            canvas = matrix.swap(canvas);
            thread::sleep(time::Duration::new(0, 50000000));
        }
    }
}