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

Add StringIndex and GraphemeIndex to GlyphBounds #396

Merged
merged 1 commit into from
Mar 19, 2024
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
16 changes: 15 additions & 1 deletion src/SixLabors.Fonts/GlyphBounds.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,14 @@ public readonly struct GlyphBounds
/// </summary>
/// <param name="codePoint">The Unicode codepoint for the glyph.</param>
/// <param name="bounds">The glyph bounds.</param>
public GlyphBounds(CodePoint codePoint, in FontRectangle bounds)
/// <param name="graphemeIndex">The index of the grapheme in original text.</param>
/// <param name="stringIndex">The index of the codepoint in original text..</param>
public GlyphBounds(CodePoint codePoint, in FontRectangle bounds, int graphemeIndex, int stringIndex)
{
this.Codepoint = codePoint;
this.Bounds = bounds;
this.GraphemeIndex = graphemeIndex;
this.StringIndex = stringIndex;
}

/// <summary>
Expand All @@ -31,6 +35,16 @@ public GlyphBounds(CodePoint codePoint, in FontRectangle bounds)
/// </summary>
public FontRectangle Bounds { get; }

/// <summary>
/// Gets grapheme index of glyph in original text.
/// </summary>
public int GraphemeIndex { get; }

/// <summary>
/// Gets string index of glyph in original text.
/// </summary>
public int StringIndex { get; }

/// <inheritdoc/>
public override string ToString()
=> $"Codepoint: {this.Codepoint}, Bounds: {this.Bounds}.";
Expand Down
16 changes: 15 additions & 1 deletion src/SixLabors.Fonts/GlyphLayout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ internal GlyphLayout(
float advanceWidth,
float advanceHeight,
GlyphLayoutMode layoutMode,
bool isStartOfLine)
bool isStartOfLine,
int graphemeIndex,
int stringIndex)
{
this.Glyph = glyph;
this.CodePoint = glyph.GlyphMetrics.CodePoint;
Expand All @@ -30,6 +32,8 @@ internal GlyphLayout(
this.AdvanceY = advanceHeight;
this.LayoutMode = layoutMode;
this.IsStartOfLine = isStartOfLine;
this.GraphemeIndex = graphemeIndex;
this.StringIndex = stringIndex;
}

/// <summary>
Expand Down Expand Up @@ -78,6 +82,16 @@ internal GlyphLayout(
/// </summary>
public bool IsStartOfLine { get; }

/// <summary>
/// Gets grapheme index of glyph in original text.
/// </summary>
public int GraphemeIndex { get; }

/// <summary>
/// Gets string index of glyph in original text.
/// </summary>
public int StringIndex { get; }

/// <summary>
/// Gets a value indicating whether the glyph represents a whitespace character.
/// </summary>
Expand Down
34 changes: 26 additions & 8 deletions src/SixLabors.Fonts/TextLayout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,9 @@ private static IEnumerable<GlyphLayout> LayoutLineHorizontal(
data.ScaledAdvance,
advanceY,
GlyphLayoutMode.Horizontal,
i == 0 && j == 0));
i == 0 && j == 0,
data.GraphemeIndex,
data.StringIndex));

j++;
}
Expand Down Expand Up @@ -556,7 +558,9 @@ private static IEnumerable<GlyphLayout> LayoutLineVertical(
advanceX,
data.ScaledAdvance,
GlyphLayoutMode.Vertical,
i == 0 && j == 0));
i == 0 && j == 0,
data.GraphemeIndex,
data.StringIndex));

j++;
}
Expand Down Expand Up @@ -689,7 +693,9 @@ private static IEnumerable<GlyphLayout> LayoutLineVerticalMixed(
advanceX,
data.ScaledAdvance,
GlyphLayoutMode.VerticalRotated,
i == 0 && j == 0));
i == 0 && j == 0,
data.GraphemeIndex,
data.StringIndex));

j++;
}
Expand All @@ -712,7 +718,9 @@ private static IEnumerable<GlyphLayout> LayoutLineVerticalMixed(
advanceX,
data.ScaledAdvance,
GlyphLayoutMode.Vertical,
i == 0 && j == 0));
i == 0 && j == 0,
data.GraphemeIndex,
data.StringIndex));

j++;
}
Expand Down Expand Up @@ -895,6 +903,7 @@ private static TextBox BreakLines(
List<TextLine> textLines = new();
TextLine textLine = new();
int glyphCount = 0;
int stringIndex = 0;

// No glyph should contain more than 64 metrics.
// We do a sanity check below just in case.
Expand Down Expand Up @@ -1205,12 +1214,15 @@ private static TextBox BreakLines(
graphemeIndex,
codePointIndex,
isRotated,
isDecomposed);
isDecomposed,
stringIndex);
}

