Skip to content

Commit

Permalink
Add components
Browse files Browse the repository at this point in the history
  • Loading branch information
ctrlcctrlv committed May 22, 2021
1 parent 08643ee commit 0a79aa7
Show file tree
Hide file tree
Showing 18 changed files with 1,258 additions and 683 deletions.
10 changes: 8 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@
name = "glifparser"
version = "0.0.0"
authors = ["Fredrick Brennan <[email protected]>"]
edition = "2018"

[dependencies]
xmltree = "0.10.1"
log = "0.4.11"
xmltree = "0.10.3"
log = "0.4"
kurbo = "0.8"
trees = "0.4"

# Our submodules
integer_or_float = { git = "https://github.com/MFEK/integer_or_float.rlib" }
15 changes: 10 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@ Skia-friendly points. A cubic B&eacute;zier spline has two handles, `a` and
with this. (A quadratic B&eacute;zier spline uses the same `Point` type but
will always have handle `b` set to `Handle::Colocated`.)

**NOTE**: This `.glif` parser is at the moment _unversioned_ (0.0.0); it has an
unstable API. Don't use it in your own projects yet; if you insist, tell Cargo
to use a `rev`. Right now it just panics instead of returning a `Result<Glif,
E>` type and has no `Error` enum, which will be fixed in the final
crates.io-friendly API.
Another difference is that it supports glyph components more fully, and allows
you to flatten the components to another Glif representing the outlines of all
the components, plus the outlines in the original glyph.

Yet a third difference is the support for private libraries, stored in
comments. This is for support of the `<MFEK>` comment.

Since this library considers .glif files as detached from .ufo files, its
approach is much different from Norad's as well. This is because MFEKglif, the
first software this was written for, is a detached UFO .glif editor.
30 changes: 30 additions & 0 deletions src/anchor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use std::fmt::Debug;

#[derive(Clone, Debug, PartialEq)]
pub struct Anchor {
pub x: f32,
pub y: f32,
pub class: String,
pub r#type: AnchorType,
}

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum AnchorType {
Undefined,
Mark,
Base,
MarkMark,
MarkBase,
} // Undefined used everywhere for now as getting type requires parsing OpenType features, which we will be using nom to do since I have experience w/it.

impl Anchor {
pub fn new() -> Anchor {
Anchor {
x: 0.,
y: 0.,
r#type: AnchorType::Undefined,
class: String::new(),
}
}
}

9 changes: 9 additions & 0 deletions src/codepoint.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
pub trait Codepoint {
fn display(&self) -> String;
}

impl Codepoint for char {
fn display(&self) -> String {
format!("{:x}", *self as u32)
}
}
223 changes: 223 additions & 0 deletions src/component.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
use crate::error::GlifParserError;
use crate::glif::{self, Glif};
use crate::point::{Handle, PointData, WhichHandle};
use crate::outline::Outline;

use integer_or_float::IntegerOrFloat;

#[allow(non_snake_case)] // to match UFO spec https://unifiedfontobject.org/versions/ufo3/glyphs/glif/#component
#[derive(Clone, Debug, PartialEq)]
pub struct GlifComponent {
pub base: String,
pub xScale: IntegerOrFloat,
pub xyScale: IntegerOrFloat,
pub yxScale: IntegerOrFloat,
pub yScale: IntegerOrFloat,
pub xOffset: IntegerOrFloat,
pub yOffset: IntegerOrFloat,
pub identifier: Option<String>
}

impl GlifComponent {
pub fn new() -> Self {
Self {
base: String::new(),
xScale: IntegerOrFloat::Integer(1),
xyScale: IntegerOrFloat::Integer(0),
yxScale: IntegerOrFloat::Integer(0),
yScale: IntegerOrFloat::Integer(1),
xOffset: IntegerOrFloat::Integer(0),
yOffset: IntegerOrFloat::Integer(0),
identifier: None
}
}
}

type ComponentMatrix = [IntegerOrFloat; 6];

impl GlifComponent {
fn matrix(&self) -> ComponentMatrix {
[self.xScale, self.xyScale, self.yxScale, self.yScale, self.xOffset, self.yOffset]
}
}

trait FromComponentMatrix {
fn from_component_matrix(cm: &ComponentMatrix) -> Self;
}

