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

Instrumented SVGs #29

Merged
merged 2 commits into from
Dec 23, 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
6 changes: 3 additions & 3 deletions src/svg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use allsorts::{tag, Font};

use crate::cli::SvgOpts;
use crate::script;
use crate::writer::{GlyfPost, SVGWriter};
use crate::writer::{GlyfPost, SVGMode, SVGWriter};
use crate::BoxError;

const FONT_SIZE: f32 = 1000.0;
Expand Down Expand Up @@ -63,7 +63,7 @@ pub fn main(opts: SvgOpts) -> Result<i32, BoxError> {
{
let cff_data = provider.read_table_data(tag::CFF)?;
let mut cff = ReadScope::new(&cff_data).read::<CFF<'_>>()?;
let writer = SVGWriter::new(Some(opts.testcase), transform);
let writer = SVGWriter::new(SVGMode::TextRenderingTests(opts.testcase), transform);
writer.glyphs_to_svg(&mut cff, &mut font, &infos, direction)?
} else if font.glyph_table_flags.contains(GlyphTableFlags::GLYF) {
let loca_data = provider.read_table_data(tag::LOCA)?;
Expand All @@ -79,7 +79,7 @@ pub fn main(opts: SvgOpts) -> Result<i32, BoxError> {
.map(|data| ReadScope::new(data).read::<PostTable<'_>>())
.transpose()?;
let mut glyf_post = GlyfPost { glyf, post };
let writer = SVGWriter::new(Some(opts.testcase), transform);
let writer = SVGWriter::new(SVGMode::TextRenderingTests(opts.testcase), transform);
writer.glyphs_to_svg(&mut glyf_post, &mut font, &infos, direction)?
} else {
eprintln!("no glyf or CFF table");
Expand Down
6 changes: 3 additions & 3 deletions src/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use allsorts::tinyvec::tiny_vec;

use crate::cli::ViewOpts;
use crate::script;
use crate::writer::{GlyfPost, SVGWriter};
use crate::writer::{GlyfPost, SVGMode, SVGWriter};
use crate::BoxError;

const FONT_SIZE: f32 = 1000.0;
Expand Down Expand Up @@ -79,7 +79,7 @@ pub fn main(opts: ViewOpts) -> Result<i32, BoxError> {
{
let cff_data = provider.read_table_data(tag::CFF)?;
let mut cff = ReadScope::new(&cff_data).read::<CFF<'_>>()?;
let writer = SVGWriter::new(None, transform);
let writer = SVGWriter::new(SVGMode::View, transform);
writer.glyphs_to_svg(&mut cff, &mut font, &infos, direction)?
} else if font.glyph_table_flags.contains(GlyphTableFlags::GLYF) {
let loca_data = provider.read_table_data(tag::LOCA)?;
Expand All @@ -95,7 +95,7 @@ pub fn main(opts: ViewOpts) -> Result<i32, BoxError> {
.map(|data| ReadScope::new(data).read::<PostTable<'_>>())
.transpose()?;
let mut glyf_post = GlyfPost { glyf, post };
let writer = SVGWriter::new(None, transform);
let writer = SVGWriter::new(SVGMode::View, transform);
writer.glyphs_to_svg(&mut glyf_post, &mut font, &infos, direction)?
} else {
eprintln!("no glyf or CFF table");
Expand Down
150 changes: 112 additions & 38 deletions src/writer.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use std::borrow::Cow;
use std::collections::HashMap;

use allsorts::cff::CFF;
use allsorts::context::Glyph;
use allsorts::error::ParseError;
use allsorts::glyph_position::{GlyphLayout, GlyphPosition, TextDirection};
use allsorts::gpos::Info;
use allsorts::gpos::{Info, Placement};
use allsorts::gsub::GlyphOrigin;
use allsorts::outline::{OutlineBuilder, OutlineSink};
use allsorts::pathfinder_geometry::line_segment::LineSegment2F;
use allsorts::pathfinder_geometry::transform2d::Matrix2x2F;
Expand All @@ -17,9 +19,10 @@ use xmlwriter::XmlWriter;

use crate::BoxError;

struct Symbol {
struct Symbol<'info> {
glyph_name: String,
path: String,
info: &'info Info,
}

pub trait GlyphName {
Expand Down Expand Up @@ -63,19 +66,32 @@ impl<'a> OutlineBuilder for GlyfPost<'a> {
}
}

pub enum SVGMode {
/// SVGs are being generated to comply with the expected output of the
/// [Unicode text rendering tests](https://github.com/unicode-org/text-rendering-tests).
///
/// The String is the testcase name to be used as a prefix on ids.
TextRenderingTests(String),
/// SVGs are being generated for human viewing
View,
}

pub struct SVGWriter {
id_prefix: Option<String>,
mode: SVGMode,
transform: Matrix2x2F,
symbols: Vec<Symbol>,
usage: Vec<(usize, Vector2F)>,
}

struct Symbols<'info> {
transform: Matrix2x2F,
symbols: Vec<Symbol<'info>>,
}

impl SVGWriter {
pub fn new(id_prefix: Option<String>, transform: Matrix2x2F) -> Self {
pub fn new(mode: SVGMode, transform: Matrix2x2F) -> Self {
SVGWriter {
id_prefix,
mode,
transform,
symbols: Vec::new(),
usage: Vec::new(),
}
}
Expand All @@ -98,7 +114,7 @@ impl SVGWriter {
TextDirection::LeftToRight => self.glyphs_to_svg_impl(builder, font, iter),
TextDirection::RightToLeft => self.glyphs_to_svg_impl(builder, font, iter.rev()),
}
.map_err(|err| format!("error buliding SVG: {}", err))?;
.map_err(|err| format!("error building SVG: {}", err))?;
Ok(svg)
}

Expand All @@ -116,10 +132,14 @@ impl SVGWriter {
// Turn each glyph into an SVG...
let mut x = 0.;
let mut y = 0.;
let mut symbols = HashMap::new();
let mut symbols = Symbols {
transform: self.transform,
symbols: Vec::new(),
};
let mut symbol_map = HashMap::new();
for (info, pos) in iter {
let glyph_index = info.get_glyph_index();
if let Some(&symbol_index) = symbols.get(&glyph_index) {
if let Some(&symbol_index) = symbol_map.get(&glyph_index) {
self.use_glyph(
symbol_index,
x + pos.x_offset as f32,
Expand All @@ -129,9 +149,9 @@ impl SVGWriter {
let glyph_name = builder
.gid_to_glyph_name(glyph_index)
.unwrap_or_else(|| format!("gid{}", glyph_index));
let symbol_index = self.new_glyph(glyph_name);
symbols.insert(glyph_index, symbol_index);
builder.visit(glyph_index, &mut self)?;
let symbol_index = symbols.new_glyph(glyph_name, info);
symbol_map.insert(glyph_index, symbol_index);
builder.visit(glyph_index, &mut symbols)?;
self.use_glyph(
symbol_index,
x + pos.x_offset as f32,
Expand All @@ -142,21 +162,20 @@ impl SVGWriter {
y += pos.vert_advance as f32;
}

Ok(self.end(x, font.hhea_table.ascender, font.hhea_table.descender))
}

fn new_glyph(&mut self, glyph_name: String) -> usize {
let index = self.symbols.len();
self.symbols.push(Symbol::new(glyph_name));
index
Ok(self.end(
x,
font.hhea_table.ascender,
font.hhea_table.descender,
symbols,
))
}

fn use_glyph(&mut self, symbol_index: usize, x: f32, y: f32) {
self.usage
.push((symbol_index, self.transform * vec2f(x, y)));
}

fn end(self, x_max: f32, ascender: i16, descender: i16) -> String {
fn end(self, x_max: f32, ascender: i16, descender: i16, symbols: Symbols) -> String {
let mut w = XmlWriter::new(xmlwriter::Options::default());
w.write_declaration();
w.start_element("svg");
Expand All @@ -179,10 +198,12 @@ impl SVGWriter {
w.write_attribute("viewBox", &view_box);

// Write symbols
for symbol in &self.symbols {
for symbol in &symbols.symbols {
w.start_element("symbol");
let id = SVGWriter::format_id(&self.id_prefix, &symbol.glyph_name);
w.write_attribute("id", &id);
w.write_attribute("id", &symbol.id(&self.mode));
for (key, value) in symbol.data(&self.mode) {
w.write_attribute(key, &value);
}
w.write_attribute("overflow", "visible");
w.start_element("path");
w.write_attribute("d", &symbol.path);
Expand All @@ -193,40 +214,93 @@ impl SVGWriter {
// Write use statements
for (symbol_index, point) in self.usage {
w.start_element("use");
let symbol = &self.symbols[symbol_index];
let id = SVGWriter::format_id(&self.id_prefix, &symbol.glyph_name);
let href = format!("#{}", id);
w.write_attribute("xlink:href", &href);
let symbol = &symbols.symbols[symbol_index];
w.write_attribute("xlink:href", &format!("#{}", symbol.id(&self.mode)));
w.write_attribute("x", &point.x().round());
w.write_attribute("y", &point.y().round());
w.end_element();
}

w.end_document()
}
}

fn current_path(&mut self) -> &mut String {
&mut self.symbols.last_mut().unwrap().path
impl<'info> Symbols<'info> {
fn new_glyph(&mut self, glyph_name: String, info: &'info Info) -> usize {
let index = self.symbols.len();
self.symbols.push(Symbol::new(glyph_name, info));
index
}

fn format_id(id_prefix: &Option<String>, glyph_name: &str) -> String {
match id_prefix {
Some(id_prefix) => format!("{}.{}", id_prefix, glyph_name),
None => glyph_name.to_owned(),
}
fn current_path(&mut self) -> &mut String {
&mut self.symbols.last_mut().unwrap().path
}
}

impl Symbol {
fn new(glyph_name: String) -> Self {
impl<'info> Symbol<'info> {
fn new(glyph_name: String, info: &'info Info) -> Self {
Symbol {
glyph_name,
path: String::new(),
info,
}
}

fn id(&self, mode: &SVGMode) -> Cow<'_, str> {
match mode {
SVGMode::TextRenderingTests(id_prefix) => {
format!("{}.{}", id_prefix, self.glyph_name).into()
}
SVGMode::View => Cow::from(&self.glyph_name),
}
}

fn data(&self, mode: &SVGMode) -> HashMap<&'static str, String> {
match mode {
SVGMode::TextRenderingTests(_) => HashMap::new(),
SVGMode::View => {
let bool_true = String::from("true");
let mut data = HashMap::new();
if matches!(
self.info.placement,
Placement::MarkAnchor(_, _, _) | Placement::MarkOverprint(_)
) {
data.insert("data-mark", bool_true.clone());
}
data.insert("data-glyph-index", self.info.glyph.glyph_index.to_string());
data.insert(
"data-liga-component-pos",
self.info.glyph.liga_component_pos.to_string(),
);
data.insert(
"data-glyph-origin",
match self.info.glyph.glyph_origin {
GlyphOrigin::Char(_) => String::from("char"),
GlyphOrigin::Direct => String::from("direct"),
},
);
if self.info.glyph.small_caps {
data.insert("data-small-caps", bool_true.clone());
}
if self.info.glyph.multi_subst_dup {
data.insert("data-multi-subst-dup", bool_true.clone());
}
if self.info.glyph.is_vert_alt {
data.insert("data-is-vert-alt", bool_true.clone());
}
if self.info.glyph.fake_bold {
data.insert("data-fake-bold", bool_true.clone());
}
if self.info.glyph.fake_italic {
data.insert("data-fake-italic", bool_true.clone());
}
data
}
}
}
}

impl OutlineSink for SVGWriter {
impl<'info> OutlineSink for Symbols<'info> {
fn move_to(&mut self, point: Vector2F) {
let point = self.transform * point;
self.current_path()
Expand Down