codePointIndex++;
graphemeCodePointIndex++;
}

stringIndex += graphemeEnumerator.Current.Length;
}

// Add the final line.
Expand Down Expand Up @@ -1268,7 +1280,8 @@ public void Add(
int graphemeIndex,
int offset,
bool isRotated,
bool isDecomposed)
bool isDecomposed,
int stringIndex)
{
// Reset metrics.
// We track the maximum metrics for each line to ensure glyphs can be aligned.
Expand All @@ -1288,7 +1301,8 @@ public void Add(
graphemeIndex,
offset,
isRotated,
isDecomposed));
isDecomposed,
stringIndex));
}

public TextLine SplitAt(LineBreak lineBreak, bool keepAll)
Expand Down Expand Up @@ -1627,7 +1641,8 @@ public GlyphLayoutData(
int graphemeIndex,
int offset,
bool isRotated,
bool isDecomposed)
bool isDecomposed,
int stringIndex)
{
this.Metrics = metrics;
this.PointSize = pointSize;
Expand All @@ -1640,6 +1655,7 @@ public GlyphLayoutData(
this.Offset = offset;
this.IsRotated = isRotated;
this.IsDecomposed = isDecomposed;
this.StringIndex = stringIndex;
}

public readonly CodePoint CodePoint => this.Metrics[0].CodePoint;
Expand Down Expand Up @@ -1668,6 +1684,8 @@ public GlyphLayoutData(

public bool IsDecomposed { get; }

public int StringIndex { get; }

public readonly bool IsNewLine => CodePoint.IsNewLine(this.CodePoint);

private readonly string DebuggerDisplay => FormattableString
Expand Down
6 changes: 3 additions & 3 deletions src/SixLabors.Fonts/TextMeasurer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ internal static bool TryGetCharacterAdvances(IReadOnlyList<GlyphLayout> glyphLay
GlyphLayout glyph = glyphLayouts[i];
FontRectangle bounds = new(0, 0, glyph.AdvanceX * dpi, glyph.AdvanceY * dpi);
hasSize |= bounds.Width > 0 || bounds.Height > 0;
characterBoundsList[i] = new GlyphBounds(glyph.Glyph.GlyphMetrics.CodePoint, in bounds);
characterBoundsList[i] = new GlyphBounds(glyph.Glyph.GlyphMetrics.CodePoint, in bounds, glyph.GraphemeIndex, glyph.StringIndex);
}

characterBounds = characterBoundsList;
Expand All @@ -290,7 +290,7 @@ internal static bool TryGetCharacterSizes(IReadOnlyList<GlyphLayout> glyphLayout
bounds = new(0, 0, bounds.Width, bounds.Height);

hasSize |= bounds.Width > 0 || bounds.Height > 0;
characterBoundsList[i] = new GlyphBounds(g.Glyph.GlyphMetrics.CodePoint, in bounds);
characterBoundsList[i] = new GlyphBounds(g.Glyph.GlyphMetrics.CodePoint, in bounds, g.GraphemeIndex, g.StringIndex);
}

characterBounds = characterBoundsList;
Expand All @@ -312,7 +312,7 @@ internal static bool TryGetCharacterBounds(IReadOnlyList<GlyphLayout> glyphLayou
GlyphLayout g = glyphLayouts[i];
FontRectangle bounds = g.BoundingBox(dpi);
hasSize |= bounds.Width > 0 || bounds.Height > 0;
characterBoundsList[i] = new GlyphBounds(g.Glyph.GlyphMetrics.CodePoint, in bounds);
characterBoundsList[i] = new GlyphBounds(g.Glyph.GlyphMetrics.CodePoint, in bounds, g.GraphemeIndex, g.StringIndex);
}

characterBounds = characterBoundsList;
Expand Down
76 changes: 71 additions & 5 deletions tests/SixLabors.Fonts.Tests/TextLayoutTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

using System.Globalization;
using System.Numerics;
using System.Text;
using SixLabors.Fonts.Tests.Fakes;
using SixLabors.Fonts.Unicode;

Expand Down Expand Up @@ -241,10 +240,10 @@
const string text = "a b\nc";
GlyphBounds[] expectedGlyphMetrics =
{
new(new CodePoint('a'), new FontRectangle(10, 0, 10, 10)),
new(new CodePoint(' '), new FontRectangle(40, 0, 30, 10)),
new(new CodePoint('b'), new FontRectangle(70, 0, 10, 10)),
new(new CodePoint('c'), new FontRectangle(10, 30, 10, 10)),
new(new CodePoint('a'), new FontRectangle(10, 0, 10, 10), 0, 0),
new(new CodePoint(' '), new FontRectangle(40, 0, 30, 10), 1, 1),
new(new CodePoint('b'), new FontRectangle(70, 0, 10, 10), 2, 2),
new(new CodePoint('c'), new FontRectangle(10, 30, 10, 10), 3, 3),
};
Font font = CreateFont(text);

Expand Down Expand Up @@ -778,7 +777,7 @@
}
}

