Skip to content
Open
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
87 changes: 75 additions & 12 deletions src/cff/charset.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,86 @@
use crate::write::Writer;
use crate::CidMapping;
use crate::GlyphRemapper;
use crate::Result;

/// Rewrite the charset of the font. We do not perserve the CID's from the original font. Instead,
/// we assign each glyph it's original glyph as the CID. This makes it easier to reference them
/// from the PDF, since we know the CID a glyph will have before it's subsetted.
pub fn rewrite_charset(gid_mapper: &GlyphRemapper, w: &mut Writer) -> Result<()> {
/// Rewrite the charset of the font. We do not preserve the CIDs from the original font. Instead,
/// each glyph gets as its CID either its glyph ID in the subset or, with
/// [`CidMapping::OriginalGlyphId`], its glyph ID in the original font. Either way, the CID of a
/// glyph is known before the font is subsetted, which makes it easy to reference from the PDF.
pub fn rewrite_charset(
gid_mapper: &GlyphRemapper,
cid_mapping: CidMapping,
w: &mut Writer,
) -> Result<()> {
if gid_mapper.num_gids() == 1 {
// We only have .notdef, so use format 0.
w.write::<u8>(0);
} else {
// Use format 2.
w.write::<u8>(2);

w.write::<u16>(1);
// -2 because -1 for not including .notdef and -1 since the first glyph
// in the range is not counted.
w.write::<u16>(gid_mapper.num_gids() - 2);
return Ok(());
}

// Use format 2.
w.write::<u8>(2);

match cid_mapping {
CidMapping::SubsetGlyphId => {
w.write::<u16>(1);
// -2 because -1 for not including .notdef and -1 since the first glyph
// in the range is not counted.
w.write::<u16>(gid_mapper.num_gids() - 2);
}
CidMapping::OriginalGlyphId => {
// One range for each run of consecutive old glyph IDs, in the order of the
// new glyph IDs. .notdef is not part of the charset.
let mut gids = gid_mapper.remapped_gids().skip(1);
let mut first = gids.next().unwrap();
let mut last = first;

for gid in gids {
if gid == last + 1 {
last = gid;
} else {
w.write::<u16>(first);
w.write::<u16>(last - first);
first = gid;
last = gid;
}
}

w.write::<u16>(first);
w.write::<u16>(last - first);
}
}

Ok(())
}

#[cfg(test)]
mod tests {
use super::*;

fn charset(glyphs: &[u16], cid_mapping: CidMapping) -> Vec<u8> {
let mut w = Writer::new();
rewrite_charset(&GlyphRemapper::new_from_glyphs(glyphs), cid_mapping, &mut w)
.unwrap();
w.finish()
}

#[test]
fn subset_glyph_ids() {
assert_eq!(charset(&[], CidMapping::SubsetGlyphId), [0]);
assert_eq!(
charset(&[5, 6, 7, 20, 3], CidMapping::SubsetGlyphId),
[2, 0, 1, 0, 4]
);
}

#[test]
fn original_glyph_ids() {
assert_eq!(charset(&[], CidMapping::OriginalGlyphId), [0]);
assert_eq!(charset(&[7], CidMapping::OriginalGlyphId), [2, 0, 7, 0, 0]);
assert_eq!(
charset(&[5, 6, 7, 20, 3], CidMapping::OriginalGlyphId),
[2, 0, 5, 0, 2, 0, 20, 0, 0, 0, 3, 0, 0]
);
}
}
2 changes: 1 addition & 1 deletion src/cff/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ pub fn subset(ctx: &mut Context<'_>) -> Result<()> {

// Charsets
offsets.charset_offset.update_value(w.len())?;
rewrite_charset(&ctx.mapper, &mut w)?;
rewrite_charset(&ctx.mapper, ctx.cid_mapping, &mut w)?;

// Private dicts.
match &table.font_kind {
Expand Down
67 changes: 64 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ A couple of important notes if you want to use this crate in combination with yo
mapping from GID to CID for all fonts, regardless of the previous mapping. Because of this, you can
always use the remapped GID as the CID for a glyph, and do not need to worry about the type of font
you are embedding.
- If you need to address glyphs before the subset is known (for example to write pages on
several threads and subset the fonts once at the end), [`subset_with_options`] with
[`CidMapping::OriginalGlyphId`] makes the CID of each glyph in a CFF subset its glyph ID in
the original font. TrueType subsets carry no charset, so for them write a `CIDToGIDMap`
from the remapper instead.

# Example
In the example below, we remove all glyphs except the ones with IDs 68, 69, 70 from Noto Sans.
Expand Down Expand Up @@ -106,7 +111,7 @@ use std::str::FromStr;
///
/// CFF2 fonts are not supported.
pub fn subset(data: &[u8], index: u32, mapper: &GlyphRemapper) -> Result<Vec<u8>> {
subset_inner(data, index, &[], false, mapper)
subset_inner(data, index, &[], false, CidMapping::default(), mapper)
}

/// Subset the font face to include only the necessary glyphs and tables, instantiated
Expand All @@ -123,19 +128,72 @@ pub fn subset_with_variations(
variation_coordinates: &[(Tag, f32)],
mapper: &GlyphRemapper,
) -> Result<Vec<u8>> {
subset_inner(data, index, variation_coordinates, true, mapper)
subset_inner(data, index, variation_coordinates, true, CidMapping::default(), mapper)
}

/// Subset the font face with [`Options`].
///
/// This does the same as [`subset`] or, with the `variable-fonts` feature,
/// [`subset_with_variations`], and in addition lets you choose how the glyphs of a
/// CFF subset are addressed as CIDs.
pub fn subset_with_options(
data: &[u8],
index: u32,
mapper: &GlyphRemapper,
options: &Options,
) -> Result<Vec<u8>> {
if !cfg!(feature = "variable-fonts") && !options.variation_coordinates.is_empty() {
return Err(Unimplemented);
}
subset_inner(
data,
index,
options.variation_coordinates,
cfg!(feature = "variable-fonts"),
options.cid_mapping,
mapper,
)
}

/// How the glyphs of a CFF subset are addressed as CIDs, through its charset.
///
/// TrueType subsets have no charset: their CIDs are always the glyph IDs in the subset, and
/// a `CIDToGIDMap` in the PDF can map other CIDs onto them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CidMapping {
/// The CID of each glyph is its glyph ID in the subset, which [`GlyphRemapper::get`]
/// gives. This is the default.
#[default]
SubsetGlyphId,
/// The CID of each glyph is its glyph ID in the original font, so that content can
/// address glyphs before the subset is known. The charset grows by a few bytes for each
/// run of consecutive glyph IDs in the subset.
OriginalGlyphId,
}

/// Options for [`subset_with_options`].
#[derive(Debug, Clone, Default)]
pub struct Options<'a> {
/// How the glyphs of a CFF subset are addressed as CIDs.
pub cid_mapping: CidMapping,
/// The variation coordinates to instantiate the font at, as for
/// `subset_with_variations`. Without the `variable-fonts` feature, subsetting
/// fails with [`Error::Unimplemented`] unless this is empty.
pub variation_coordinates: &'a [(Tag, f32)],
}

fn subset_inner(
data: &[u8],
index: u32,
variation_coordinates: &[(Tag, f32)],
allow_cff2: bool,
cid_mapping: CidMapping,
mapper: &GlyphRemapper,
) -> Result<Vec<u8>> {
let mapper = mapper.clone();
let context =
let mut context =
prepare_context(data, index, variation_coordinates, allow_cff2, mapper)?;
context.cid_mapping = cid_mapping;
_subset(context)
}

Expand Down Expand Up @@ -198,6 +256,7 @@ fn prepare_context<'a>(
face,
mapper: gid_remapper,
interjector,
cid_mapping: CidMapping::default(),
custom_maxp_data: None,
custom_hmtx_data: None,
flavor,
Expand Down Expand Up @@ -371,6 +430,8 @@ struct Context<'a> {
face: Face<'a>,
/// A map from old gids to new gids, and the reverse
mapper: GlyphRemapper,
/// How the glyphs of a CFF subset are addressed as CIDs.
cid_mapping: CidMapping,
/// The font flavor.
flavor: FontFlavor,
/// Subsetted tables.
Expand Down
Loading