use kurbo::Affine;
impl FromComponentMatrix for Affine {
fn from_component_matrix(cm: &ComponentMatrix) -> Self {
Affine::new([cm[0].into(), cm[1].into(), cm[2].into(), cm[3].into(), cm[4].into(), cm[5].into()])
}
}

#[derive(Clone, Debug, PartialEq)]
pub struct Component<PD: PointData> {
pub glif: Glif<PD>,
pub matrix: Affine
}

impl<PD: PointData> Component<PD> {
pub fn new() -> Self {
Component {
glif: Glif::new(),
matrix: Affine::IDENTITY
}
}
}

use std::fs;
impl GlifComponent {
pub fn to_component_of<PD: PointData>(&self, glif: &Glif<PD>) -> Result<Component<PD>, GlifParserError> {
let gliffn = &glif.filename.as_ref().ok_or(GlifParserError::GlifFilenameNotSet(glif.name.clone()))?;

let mut ret = Component::new();
ret.matrix = Affine::from_component_matrix(&self.matrix());
ret.glif.name = self.base.clone();
let mut retglifname = gliffn.to_path_buf();
retglifname.set_file_name(ret.glif.name_to_filename());
let component_xml = fs::read_to_string(&retglifname).unwrap();
ret.glif.filename = Some(retglifname);
let newglif: Glif<PD> = glif::read(&component_xml)?;
ret.glif.components = newglif.components;
ret.glif.anchors = newglif.anchors;
ret.glif.outline = newglif.outline;
Ok(ret)
}

pub fn refers_to<PD: PointData>(&self, glif: &Glif<PD>) -> bool {
self.base == glif.name
}
}

use kurbo::Point as KurboPoint;
impl<PD: PointData> Glif<PD> {
/// Flatten a UFO .glif with components.
///
/// Can fail if the .glif's components form an infinite loop.
// How this works is we start at the bottom of the tree, take all of the Affine matrices which
// describe the transformation of the glyph's points, and continuously apply them until we run
// out of nodes of the tree. Finally, we set our outline to be the final transformed outline,
// and consider ourselves as no longer being made up of components.
pub fn flatten(mut self) -> Result<Self, GlifParserError> {
let components_r: Result<Forest<Component<PD>>, _> = (&self).into();
let components = components_r?;
let mut final_outline: Outline<PD> = Outline::new();

for mut component in components {
while let Some(last) = component.back_mut() {
let mut matrices = vec![];
matrices.push((*last).data().matrix);

// Climb the tree, building a Vec of matrices for this component
let mut pt = last.parent();
while let Some(parent) = pt {
matrices.push(parent.data().matrix);
pt = parent.parent();
}

match (*last).data().glif.outline {
Some(ref o) => {
let mut to_transform = o.clone();
for i in 0..to_transform.len() {
for j in 0..to_transform[i].len() {
let mut p = to_transform[i][j].clone();
let kbp = matrices.iter().fold(KurboPoint::new(p.x as f64, p.y as f64), |p, m| *m * p);
p.x = kbp.x as f32;
p.y = kbp.y as f32;

if p.a != Handle::Colocated {
let (ax, ay) = p.handle_or_colocated(WhichHandle::A, |f|f, |f|f);
let kbpa = matrices.iter().fold(KurboPoint::new(ax as f64, ay as f64), |p, m| *m * p);
p.a = Handle::At(kbpa.x as f32, kbpa.y as f32);
}

if p.b != Handle::Colocated {
let (bx, by) = p.handle_or_colocated(WhichHandle::B, |f|f, |f|f);
let kbpb = matrices.iter().fold(KurboPoint::new(bx as f64, by as f64), |p, m| *m * p);
p.b = Handle::At(kbpb.x as f32, kbpb.y as f32);
}

to_transform[i][j] = p;
}
}
final_outline.extend(to_transform);
},
None => {}
}

component.pop_back();
}
}

self.outline = Some(final_outline);

// If we were to leave this here, then API consumers would potentially draw component outlines on top of components.
self.components = vec![];

Ok(self)
}
}