public static TheoryData<char, FontRectangle> OpenSans_Data

Check warning on line 780 in tests/SixLabors.Fonts.Tests/TextLayoutTests.cs

View workflow job for this annotation

GitHub Actions / Build (false, macos-latest, net7.0, 7.0.x, true, -x64, false)

Non-constant fields should not be visible (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2211)

Check warning on line 780 in tests/SixLabors.Fonts.Tests/TextLayoutTests.cs

View workflow job for this annotation

GitHub Actions / Build (false, windows-latest, net6.0, 6.0.x, -x64, true)

Non-constant fields should not be visible (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2211)
= new()
{
{ '!', new(0, 0, 2, 8) },
Expand Down Expand Up @@ -996,11 +995,78 @@
}
}

[Fact]
public void DoesMeasureCharacterLayoutIncludeStringIndex()
{
FontFamily family = new FontCollection().Add(TestFonts.OpenSansFile);
family.TryGetMetrics(FontStyle.Regular, out FontMetrics metrics);

TextOptions options = new(family.CreateFont(metrics.UnitsPerEm))
{
LineSpacing = 1.5F
};

const string text = "The quick👩🏽‍🚒 brown fox jumps over \r\n the lazy dog";

Assert.True(TextMeasurer.TryMeasureCharacterAdvances(text, options, out ReadOnlySpan<GlyphBounds> advances));
Assert.True(TextMeasurer.TryMeasureCharacterSizes(text, options, out ReadOnlySpan<GlyphBounds> sizes));
Assert.True(TextMeasurer.TryMeasureCharacterBounds(text, options, out ReadOnlySpan<GlyphBounds> bounds));

Assert.Equal(advances.Length, sizes.Length);
Assert.Equal(advances.Length, bounds.Length);

int stringIndex = -1;

for (int i = 0; i < advances.Length; i++)
{
GlyphBounds advance = advances[i];
GlyphBounds size = sizes[i];
GlyphBounds bound = bounds[i];

Assert.Equal(bound.StringIndex, advance.StringIndex);
Assert.Equal(bound.StringIndex, size.StringIndex);

Assert.Equal(bound.GraphemeIndex, advance.GraphemeIndex);
Assert.Equal(bound.GraphemeIndex, size.GraphemeIndex);

if (bound.Codepoint == new CodePoint("k"[0]))
{
stringIndex = text.IndexOf("k", StringComparison.InvariantCulture);
Assert.Equal(stringIndex, bound.StringIndex);
Assert.Equal(stringIndex, bound.GraphemeIndex);
}

// after emoji
if (bound.Codepoint == new CodePoint("b"[0]))
{
stringIndex = text.IndexOf("b", StringComparison.InvariantCulture);
Assert.NotEqual(bound.StringIndex, bound.GraphemeIndex);
Assert.Equal(stringIndex, bound.StringIndex);
Assert.Equal(11, bound.GraphemeIndex);
}
}

SpanGraphemeEnumerator graphemeEnumerator = new(text);
int graphemeCount = 0;
while (graphemeEnumerator.MoveNext())
{
graphemeCount += 1;
}

GlyphBounds firstBound = bounds[0];
Assert.Equal(0, firstBound.StringIndex);
Assert.Equal(0, firstBound.GraphemeIndex);

GlyphBounds lastBound = bounds[^1];
Assert.Equal(text.Length - 1, lastBound.StringIndex);
Assert.Equal(graphemeCount - 1, lastBound.GraphemeIndex);
}

private static readonly Font OpenSansTTF = new FontCollection().Add(TestFonts.OpenSansFile).CreateFont(10);
private static readonly Font OpenSansWoff = new FontCollection().Add(TestFonts.OpenSansFile).CreateFont(10);

#if OS_WINDOWS
public static TheoryData<char, FontRectangle> SegoeUi_Data

Check warning on line 1069 in tests/SixLabors.Fonts.Tests/TextLayoutTests.cs

View workflow job for this annotation

GitHub Actions / Build (false, windows-latest, net6.0, 6.0.x, -x64, true)

Non-constant fields should not be visible (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2211)
= new()
{
{ '!', new(0, 0, 2, 8) },
Expand Down
Loading