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

Use fontations Glyph enum #382

Merged
merged 2 commits into from
Aug 10, 2023
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
22 changes: 12 additions & 10 deletions fontbe/src/glyphs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use read_fonts::{
};
use write_fonts::{
tables::{
glyf::{Bbox, Component, ComponentFlags, CompositeGlyph, SimpleGlyph},
glyf::{Bbox, Component, ComponentFlags, CompositeGlyph, Glyph as RawGlyph, SimpleGlyph},
variations::iup_delta_optimize,
},
OtRound,
Expand Down Expand Up @@ -281,7 +281,7 @@ impl Work<Context, AnyWorkId, Error> for GlyphWork {
let composite = create_composite(context, ir_glyph, default_location, &components)?;
context
.glyphs
.set_unconditionally(Glyph::new_composite(name.clone(), composite));
.set_unconditionally(Glyph::new(name.clone(), composite));
let point_seqs = point_seqs_for_composite_glyph(ir_glyph);
(name, point_seqs, Vec::new())
}
Expand Down Expand Up @@ -309,7 +309,7 @@ impl Work<Context, AnyWorkId, Error> for GlyphWork {
};
context
.glyphs
.set_unconditionally(Glyph::new_simple(name.clone(), base_glyph.clone()));
.set_unconditionally(Glyph::new(name.clone(), base_glyph.clone()));

let mut contour_end = 0;
let mut contour_ends = Vec::with_capacity(base_glyph.contours().len());
Expand Down Expand Up @@ -661,7 +661,7 @@ fn compute_composite_bboxes(context: &Context) -> Result<(), Error> {
let mut bbox_acquired: HashMap<GlyphName, Rect> = HashMap::new();
let mut composites = glyphs
.values()
.filter(|glyph| matches!(glyph.as_ref(), Glyph::Composite(..)))
.filter(|glyph| !glyph.is_simple())
.collect::<Vec<_>>();

trace!("Resolve bbox for {} composites", composites.len());
Expand All @@ -670,9 +670,11 @@ fn compute_composite_bboxes(context: &Context) -> Result<(), Error> {

// Hopefully we can figure out some of those bboxes!
for composite in composites.iter() {
let Glyph::Composite(glyph_name, composite) = composite.as_ref() else {
let glyph_name = &composite.name;
let RawGlyph::Composite(composite) = &composite.data else {
panic!("Only composites should be in our vector of composites!!");
};

let mut missing_boxes = false;
let boxes: Vec<_> = composite
.components()
Expand All @@ -686,9 +688,9 @@ fn compute_composite_bboxes(context: &Context) -> Result<(), Error> {
glyphs
.get(ref_glyph_name)
.map(|g| g.as_ref().clone())
.and_then(|g| match g {
Glyph::Composite(..) => None,
Glyph::Simple(_, simple_glyph) => Some(bbox2rect(simple_glyph.bbox)),
.and_then(|g| match &g.data {
RawGlyph::Composite(..) => None,
RawGlyph::Simple(simple_glyph) => Some(bbox2rect(simple_glyph.bbox)),
})
});
if bbox.is_none() {
Expand All @@ -715,7 +717,7 @@ fn compute_composite_bboxes(context: &Context) -> Result<(), Error> {
}

// Kerplode if we didn't make any progress this spin
composites.retain(|composite| !bbox_acquired.contains_key(composite.glyph_name()));
composites.retain(|composite| !bbox_acquired.contains_key(&composite.name));
if pending == composites.len() {
panic!("Unable to make progress on composite bbox, stuck at\n{composites:?}");
}
Expand All @@ -727,7 +729,7 @@ fn compute_composite_bboxes(context: &Context) -> Result<(), Error> {
.glyphs
.get(&WorkId::GlyfFragment(glyph_name.clone()).into()))
.clone();
let Glyph::Composite(_, composite) = &mut glyph else {
let RawGlyph::Composite(composite) = &mut glyph.data else {
panic!("{glyph_name} is not a composite; we shouldn't be trying to update it");
};
composite.bbox = bbox.into(); // delay conversion to Bbox to avoid accumulating rounding error
Expand Down
18 changes: 9 additions & 9 deletions fontbe/src/metrics_and_limits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use read_fonts::types::FWord;
use write_fonts::{
dump_table,
tables::{
glyf::{Bbox, Contour},
glyf::{Bbox, Contour, Glyph as RawGlyph},
hhea::Hhea,
hmtx::Hmtx,
maxp::Maxp,
Expand Down Expand Up @@ -84,8 +84,8 @@ impl FontLimits {
fn update(&mut self, id: GlyphId, advance: u16, glyph: &Glyph) {
// min side bearings are only for non-empty glyphs
// we will presume only simple glyphs with no contours are empty
if !glyph.is_empty() {
let bbox = glyph.bbox();
if !glyph.data.is_empty() {
let bbox = glyph.data.bbox();
let left_side_bearing = bbox.x_min;
// aw - (lsb + xMax - xMin) ... but if lsb == xMin then just advance - xMax?
let right_side_bearing: i16 = match advance as i32 - bbox.x_max as i32 {
Expand All @@ -108,11 +108,11 @@ impl FontLimits {
self.advance_width_max = max(self.advance_width_max, advance);
}

let bbox = glyph.bbox();
let bbox = glyph.data.bbox();
self.bbox = self.bbox.map(|b| b.union(bbox)).or(Some(bbox));

match glyph {
Glyph::Simple(_, simple) => {
match &glyph.data {
RawGlyph::Simple(simple) => {
let num_points = simple.contours().iter().map(Contour::len).sum::<usize>() as u16;
let num_contours = simple.contours().len() as u16;
self.max_points = max(self.max_points, num_points);
Expand All @@ -129,7 +129,7 @@ impl FontLimits {
},
)
}
Glyph::Composite(_, composite) => {
RawGlyph::Composite(composite) => {
let num_components = composite.components().len() as u16;
self.max_component_elements = max(self.max_component_elements, num_components);
let components = Some(composite.components().iter().map(|c| c.glyph).collect());
Expand Down Expand Up @@ -262,7 +262,7 @@ impl Work<Context, AnyWorkId, Error> for MetricAndLimitWork {
glyph_limits.update(gid, advance, &glyph);
LongMetric {
advance,
side_bearing: glyph.bbox().x_min,
side_bearing: glyph.data.bbox().x_min,
}
})
.collect();
Expand Down Expand Up @@ -379,7 +379,7 @@ mod tests {
glyph_limits.update(
GlyphId::new(0),
0,
&crate::orchestration::Glyph::Simple(
&crate::orchestration::Glyph::new(
"don't care".into(),
SimpleGlyph::from_bezpath(
&BezPath::from_svg("M-437,611 L-334,715 L-334,611 Z").unwrap(),
Expand Down
119 changes: 24 additions & 95 deletions fontbe/src/orchestration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,13 @@ use serde::{Deserialize, Serialize};
use write_fonts::{
dump_table,
tables::{
avar::Avar,
cmap::Cmap,
fvar::Fvar,
glyf::{Bbox, SimpleGlyph},
gpos::Gpos,
gsub::Gsub,
gvar::GlyphDeltas,
head::Head,
hhea::Hhea,
maxp::Maxp,
name::Name,
os2::Os2,
post::Post,
stat::Stat,
variations::Tuple,
avar::Avar, cmap::Cmap, fvar::Fvar, glyf::Glyph as RawGlyph, gpos::Gpos, gsub::Gsub,
gvar::GlyphDeltas, head::Head, hhea::Hhea, maxp::Maxp, name::Name, os2::Os2, post::Post,
stat::Stat, variations::Tuple,
},
validate::Validate,
FontWrite, OtRound,
};
use write_fonts::{from_obj::FromTableRef, tables::glyf::CompositeGlyph};

use crate::{error::Error, paths::Paths};

Expand Down Expand Up @@ -127,107 +114,49 @@ impl From<WorkId> for AnyWorkId {
}
}

/// <https://learn.microsoft.com/en-us/typography/opentype/spec/glyf>
/// A glyph and its associated name
///
/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/glyf>
#[derive(Debug, Clone)]
pub enum Glyph {
Simple(GlyphName, SimpleGlyph),
Composite(GlyphName, CompositeGlyph),
pub struct Glyph {
pub name: GlyphName,
pub data: RawGlyph,
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NamedGlyph suggests the existence of other types but there really aren't any. I'd rather call this Glyph and rename the Glyph nested within, e.g.

/// A glyph and its associated name
///
/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/glyf>
#[derive(Debug, Clone)]
pub struct Glyph {
    pub name: GlyphName,
    pub data: GlyphData,
}


impl Glyph {
pub(crate) fn new_simple(glyph_name: GlyphName, simple: SimpleGlyph) -> Glyph {
Glyph::Simple(glyph_name, simple)
}

pub(crate) fn new_composite(glyph_name: GlyphName, composite: CompositeGlyph) -> Glyph {
Glyph::Composite(glyph_name, composite)
}

pub(crate) fn glyph_name(&self) -> &GlyphName {
match self {
Glyph::Simple(name, _) | Glyph::Composite(name, _) => name,
pub(crate) fn new(name: GlyphName, glyph: impl Into<RawGlyph>) -> Self {
Self {
name,
data: glyph.into(),
}
}

pub fn to_bytes(&self) -> Vec<u8> {
match self {
Glyph::Simple(_, table) => dump_table(table),
Glyph::Composite(_, table) => dump_table(table),
}
.unwrap()
}

pub fn bbox(&self) -> Bbox {
match self {
Glyph::Simple(_, table) => table.bbox,
Glyph::Composite(_, table) => table.bbox,
}
pub fn is_simple(&self) -> bool {
matches!(&self.data, RawGlyph::Simple(_))
}

pub fn is_empty(&self) -> bool {
match self {
Glyph::Simple(_, table) => table.contours().is_empty(),
Glyph::Composite(_, table) => table.components().is_empty(),
}
pub fn to_bytes(&self) -> Vec<u8> {
dump_table(&self.data).unwrap()
}
}

impl IdAware<AnyWorkId> for Glyph {
fn id(&self) -> AnyWorkId {
AnyWorkId::Be(WorkId::GlyfFragment(self.glyph_name().clone()))
}
}

#[derive(Serialize, Deserialize)]
struct GlyphPersistable {
name: GlyphName,
simple: bool,
glyph: Vec<u8>,
}

impl From<GlyphPersistable> for Glyph {
fn from(value: GlyphPersistable) -> Self {
match value.simple {
true => {
let glyph =
read_fonts::tables::glyf::SimpleGlyph::read(FontData::new(&value.glyph))
.unwrap();
let glyph = SimpleGlyph::from_table_ref(&glyph);
Glyph::Simple(value.name, glyph)
}
false => {
let glyph =
read_fonts::tables::glyf::CompositeGlyph::read(FontData::new(&value.glyph))
.unwrap();
let glyph = CompositeGlyph::from_table_ref(&glyph);
Glyph::Composite(value.name, glyph)
}
}
AnyWorkId::Be(WorkId::GlyfFragment(self.name.clone()))
}
}

impl Persistable for Glyph {
fn read(from: &mut dyn Read) -> Self {
bincode::deserialize_from::<&mut dyn Read, GlyphPersistable>(from)
.unwrap()
.into()
let (name, bytes): (GlyphName, Vec<u8>) = bincode::deserialize_from(from).unwrap();
let glyph = RawGlyph::read(bytes.as_slice().into()).unwrap();
Glyph { name, data: glyph }
}

fn write(&self, to: &mut dyn Write) {
let obj = match self {
Glyph::Simple(name, table) => GlyphPersistable {
name: name.clone(),
simple: true,
glyph: dump_table(table).unwrap(),
},
Glyph::Composite(name, table) => GlyphPersistable {
name: name.clone(),
simple: false,
glyph: dump_table(table).unwrap(),
},
};

bincode::serialize_into::<&mut dyn Write, GlyphPersistable>(to, &obj).unwrap();
let glyph_bytes = dump_table(&self.data).unwrap();
let to_write = (&self.name, glyph_bytes);
bincode::serialize_into(to, &to_write).unwrap();
}
}

Expand Down
Loading