using System;
using System.Collections.Generic;
using Tessera.Typesetting;
namespace Tessera.UnitTests.Typesetting
{
///
/// A font of metrics alone, holding exactly the glyphs and kerning pairs a test gives it. A glyph it lacks
/// measures as its invalid glyph, whitespace and default ignorables included.
///
public class MetricsFont : IFontMetrics
{
public struct Data
{
public string Name;
///
/// The em in pixels, or 0 to use the line height.
///
public int Em;
public int LineHeight;
///
/// How far below the top of a line its baseline sits.
///
public int Baseline;
///
/// The space between one line's descent and the next line's ascent.
///
public int LineGap;
public IReadOnlyList Pages;
///
/// The metrics of every glyph the font lacks. Required.
///
public GlyphMetrics InvalidGlyph;
public Dictionary Glyphs;
public Dictionary<(short, short), short> Kernings;
}
private readonly Data data;
private readonly Dictionary glyphs = new Dictionary();
public MetricsFont(Data data)
{
if (data.InvalidGlyph == null)
{
throw new ArgumentException("A test font needs an invalid glyph.", nameof(data));
}
this.data = data;
KerningTable = KerningTable.Build(data.Kernings ?? new Dictionary<(short, short), short>());
// Copied, since the kerning classes written into each glyph belong to this font's kerning table.
if (data.Glyphs != null)
{
foreach (KeyValuePair entry in data.Glyphs)
{
KerningClass leftKerningClass = KerningTable.LeftClassOf(entry.Key);
glyphs[entry.Key] = new GlyphMetrics
{
Width = entry.Value.Width,
LeftKerningClass = leftKerningClass,
RightKerningClass = KerningTable.RightClassOf(entry.Key),
LeftKerningRow = (ushort)((int)leftKerningClass * KerningTable.Columns),
};
}
}
MetricsTable = new GlyphMetricsTable(glyph =>
glyphs.TryGetValue(glyph, out GlyphMetrics metrics) ? metrics : data.InvalidGlyph);
}
public GlyphMetricsTable MetricsTable { get; }
public KerningTable KerningTable { get; }
public bool HasGlyph(char glyph) => glyphs.ContainsKey(glyph);
public int LineAscent => data.Baseline;
public int LineDescent => data.LineHeight - data.Baseline;
public int LineGap => data.LineGap;
public int LineHeight => data.LineHeight;
public int Em => data.Em != 0 ? data.Em : data.LineHeight;
public string Name => data.Name;
public IReadOnlyList Pages => data.Pages;
public FontFamily Family { get; set; }
}
}