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
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, Read};
use std::path::Path;

use error::ParseError;

pub mod character;
pub mod error;
pub mod header;
pub mod result;
pub mod subcharacter;
mod utils;

use crate::result::Result;

const DEUTSCH_CODE_POINTS: [i32; 7] = [196, 214, 220, 228, 246, 252, 223];

const STANDARD_FONT: &'static [u8] = include_bytes!("../fonts/plain/standard.flf");

pub use crate::{
    character::FIGcharacter,
    header::{Header, Layout, PrintDirection},
    subcharacter::SubCharacter,
};

/// FIGfont reader and parser.
#[derive(Debug)]
pub struct FIGfont {
    header: Header,
    characters: HashMap<i32, FIGcharacter>,
}

impl FIGfont {
    /// Read and parse a FIGfont from a path. It can be zipped if you have zip
    /// feature enabled.
    pub fn load_from<P: AsRef<Path>>(path: P) -> Result<FIGfont> {
        load_from(path)
    }

    /// Read and parse a FIGfont from a impl Read.
    pub fn read_from<R: Read>(reader: R) -> Result<FIGfont> {
        parse(reader)
    }

    /// Get the standard FIGfont. (hardcoded)
    pub fn standard() -> Result<FIGfont> {
        Self::read_from(STANDARD_FONT)
    }

    /// Get the current FIGfont's header.
    pub fn header(&self) -> &Header {
        &self.header
    }

    /// Get the FIGcharacter for the `code` character.
    pub fn get(&self, code: i32) -> &FIGcharacter {
        self.characters
            .get(&code)
            .unwrap_or_else(|| self.characters.get(&126i32).unwrap())
    }
}

fn parse<R: Read>(reader: R) -> Result<FIGfont> {
    let mut bread /* mlmlmlml */ = BufReader::new(reader);

    let header = Header::parse(&mut bread)?;

    let mut characters = HashMap::new();

    for codepoint in 32..127 {
        characters.insert(codepoint, FIGcharacter::parse(&mut bread, &header)?);
    }

    for codepoint in DEUTSCH_CODE_POINTS.iter() {
        let codepoint = *codepoint;

        characters.insert(codepoint, FIGcharacter::parse(&mut bread, &header)?);
    }

    let mut cnt = 0;
    while bread.fill_buf()?.len() > 0 {
        let (codepoint, character) = FIGcharacter::parse_with_codetag(&mut bread, &header)?;
        characters.insert(codepoint, character);
        cnt += 1;
    }

    match header.codetag_count() {
        Some(expected_cnt) => {
            if expected_cnt != cnt {
                return Err(ParseError::InvalidFont.into());
            }
        }
        None => (),
    }

    Ok(FIGfont { header, characters })
}

#[cfg(feature = "zip")]
fn load_from_zip<P: AsRef<Path>>(path: P) -> Result<FIGfont> {
    use crate::error::Error;
    use zip::ZipArchive;

    let mut zip = ZipArchive::new(File::open(path.as_ref())?)?;

    let file_name = path
        .as_ref()
        .file_name()
        .ok_or::<Error>(ParseError::InvalidFont.into())?
        .to_str()
        .ok_or::<Error>(ParseError::InvalidFont.into())?;

    let f = zip.by_name(file_name)?;

    parse(f)
}

#[cfg(feature = "zip")]
fn is_plain<P: AsRef<Path>>(path: P) -> Result<bool> {
    let mut f = File::open(path)?;
    let mut number: [u8; 5] = [0; 5];
    f.read(&mut number)?;
    Ok(&number == b"flf2a")
}

fn load_from<P: AsRef<Path>>(path: P) -> Result<FIGfont> {
    let path = path.as_ref();
    match path.extension() {
        Some(ext) => {
            if ext != "flf" {
                return Err(ParseError::InvalidExtension.into());
            }
        }
        None => {
            return Err(ParseError::InvalidExtension.into());
        }
    }

    #[cfg(feature = "zip")]
    {
        if is_plain(path)? {
            parse(File::open(path)?)
        } else {
            load_from_zip(path)
        }
    }

    #[cfg(not(feature = "zip"))]
    {
        parse(File::open(path)?)
    }
}

#[cfg(test)]
mod tests {
    use crate::FIGfont;

    #[test]
    fn default() {
        assert!(FIGfont::standard().is_ok());
    }
}