using System; using System.Collections.Generic; using System.IO; using System.Linq; using Amphora; using Tessera.Typesetting; using Tessera.UnitTests.Editing; using UnitTestSharp; using Tessera.UnitTests.Unicode; using Tessera.Unicode; using static Tessera.UnitTests.Typesetting.LayoutFonts; namespace Tessera.UnitTests.Typesetting { public class WordMeasurerTests : TestFixture { public const char SoftHyphen = LineBreakIterator.SoftHyphen; public const char LineSeparator = (char)0x2028; public static readonly string Emoji = TextSamples.Emoji; public static readonly string LanguageTag = TextSamples.LanguageTag; /// /// Lowercase letters, a space and a hyphen, with a few kerning pairs whose amounts all differ. /// public static MetricsFont TestFont(Dictionary glyphs = null, short kerningBetweenSpaces = 0) { glyphs ??= new Dictionary(); for (char letter = 'a'; letter <= 'z'; ++letter) { glyphs[letter] = new GlyphMetrics { Width = LetterWidth }; } glyphs[' '] = new GlyphMetrics { Width = SpaceWidth }; glyphs['-'] = new GlyphMetrics { Width = HyphenWidth }; var kernings = new Dictionary<(short, short), short> { [Pair('a', 'b')] = -1, [Pair('b', ' ')] = -2, [Pair(' ', 'c')] = -3, [Pair('b', '-')] = -1, [Pair('a', 'c')] = -5, }; if (kerningBetweenSpaces != 0) { kernings[Pair(' ', ' ')] = kerningBetweenSpaces; } return new MetricsFont(new MetricsFont.Data { Glyphs = glyphs, InvalidGlyph = new GlyphMetrics { Width = InvalidGlyphWidth }, Kernings = kernings, }); } /// /// The plain , built once for every test to share, since a font takes milliseconds to /// build. /// public static readonly MetricsFont SharedFont = TestFont(); public static string Describe(int start, in MeasuredWord word, in WordEndMetrics ends) { return $"{start}..{word.ContentEnd}..{word.End}{(word.IsMandatory ? "!" : "")} " + $"lead {word.LeadingKerning} content {word.ContentWidth} trailing {ends.TrailingWidthOf(word)} " + $"hyphen {ends.HyphenWidthOf(word)}"; } public static List Words(StringView text, IFontMetrics font = null) { return Words(new WordMeasurer(font ?? SharedFont, new LineBreakIterator(text))); } public static List Words(WordMeasurer measurer) { var ends = new WordEndMetrics(measurer.Font); var returnMe = new List(); while (measurer.MoveNext()) { returnMe.Add(Describe(measurer.CurrentStart, measurer.Current, ends)); } return returnMe; } /// /// Printable ASCII in assorted widths, with kerning between the characters LineBreakTest.txt uses most. /// public static MetricsFont ConformanceFont() { var glyphs = new Dictionary(); for (char character = ' '; character <= '~'; ++character) { glyphs[character] = new GlyphMetrics { Width = character % 7 + 3 }; } var kernings = new Dictionary<(short, short), short>(); const string kerned = " #%()0,-.a"; foreach (char left in kerned) { foreach (char right in kerned) { kernings[Pair(left, right)] = (short)((left * 3 + right) % 5 - 2); } } return new MetricsFont(new MetricsFont.Data { Glyphs = glyphs, InvalidGlyph = new GlyphMetrics { Width = InvalidGlyphWidth }, Kernings = kernings, }); } public class CtorTests : TestFixture { public void NullFont_Throws() { CheckThrow(typeof(ArgumentNullException)); new WordMeasurer(null, new LineBreakIterator("ab")); } public void KeepsFontAndText() { MetricsFont font = SharedFont; var measurer = new WordMeasurer(font, new LineBreakIterator("ab cd")); CheckEqual(font, measurer.Font); CheckEqual("ab cd", measurer.Text.ToString()); } public void ExposesTheFontsAlreadyLookedUpMetricsKerningTableAndSpace() { MetricsFont font = SharedFont; var measurer = new WordMeasurer(font, new LineBreakIterator("ab")); CheckEqual(font.MetricsTable, measurer.MetricsTable); CheckEqual(font.KerningTable, measurer.KerningTable); CheckEqual(font.MetricsTable[' '], measurer.Space); } public void ExposesTheViewOverItsString() { const string backing = "xab"; var measurer = new WordMeasurer(SharedFont, new LineBreakIterator(new StringView(backing, 1, 3))); CheckTrue(measurer.Text.IsOver(backing)); CheckEqual(1, measurer.Text.StartIndex); } public void ExposesTheViewOverItsArray() { char[] backing = "xab".ToCharArray(); var measurer = new WordMeasurer(SharedFont, new LineBreakIterator(new StringView(backing, 1, 3))); CheckTrue(measurer.Text.IsOver(backing)); CheckEqual(1, measurer.Text.StartIndex); } public void ReadsTheViewsCharactersByPositionInTheView() { var measurer = new WordMeasurer(SharedFont, new LineBreakIterator(new StringView("xab", 1, 3))); CheckEqual('a', measurer.Reader[0]); CheckEqual('b', measurer.Reader[1]); } public void ReadsAnArrayViewsCharactersByPositionInTheView() { var measurer = new WordMeasurer(SharedFont, new LineBreakIterator(new StringView("xab".ToCharArray(), 1, 3))); CheckEqual('a', measurer.Reader[0]); CheckEqual('b', measurer.Reader[1]); } public void MeasuredWords_HandsThemOutAgain() { const string text = "ab cd\ne-f"; CheckEqual(Words(text), Words(new WordMeasurer(new MeasuredWords(SharedFont, text)))); } public void MeasuredWords_ExposesTheirFontAndView() { const string backing = "xab cd"; MetricsFont font = SharedFont; var measurer = new WordMeasurer(new MeasuredWords(font, new StringView(backing, 1, 6))); CheckEqual(font, measurer.Font); CheckEqual("ab cd", measurer.Text.ToString()); CheckTrue(measurer.Text.IsOver(backing)); CheckEqual(1, measurer.Text.StartIndex); } } public class InitializeTests : TestFixture { public void MeasuresLikeTheConstructor() { var measurer = default(WordMeasurer); measurer.Initialize(SharedFont, "ab cd\ne"); CheckEqual(Words("ab cd\ne"), Words(measurer)); } public void AfterUse_StartsOverOnTheNewText() { var measurer = new WordMeasurer(SharedFont, new LineBreakIterator("xy zw")); while (measurer.MoveNext()) { } measurer.Initialize(SharedFont, "ab cd"); CheckEqual(Words("ab cd"), Words(measurer)); } public void NullFont_Throws() { var measurer = default(WordMeasurer); CheckThrow(typeof(ArgumentNullException)); measurer.Initialize(null, "ab"); } public void MeasuredWords_HandsThemOutLikeTheConstructor() { var measuredWords = new MeasuredWords(SharedFont, "ab cd\ne"); var measurer = default(WordMeasurer); measurer.Initialize(measuredWords); CheckEqual(Words(new WordMeasurer(measuredWords)), Words(measurer)); } public void AfterHandingOutMeasuredWords_MeasuresTheNewText() { var measurer = new WordMeasurer(new MeasuredWords(SharedFont, "xy zw")); while (measurer.MoveNext()) { } measurer.Initialize(SharedFont, "ab cd"); CheckEqual(Words("ab cd"), Words(measurer)); } public void MeasuredWords_AfterUse_StartsFromTheirFirstWord() { var measuredWords = new MeasuredWords(SharedFont, "ab cd"); var measurer = new WordMeasurer(measuredWords); measurer.MoveNext(); measurer.Initialize(measuredWords); CheckEqual(Words("ab cd"), Words(measurer)); } } public class MoveNextTests : TestFixture { [CpuTimeout(3000)] public void OnLineBreakTest_EndsAtEveryBreakAndAddsUpToTheTextWidth() { MetricsFont font = ConformanceFont(); var endMetrics = new WordEndMetrics(font); var mismatches = new List(); foreach (BoundaryTestFile.Case testCase in LineBreakSamples.LineBreakTestFile.Cases) { string text = testCase.Text; var ends = new List(); int width = 0; var measurer = new WordMeasurer(font, new LineBreakIterator(text)); while (measurer.MoveNext()) { ends.Add(measurer.Current.End); width += measurer.Current.LeadingKerning + measurer.Current.ContentWidth + endMetrics.TrailingWidthOf(measurer.Current); } bool endsMatch = ends.SequenceEqual(LineBreakSamples.PositionsIn(text)); // TextWidth has no lines, so it measures a hard break as a glyph. bool widthMatches = text.Any(LineBreakSamples.IsHardBreak) || width == TextWidth.Calculate(font, text); if ((!endsMatch || !widthMatches) && mismatches.Count < 10) { mismatches.Add($"[{LineBreakSamples.CodePointsOf(text)}] " + $"ends {string.Join(",", ends)}, width {width}"); } } CheckEqual("", string.Join("; ", mismatches)); } public void HandingOutMeasuredWords_PastTheLastOne_StaysFalse() { var measurer = new WordMeasurer(new MeasuredWords(SharedFont, "ab")); measurer.MoveNext(); measurer.MoveNext(); CheckFalse(measurer.MoveNext()); } public void EmptyText_HasNoWords() { CheckEqual(new string[0], Words("")); } public void OneWord_IsMandatoryAndKeepsItsInteriorKerning() { CheckEqual(new[] { "0..2..2! lead 0 content 19 trailing 0 hyphen 0" }, Words("ab")); } public void Space_HangsWithTheKerningIntoIt() { CheckEqual("0..2..3 lead 0 content 19 trailing 2 hyphen 0", Words("ab c")[0]); } public void KerningAcrossABreak_IsTheNextWordsLeadingKerning() { CheckEqual("3..4..4! lead -3 content 10 trailing 0 hyphen 0", Words("ab c")[1]); } public void SeveralSpaces_AllHang() { CheckEqual("0..1..4 lead 0 content 10 trailing 12 hyphen 0", Words("a b")[0]); } public void SeveralSpaces_KernBetweenEachOther() { CheckEqual("0..1..4 lead 0 content 10 trailing 10 hyphen 0", Words("a b", TestFont(kerningBetweenSpaces: -1))[0]); } public void SpacesAtTheStart_AreAWordWithNoContent() { CheckEqual(new[] { "0..0..2 lead 0 content 0 trailing 8 hyphen 0", "2..4..4! lead 0 content 19 trailing 0 hyphen 0", }, Words(" ab")); } public void LineFeed_HangsWithNoWidth_AndTheNextWordHasNoLeadingKerning() { CheckEqual(new[] { "0..1..3! lead 0 content 10 trailing 2 hyphen 0", "3..4..4! lead 0 content 10 trailing 0 hyphen 0", }, Words("b \nc")); } public void CarriageReturnLineFeed_EndsOneWord() { CheckEqual("0..1..3! lead 0 content 10 trailing 0 hyphen 0", Words("a\r\nb")[0]); } public void LineSeparator_IsAHardBreak() { CheckEqual("0..1..2! lead 0 content 10 trailing 0 hyphen 0", Words($"a{LineSeparator}b")[0]); } public void SoftHyphen_TakesNoWidthAndKerningCarriesAcrossIt() { CheckEqual(new[] { "0..2..2 lead 0 content 10 trailing 0 hyphen 3", "2..3..3! lead -5 content 10 trailing 0 hyphen 0", }, Words($"a{SoftHyphen}c")); } public void SoftHyphen_HyphenWidthIncludesTheKerningIntoTheHyphen() { CheckEqual("0..2..2 lead 0 content 10 trailing 0 hyphen 2", Words($"b{SoftHyphen}c")[0]); } public void SoftHyphenEndingTheText_NeedsNoHyphen() { CheckEqual(new[] { "0..3..3! lead 0 content 19 trailing 0 hyphen 0" }, Words($"ab{SoftHyphen}")); } public void SoftHyphenBeforeASpace_NeedsNoHyphen() { CheckEqual("0..2..3 lead 0 content 10 trailing 4 hyphen 0", Words($"a{SoftHyphen} b")[0]); } public void AstralCharacter_MeasuresAsOneInvalidGlyph() { CheckEqual(new[] { "0..2..2! lead 0 content 7 trailing 0 hyphen 0" }, Words(Emoji)); } public void AstralDefaultIgnorable_TakesNoWidthAndKerningCarriesAcrossIt() { CheckEqual(new[] { "0..4..4! lead 0 content 15 trailing 0 hyphen 0" }, Words($"a{LanguageTag}c")); } public void LoneSurrogate_MeasuresAsTheInvalidGlyph() { CheckEqual(new[] { "0..1..1! lead 0 content 7 trailing 0 hyphen 0" }, Words(GlyphMetricsTable.LoneSurrogate.ToString())); } public void View_PositionsAreRelativeToItsStart() { CheckEqual("0..2..3 lead 0 content 19 trailing 2 hyphen 0", Words(((StringView)"xxab cd")[2, 6])[0]); } } } }