Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get the axis ranges from .glyphs files #42

Merged
merged 3 commits into from
Dec 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions fontir/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,6 @@ pub enum WorkError {
GlyphIrWorkError(String, String),
#[error("yaml error")]
YamlSerError(#[from] serde_yaml::Error),
#[error("No axes are defined")]
NoAxisDefinitions,
}
28 changes: 14 additions & 14 deletions fontir/src/ir.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
//! Serde types for font IR. See TODO:PublicLink.

use std::collections::{BTreeMap, HashMap};

use crate::error::Error;
use ordered_float::OrderedFloat;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};

///Global font info that cannot vary.
///
/// For example, upem, axis definitions, etc, as distinct from
/// metadata that varies across design space such as ascender/descender.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct StaticMetadata {}

use ordered_float::OrderedFloat;

use crate::error::Error;
pub struct StaticMetadata {
axes: Vec<Axis>,
glyph_order: Vec<String>,
}

#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct Axis {
pub name: String,
pub tag: String,
pub min: f32,
pub default: f32,
pub max: f32,
pub min: OrderedFloat<f32>,
pub default: OrderedFloat<f32>,
pub max: OrderedFloat<f32>,
pub hidden: bool,
}

Expand Down Expand Up @@ -132,9 +132,9 @@ mod tests {
Axis {
name: String::from("Weight"),
tag: String::from("wght"),
min: 100.,
default: 400.,
max: 900.,
min: 100_f32.into(),
default: 400_f32.into(),
max: 900_f32.into(),
hidden: false,
}
}
Expand Down
61 changes: 53 additions & 8 deletions glyphs-reader/src/font.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ pub struct Anchor {
#[derive(Debug, FromPlist, PartialEq, Eq, Hash)]
pub struct FontMaster {
pub id: String,
pub axes_values: Option<Vec<OrderedFloat<f64>>>,
#[rest]
pub other_stuff: BTreeMap<String, Plist>,
}
Expand Down Expand Up @@ -215,7 +216,6 @@ impl FromPlist for Affine {

impl FromPlist for Point {
fn from_plist(plist: Plist) -> Self {
eprintln!("{:?}", plist);
let raw = plist.as_str().unwrap();
let raw = &raw[1..raw.len() - 1];
let coords: Vec<f64> = raw.split(", ").map(|c| c.parse().unwrap()).collect();
Expand Down Expand Up @@ -325,6 +325,24 @@ fn custom_param<'a>(
None
}

fn glyphs_v2_field_name_and_default(nth_axis: usize) -> Result<(&'static str, f64), Error> {
// Per https://github.com/googlefonts/fontmake-rs/pull/42#pullrequestreview-1211619812
// the field to use is based on the order in axes NOT the tag.
// That is, whatever the first axis is, it's value is in the weightValue field. Long sigh.
// Defaults per https://github.com/googlefonts/fontmake-rs/pull/42#discussion_r1044415236.
Ok(match nth_axis {
0 => ("weightValue", 100_f64),
1 => ("widthValue", 100_f64),
2 => ("customValue", 0_f64),
_ => {
return Err(Error::StructuralError(format!(
"We don't know what field to use for axis {}",
nth_axis
)))
}
})
}

impl Font {
fn parse_codepoints(&mut self, radix: u32) {
for glyph in self.glyphs.iter_mut() {
Expand Down Expand Up @@ -391,6 +409,37 @@ impl Font {
});
}

if axes.len() > 3 {
return Err(Error::StructuralError(
"We only understand 0..3 axes for Glyphs v2".into(),
));
}

// v2 stores values for axes in specific fields, find them and put them into place
// "Axis position related properties (e.g. weightValue, widthValue, customValue) have been replaced by the axesValues list which is indexed in parallel with the toplevel axes list."
for master in self.font_master.iter_mut() {
let mut axis_values = Vec::new();
for idx in 0..axes.len() {
// Per https://github.com/googlefonts/fontmake-rs/pull/42#pullrequestreview-1211619812
// the field to use is based on the order in axes NOT the tag.
// That is, whatever the first axis is, it's value is in the weightValue field. Long sigh.
let (field_name, default_value) = glyphs_v2_field_name_and_default(idx)?;
let value = master
.other_stuff
.remove(field_name)
.unwrap_or_else(|| Plist::Float(default_value.into()))
.as_f64()
.ok_or_else(|| {
Error::StructuralError(format!(
"Invalid '{}' in\n{:#?}",
field_name, master.other_stuff
))
})?;
axis_values.push(value.into());
}
master.axes_values = Some(axis_values);
}

if custom_params(&mut self.other_stuff).map_or(false, |d| d.is_empty()) {
self.other_stuff.remove("customParameters");
}
Expand Down Expand Up @@ -489,14 +538,10 @@ impl Font {

fn v2_to_v3_weight(&mut self) -> Result<(), Error> {
for master in self.font_master.iter_mut() {
let Some(Plist::Integer(wght)) = master.other_stuff.remove("weightValue") else {
// Don't remove weightValue, we need it to understand axes
let Some(Plist::Integer(..)) = master.other_stuff.get("weightValue") else {
continue;
};
master.other_stuff.insert(
"axesValues".into(),
Plist::Array(vec![Plist::Integer(wght)]),
);

let name = match master.other_stuff.remove("weight") {
Some(Plist::String(name)) => name,
_ => String::from("Regular"), // Missing = default = Regular per @anthrotype
Expand All @@ -510,8 +555,8 @@ impl Font {

/// `<See https://github.com/schriftgestalt/GlyphsSDK/blob/Glyphs3/GlyphsFileFormat/GlyphsFileFormatv3.md#differences-between-version-2>`
fn v2_to_v3(&mut self) -> Result<(), Error> {
self.v2_to_v3_axes()?;
self.v2_to_v3_weight()?;
self.v2_to_v3_axes()?;
self.v2_to_v3_metrics()?;
self.v2_to_v3_shapes()?;
Ok(())
Expand Down
18 changes: 12 additions & 6 deletions ufo2fontir/src/toir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,15 @@ fn to_ir_axis(axis: designspace::Axis) -> ir::Axis {
ir::Axis {
name: axis.name,
tag: axis.tag,
min: axis.minimum.expect("Discrete axes not supported yet"),
default: axis.default,
max: axis.maximum.expect("Discrete axes not supported yet"),
min: axis
.minimum
.expect("Discrete axes not supported yet")
.into(),
default: axis.default.into(),
max: axis
.maximum
.expect("Discrete axes not supported yet")
.into(),
hidden: axis.hidden,
}
}
Expand Down Expand Up @@ -110,9 +116,9 @@ mod tests {
vec![ir::Axis {
name: "Weight".to_string(),
tag: "wght".to_string(),
min: 400.,
default: 400.,
max: 700.,
min: 400_f32.into(),
default: 400_f32.into(),
max: 700_f32.into(),
hidden: false
}],
designspace_to_ir(ds).unwrap()
Expand Down