use std::collections::HashSet;
use trees::{Forest, Tree};
// This impl builds up a forest of trees for a glyph's components. Imagine a hungarumlaut (˝).
//
// This character may be built of glyph components, as such:
//
// hungarumlaut
// / \
// / \
// grave grave
// | |
// acute acute
//
// This function will give you a Forest of both of the sub-trees. (Forest<Component>). The elements
// of a Forest are Tree<Component>. For safety reasons, this function cannot always return a
// Forest, however. Sometimes, .glif files can be malformed, containing components which refer to
// themselves, or to components higher up the tree. Therefore, the inner recursive function
// `component_to_tree` receives a Vec of `uniques`, calculated for each sub-tree, and also a global
// mutable `unique_found` flag, for the entire Forest.
//
// If a loop is found in the tree (for example, grave refers to grave), `unique_found` is set,
// poisoning the function, returning an error. unique_found is (String, String) for error formatting;
// however, should be considered basically equivalent to a boolean.
impl<PD: PointData> From<&Glif<PD>> for Result<Forest<Component<PD>>, GlifParserError> {
fn from(glif: &Glif<PD>) -> Self {
let mut unique_found = None;

fn component_to_tree<PD: PointData>(component: Component<PD>, glif: &Glif<PD>, uniques: &mut HashSet<String>, unique_found: &mut Option<(String, String)>) -> Result<Tree<Component<PD>>, GlifParserError> {
let mut tree = Tree::new(component.clone());
for gc in component.glif.components.iter() {
let component_inner = gc.to_component_of(glif)?;
if uniques.contains(&gc.base) {
return {
*unique_found = Some((component.glif.name.clone(), gc.base.clone()));
Ok(tree)
}
}
uniques.insert(gc.base.clone());
tree.push_back(component_to_tree(component_inner, glif, uniques, unique_found)?);
}
Ok(tree)
}

let mut forest = Forest::new();
let cs: Vec<_> = glif.components.iter().map(|gc| {
let mut uniques = HashSet::new();
uniques.insert(glif.name.clone());
uniques.insert(gc.base.clone());
component_to_tree(gc.to_component_of(glif).unwrap(), glif, &mut uniques, &mut unique_found).unwrap()
}).collect();

for c in cs {
forest.push_back(c);
}

match unique_found {
Some((base, unique)) => {Err(GlifParserError::GlifComponentsCyclical(format!("in glif {}, {} refers to {}", &glif.name, base, unique)))},
None => Ok(forest)
}
}
}
71 changes: 71 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
use std::fmt::{Formatter, Display};
use std::error::Error;
use std::string;

use xmltree::{ParseError, Error as XMLTreeError};

#[derive(Debug, Clone)]
pub enum GlifParserError {
/// Glif filename not set
GlifFilenameNotSet(String),
/// Glif filename doesn't match name in XML
GlifFilenameInsane(String),
/// Components of the glyph form a loop
GlifComponentsCyclical(String),
/// Glif isn't UTF8
GlifNotUtf8(String),
/// The XML making up the glif is invalid
XmlParseError(String),
/// Failures when writing glif XML
XmlWriteError(String),
/// The XML is valid, but doesn't meet the UFO .glif spec
GlifInputError(String),
}

impl Display for GlifParserError {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "glifparser error: {}", match self {
Self::GlifFilenameNotSet(s) => {
format!("Glyph filename not set: {}", &s)
},
Self::GlifFilenameInsane(s) => {
format!("Glyph filename not sane: {}", &s)
},
Self::GlifNotUtf8(_) => {
format!("Glyph not utf-8")
},
Self::GlifComponentsCyclical(s) => {
format!("Glyph components are cyclical: {}", &s)
},
Self::XmlParseError(s) | Self::XmlWriteError(s) => {
format!("XML error: {}", &s)
},
Self::GlifInputError(s) => {
format!("Glif format spec error: {}", &s)
},
})
}
}

// the parsing function in read_ufo_glif can only return this error type
impl From<ParseError> for GlifParserError {
fn from(e: ParseError) -> Self {
Self::XmlParseError(format!("{}", e))
}
}

// . . . therefore it's OK to consider this a write-time error type
impl From<XMLTreeError> for GlifParserError {
fn from(e: XMLTreeError) -> Self {
Self::XmlWriteError(format!("{}", e))
}
}

impl From<string::FromUtf8Error> for GlifParserError {
fn from(_: string::FromUtf8Error) -> Self {
Self::GlifNotUtf8("".to_string())
}
}


impl Error for GlifParserError {}
Loading

0 comments on commit 0a79aa7

Please sign in to comment.