Skip to content

Commit

Permalink
Use fontations Glyph enum
Browse files Browse the repository at this point in the history
This renames the backend 'Glyph' type to 'NamedGlyph', and turns it into
a simple struct, containing a `write-fonts` Glyph and the associated
name.

This also lets us delete the GlyphPersistable type, since we don't need
to store a flag indicating whether the glyph is simple or composite.
  • Loading branch information
cmyr committed Aug 8, 2023
1 parent 287e6bc commit 2adc949
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 138 deletions.
22 changes: 12 additions & 10 deletions fontbe/src/glyphs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ use read_fonts::{
};
use write_fonts::{
tables::{
glyf::{Bbox, Component, ComponentFlags, CompositeGlyph, SimpleGlyph},
glyf::{Bbox, Component, ComponentFlags, CompositeGlyph, Glyph, SimpleGlyph},
variations::iup_delta_optimize,
},
OtRound,
};

use crate::{
error::{Error, GlyphProblem},
orchestration::{AnyWorkId, BeWork, Context, Glyph, GvarFragment, LocaFormat, WorkId},
orchestration::{AnyWorkId, BeWork, Context, GvarFragment, LocaFormat, NamedGlyph, WorkId},
};

#[derive(Debug)]
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(NamedGlyph::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(NamedGlyph::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 Glyph::Composite(composite) = &composite.glyph 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 {
.and_then(|g| match &g.glyph {
Glyph::Composite(..) => None,
Glyph::Simple(_, simple_glyph) => Some(bbox2rect(simple_glyph.bbox)),
Glyph::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 Glyph::Composite(composite) = &mut glyph.glyph 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
22 changes: 11 additions & 11 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},
hhea::Hhea,
hmtx::Hmtx,
maxp::Maxp,
Expand All @@ -25,7 +25,7 @@ use write_fonts::{

use crate::{
error::Error,
orchestration::{AnyWorkId, BeWork, Context, Glyph, WorkId},
orchestration::{AnyWorkId, BeWork, Context, NamedGlyph, WorkId},
};

#[derive(Debug)]
Expand Down Expand Up @@ -81,11 +81,11 @@ impl GlyphLimits {
}

impl FontLimits {
fn update(&mut self, id: GlyphId, advance: u16, glyph: &Glyph) {
fn update(&mut self, id: GlyphId, advance: u16, glyph: &NamedGlyph) {
// 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.glyph.is_empty() {
let bbox = glyph.glyph.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.glyph.bbox();
self.bbox = self.bbox.map(|b| b.union(bbox)).or(Some(bbox));

match glyph {
Glyph::Simple(_, simple) => {
match &glyph.glyph {
Glyph::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) => {
Glyph::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.glyph.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::NamedGlyph::new(
"don't care".into(),
SimpleGlyph::from_bezpath(
&BezPath::from_svg("M-437,611 L-334,715 L-334,611 Z").unwrap(),
Expand Down
123 changes: 25 additions & 98 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,
avar::Avar, cmap::Cmap, fvar::Fvar, glyf::Glyph, 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,47 @@ impl From<WorkId> for AnyWorkId {
}
}

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

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 fn to_bytes(&self) -> Vec<u8> {
match self {
Glyph::Simple(_, table) => dump_table(table),
Glyph::Composite(_, table) => dump_table(table),
impl NamedGlyph {
pub(crate) fn new(name: GlyphName, glyph: impl Into<Glyph>) -> Self {
Self {
name,
glyph: glyph.into(),
}
.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.glyph, Glyph::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.glyph).unwrap()
}
}

impl IdAware<AnyWorkId> for Glyph {
impl IdAware<AnyWorkId> for NamedGlyph {
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 {
impl Persistable for NamedGlyph {
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 = Glyph::read(bytes.as_slice().into()).unwrap();
NamedGlyph { name, 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.glyph).unwrap();
let to_write = (&self.name, glyph_bytes);
bincode::serialize_into(to, &to_write).unwrap();
}
}

Expand Down Expand Up @@ -439,7 +366,7 @@ pub struct Context {

// work results we've completed or restored from disk
pub gvar_fragments: BeContextMap<GvarFragment>,
pub glyphs: BeContextMap<Glyph>,
pub glyphs: BeContextMap<NamedGlyph>,

pub avar: BeContextItem<BeValue<Avar>>,
pub cmap: BeContextItem<BeValue<Cmap>>,
Expand Down
Loading

0 comments on commit 2adc949

Please sign in to comment.