TextLayoutTests.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using Avalonia.Headless;
  7. using Avalonia.Media;
  8. using Avalonia.Media.TextFormatting;
  9. using Avalonia.Media.TextFormatting.Unicode;
  10. using Avalonia.UnitTests;
  11. using Avalonia.Utilities;
  12. using Xunit;
  13. namespace Avalonia.Skia.UnitTests.Media.TextFormatting
  14. {
  15. public class TextLayoutTests
  16. {
  17. private const string SingleLineText = "0123456789";
  18. private const string MultiLineText = "01 23 45 678\r\rabc def gh ij";
  19. private const string RightToLeftText = "זה כיף סתם לשמוע איך תנצח קרפד עץ טוב בגן";
  20. [InlineData("01234\r01234\r", 3)]
  21. [InlineData("01234\r01234", 2)]
  22. [Theory]
  23. public void Should_Break_Lines(string text, int numberOfLines)
  24. {
  25. using (Start())
  26. {
  27. var layout = new TextLayout(
  28. text,
  29. Typeface.Default,
  30. 12.0f,
  31. Brushes.Black);
  32. Assert.Equal(numberOfLines, layout.TextLines.Count);
  33. }
  34. }
  35. [Fact]
  36. public void Should_Apply_TextStyleSpan_To_Text_In_Between()
  37. {
  38. using (Start())
  39. {
  40. var foreground = new SolidColorBrush(Colors.Red).ToImmutable();
  41. var spans = new[]
  42. {
  43. new ValueSpan<TextRunProperties>(1, 2,
  44. new GenericTextRunProperties(Typeface.Default, 12, foregroundBrush: foreground))
  45. };
  46. var layout = new TextLayout(
  47. MultiLineText,
  48. Typeface.Default,
  49. 12.0f,
  50. Brushes.Black.ToImmutable(),
  51. textStyleOverrides: spans);
  52. var textLine = layout.TextLines[0];
  53. Assert.Equal(3, textLine.TextRuns.Count);
  54. var textRun = textLine.TextRuns[1];
  55. Assert.Equal(2, textRun.Length);
  56. var actual = textRun.Text.ToString();
  57. Assert.Equal("1 ", actual);
  58. Assert.Equal(foreground, textRun.Properties.ForegroundBrush);
  59. }
  60. }
  61. [InlineData(27)]
  62. [InlineData(22)]
  63. [Theory]
  64. public void Should_Wrap_And_Apply_Style(int length)
  65. {
  66. using (Start())
  67. {
  68. var text = "Multiline TextBox with TextWrapping.";
  69. var foreground = new SolidColorBrush(Colors.Red).ToImmutable();
  70. var expected = new TextLayout(
  71. text,
  72. Typeface.Default,
  73. 12.0f,
  74. Brushes.Black.ToImmutable(),
  75. textWrapping: TextWrapping.Wrap,
  76. maxWidth: 200);
  77. var expectedLines = expected.TextLines.Select(x => text.Substring(x.FirstTextSourceIndex,
  78. x.Length)).ToList();
  79. var spans = new[]
  80. {
  81. new ValueSpan<TextRunProperties>(0, length,
  82. new GenericTextRunProperties(Typeface.Default, 12, foregroundBrush: foreground))
  83. };
  84. var actual = new TextLayout(
  85. text,
  86. Typeface.Default,
  87. 12.0f,
  88. Brushes.Black.ToImmutable(),
  89. textWrapping: TextWrapping.Wrap,
  90. maxWidth: 200,
  91. textStyleOverrides: spans);
  92. var actualLines = actual.TextLines.Select(x => text.Substring(x.FirstTextSourceIndex,
  93. x.Length)).ToList();
  94. Assert.Equal(expectedLines.Count, actualLines.Count);
  95. for (var j = 0; j < actual.TextLines.Count; j++)
  96. {
  97. var expectedText = expectedLines[j];
  98. var actualText = actualLines[j];
  99. Assert.Equal(expectedText, actualText);
  100. }
  101. }
  102. }
  103. [Fact]
  104. public void Should_Not_Alter_Lines_After_TextStyleSpan_Was_Applied()
  105. {
  106. using (Start())
  107. {
  108. const string text = "אחד !\ntwo !\nשְׁלוֹשָׁה !";
  109. var red = new SolidColorBrush(Colors.Red).ToImmutable();
  110. var black = Brushes.Black.ToImmutable();
  111. var expected = new TextLayout(
  112. text,
  113. Typeface.Default,
  114. 12.0f,
  115. black,
  116. textWrapping: TextWrapping.Wrap);
  117. var expectedGlyphs = GetGlyphs(expected);
  118. var outer = new GraphemeEnumerator(text);
  119. var inner = new GraphemeEnumerator(text);
  120. var i = 0;
  121. var j = 0;
  122. while (true)
  123. {
  124. Grapheme grapheme;
  125. while (inner.MoveNext(out grapheme))
  126. {
  127. j += grapheme.Length;
  128. if (j + i > text.Length)
  129. {
  130. break;
  131. }
  132. var spans = new[]
  133. {
  134. new ValueSpan<TextRunProperties>(i, j,
  135. new GenericTextRunProperties(Typeface.Default, 12, foregroundBrush: red))
  136. };
  137. var actual = new TextLayout(
  138. text,
  139. Typeface.Default,
  140. 12.0f,
  141. black,
  142. textWrapping: TextWrapping.Wrap,
  143. textStyleOverrides: spans);
  144. var actualGlyphs = GetGlyphs(actual);
  145. Assert.Equal(expectedGlyphs.Count, actualGlyphs.Count);
  146. for (var k = 0; k < expectedGlyphs.Count; k++)
  147. {
  148. Assert.Equal(expectedGlyphs[k], actualGlyphs[k]);
  149. }
  150. }
  151. if (!outer.MoveNext(out grapheme))
  152. {
  153. break;
  154. }
  155. inner = new GraphemeEnumerator(text);
  156. i += grapheme.Length;
  157. }
  158. }
  159. static List<string> GetGlyphs(TextLayout textLayout)
  160. => textLayout.TextLines
  161. .Select(line => string.Join('|', line.TextRuns
  162. .Cast<ShapedTextRun>()
  163. .SelectMany(run => run.ShapedBuffer, (_, glyph) => glyph.GlyphIndex)))
  164. .ToList();
  165. }
  166. [Fact]
  167. public void Should_Apply_TextStyleSpan_To_Text_At_Start()
  168. {
  169. using (Start())
  170. {
  171. var foreground = new SolidColorBrush(Colors.Red).ToImmutable();
  172. var spans = new[]
  173. {
  174. new ValueSpan<TextRunProperties>(0, 2,
  175. new GenericTextRunProperties(Typeface.Default, 12, foregroundBrush: foreground))
  176. };
  177. var layout = new TextLayout(
  178. SingleLineText,
  179. Typeface.Default,
  180. 12.0f,
  181. Brushes.Black.ToImmutable(),
  182. textStyleOverrides: spans);
  183. var textLine = layout.TextLines[0];
  184. Assert.Equal(2, textLine.TextRuns.Count);
  185. var textRun = textLine.TextRuns[0];
  186. Assert.Equal(2, textRun.Length);
  187. var actual = SingleLineText[..textRun.Length];
  188. Assert.Equal("01", actual);
  189. Assert.Equal(foreground, textRun.Properties.ForegroundBrush);
  190. }
  191. }
  192. [Fact]
  193. public void Should_Apply_TextStyleSpan_To_Text_At_End()
  194. {
  195. using (Start())
  196. {
  197. var foreground = new SolidColorBrush(Colors.Red).ToImmutable();
  198. var spans = new[]
  199. {
  200. new ValueSpan<TextRunProperties>(8, 2,
  201. new GenericTextRunProperties(Typeface.Default, 12, foregroundBrush: foreground)),
  202. };
  203. var layout = new TextLayout(
  204. SingleLineText,
  205. Typeface.Default,
  206. 12.0f,
  207. Brushes.Black.ToImmutable(),
  208. textStyleOverrides: spans);
  209. var textLine = layout.TextLines[0];
  210. Assert.Equal(2, textLine.TextRuns.Count);
  211. var textRun = textLine.TextRuns[1];
  212. Assert.Equal(2, textRun.Length);
  213. var actual = textRun.Text.ToString();
  214. Assert.Equal("89", actual);
  215. Assert.Equal(foreground, textRun.Properties.ForegroundBrush);
  216. }
  217. }
  218. [Fact]
  219. public void Should_Apply_TextStyleSpan_To_Single_Character()
  220. {
  221. using (Start())
  222. {
  223. var foreground = new SolidColorBrush(Colors.Red).ToImmutable();
  224. var spans = new[]
  225. {
  226. new ValueSpan<TextRunProperties>(0, 1,
  227. new GenericTextRunProperties(Typeface.Default, 12, foregroundBrush: foreground))
  228. };
  229. var layout = new TextLayout(
  230. "0",
  231. Typeface.Default,
  232. 12.0f,
  233. Brushes.Black.ToImmutable(),
  234. textStyleOverrides: spans);
  235. var textLine = layout.TextLines[0];
  236. Assert.Equal(1, textLine.TextRuns.Count);
  237. var textRun = textLine.TextRuns[0];
  238. Assert.Equal(1, textRun.Length);
  239. Assert.Equal(foreground, textRun.Properties.ForegroundBrush);
  240. }
  241. }
  242. [Fact]
  243. public void Should_Apply_TextSpan_To_Unicode_String_In_Between()
  244. {
  245. using (Start())
  246. {
  247. const string text = "😄😄😄😄";
  248. var foreground = new SolidColorBrush(Colors.Red).ToImmutable();
  249. var spans = new[]
  250. {
  251. new ValueSpan<TextRunProperties>(2, 2,
  252. new GenericTextRunProperties(Typeface.Default, 12, foregroundBrush: foreground))
  253. };
  254. var layout = new TextLayout(
  255. text,
  256. Typeface.Default,
  257. 12.0f,
  258. Brushes.Black.ToImmutable(),
  259. textStyleOverrides: spans);
  260. var textLine = layout.TextLines[0];
  261. Assert.Equal(3, textLine.TextRuns.Count);
  262. var textRun = textLine.TextRuns[1];
  263. Assert.Equal(2, textRun.Length);
  264. var actual = textRun.Text.ToString();
  265. Assert.Equal("😄", actual);
  266. Assert.Equal(foreground, textRun.Properties.ForegroundBrush);
  267. }
  268. }
  269. [Fact]
  270. public void TextLength_Should_Be_Equal_To_TextLine_Length_Sum()
  271. {
  272. using (Start())
  273. {
  274. var layout = new TextLayout(
  275. MultiLineText,
  276. Typeface.Default,
  277. 12.0f,
  278. Brushes.Black.ToImmutable());
  279. Assert.Equal(MultiLineText.Length, layout.TextLines.Sum(x => x.Length));
  280. }
  281. }
  282. [Fact]
  283. public void TextLength_Should_Be_Equal_To_TextRun_TextLength_Sum()
  284. {
  285. using (Start())
  286. {
  287. var layout = new TextLayout(
  288. MultiLineText,
  289. Typeface.Default,
  290. 12.0f,
  291. Brushes.Black.ToImmutable());
  292. Assert.Equal(
  293. MultiLineText.Length,
  294. layout.TextLines.Select(textLine =>
  295. textLine.TextRuns.Sum(textRun => textRun.Length))
  296. .Sum());
  297. }
  298. }
  299. [Fact]
  300. public void TextLength_Should_Be_Equal_To_TextRun_TextLength_Sum_After_Wrap_With_Style_Applied()
  301. {
  302. using (Start())
  303. {
  304. const string text =
  305. "Multiline TextBox with TextWrapping.\r\rLorem ipsum dolor sit amet";
  306. var foreground = new SolidColorBrush(Colors.Red).ToImmutable();
  307. var spans = new[]
  308. {
  309. new ValueSpan<TextRunProperties>(0, 24,
  310. new GenericTextRunProperties(Typeface.Default, 12, foregroundBrush: foreground))
  311. };
  312. var layout = new TextLayout(
  313. text,
  314. Typeface.Default,
  315. 12.0f,
  316. Brushes.Black.ToImmutable(),
  317. textWrapping: TextWrapping.Wrap,
  318. maxWidth: 180,
  319. textStyleOverrides: spans);
  320. Assert.Equal(
  321. text.Length,
  322. layout.TextLines.Select(textLine =>
  323. textLine.TextRuns.Sum(textRun => textRun.Length))
  324. .Sum());
  325. }
  326. }
  327. [Fact]
  328. public void Should_Apply_TextStyleSpan_To_MultiLine()
  329. {
  330. using (Start())
  331. {
  332. var foreground = new SolidColorBrush(Colors.Red).ToImmutable();
  333. var spans = new[]
  334. {
  335. new ValueSpan<TextRunProperties>(5, 20,
  336. new GenericTextRunProperties(Typeface.Default, 12, foregroundBrush: foreground))
  337. };
  338. var layout = new TextLayout(
  339. MultiLineText,
  340. Typeface.Default,
  341. 12.0f,
  342. Brushes.Black.ToImmutable(),
  343. maxWidth: 200,
  344. maxHeight: 125,
  345. textStyleOverrides: spans);
  346. Assert.Equal(foreground, layout.TextLines[0].TextRuns[1].Properties.ForegroundBrush);
  347. Assert.Equal(foreground, layout.TextLines[1].TextRuns[0].Properties.ForegroundBrush);
  348. Assert.Equal(foreground, layout.TextLines[2].TextRuns[0].Properties.ForegroundBrush);
  349. }
  350. }
  351. [Fact]
  352. public void Should_Hit_Test_SurrogatePair()
  353. {
  354. using (Start())
  355. {
  356. const string text = "😄😄";
  357. var layout = new TextLayout(
  358. text,
  359. Typeface.Default,
  360. 12.0f,
  361. Brushes.Black.ToImmutable());
  362. var shapedRun = (ShapedTextRun)layout.TextLines[0].TextRuns[0];
  363. var glyphRun = shapedRun.GlyphRun;
  364. var width = glyphRun.Bounds.Width;
  365. var characterHit = glyphRun.GetCharacterHitFromDistance(width, out _);
  366. Assert.Equal(2, characterHit.FirstCharacterIndex);
  367. Assert.Equal(2, characterHit.TrailingLength);
  368. }
  369. }
  370. [Theory]
  371. [InlineData("☝🏿", new int[] { 0 })]
  372. [InlineData("☝🏿 ab", new int[] { 0, 3, 4, 5 })]
  373. [InlineData("ab ☝🏿", new int[] { 0, 1, 2, 3 })]
  374. public void Should_Create_Valid_Clusters_For_Text(string text, int[] clusters)
  375. {
  376. using (Start())
  377. {
  378. var layout = new TextLayout(
  379. text,
  380. Typeface.Default,
  381. 12.0f,
  382. Brushes.Black.ToImmutable());
  383. var textLine = layout.TextLines[0];
  384. var index = 0;
  385. foreach (var textRun in textLine.TextRuns)
  386. {
  387. var shapedRun = (ShapedTextRun)textRun;
  388. var glyphClusters = shapedRun.ShapedBuffer.Select(glyph => glyph.GlyphCluster).ToArray();
  389. var expected = clusters.Skip(index).Take(glyphClusters.Length).ToArray();
  390. Assert.Equal(expected, glyphClusters);
  391. index += glyphClusters.Length;
  392. }
  393. }
  394. }
  395. [Theory]
  396. [InlineData("abcde\r\n", 7)] // Carriage Return + Line Feed
  397. [InlineData("abcde\u000A", 6)] // Line Feed
  398. [InlineData("abcde\u000B", 6)] // Vertical Tab
  399. [InlineData("abcde\u000C", 6)] // Form Feed
  400. [InlineData("abcde\u000D", 6)] // Carriage Return
  401. public void Should_Break_With_BreakChar(string text, int expectedLength)
  402. {
  403. using (Start())
  404. {
  405. var layout = new TextLayout(
  406. text,
  407. Typeface.Default,
  408. 12.0f,
  409. Brushes.Black.ToImmutable());
  410. Assert.Equal(2, layout.TextLines.Count);
  411. Assert.Equal(1, layout.TextLines[0].TextRuns.Count);
  412. Assert.Equal(expectedLength, ((ShapedTextRun)layout.TextLines[0].TextRuns[0]).GlyphRun.GlyphInfos.Count);
  413. Assert.Equal(5, ((ShapedTextRun)layout.TextLines[0].TextRuns[0]).ShapedBuffer[5].GlyphCluster);
  414. if (expectedLength == 7)
  415. {
  416. Assert.Equal(5, ((ShapedTextRun)layout.TextLines[0].TextRuns[0]).ShapedBuffer[6].GlyphCluster);
  417. }
  418. }
  419. }
  420. [Fact]
  421. public void Should_Have_One_Run_With_Common_Script()
  422. {
  423. using (Start())
  424. {
  425. var layout = new TextLayout(
  426. "abcde\r\n",
  427. Typeface.Default,
  428. 12.0f,
  429. Brushes.Black.ToImmutable());
  430. Assert.Equal(1, layout.TextLines[0].TextRuns.Count);
  431. }
  432. }
  433. [Fact]
  434. public void Should_Layout_Corrupted_Text()
  435. {
  436. using (Start())
  437. {
  438. var text = new string(new[] { '\uD802', '\uD802', '\uD802', '\uD802', '\uD802', '\uD802', '\uD802' });
  439. var layout = new TextLayout(
  440. text,
  441. Typeface.Default,
  442. 12,
  443. Brushes.Black.ToImmutable());
  444. var textLine = layout.TextLines[0];
  445. var textRun = (ShapedTextRun)textLine.TextRuns[0];
  446. Assert.Equal(7, textRun.Length);
  447. var replacementGlyph = Typeface.Default.GlyphTypeface.GetGlyph(Codepoint.ReplacementCodepoint);
  448. foreach (var glyphInfo in textRun.GlyphRun.GlyphInfos)
  449. {
  450. Assert.Equal(replacementGlyph, glyphInfo.GlyphIndex);
  451. }
  452. }
  453. }
  454. [InlineData("0123456789\r0123456789")]
  455. [InlineData("0123456789")]
  456. [Theory]
  457. public void Should_Include_First_Line_When_Constraint_Is_Surpassed(string text)
  458. {
  459. using (Start())
  460. {
  461. var glyphTypeface = Typeface.Default.GlyphTypeface;
  462. var emHeight = glyphTypeface.Metrics.DesignEmHeight;
  463. var lineHeight = glyphTypeface.Metrics.LineSpacing * (12.0 / emHeight);
  464. var layout = new TextLayout(
  465. text,
  466. Typeface.Default,
  467. 12,
  468. Brushes.Black.ToImmutable(),
  469. maxHeight: lineHeight - lineHeight * 0.5);
  470. Assert.Equal(1, layout.TextLines.Count);
  471. Assert.Equal(lineHeight, layout.Height);
  472. }
  473. }
  474. [InlineData("0123456789\r\n0123456789\r\n0123456789", 0, 3)]
  475. [InlineData("0123456789\r\n0123456789\r\n0123456789", 1, 1)]
  476. [InlineData("0123456789\r\n0123456789\r\n0123456789", 4, 3)]
  477. [Theory]
  478. public void Should_Not_Exceed_MaxLines(string text, int maxLines, int expectedLines)
  479. {
  480. using (Start())
  481. {
  482. var layout = new TextLayout(
  483. text,
  484. Typeface.Default,
  485. 12,
  486. Brushes.Black,
  487. maxWidth: 50,
  488. maxLines: maxLines);
  489. Assert.Equal(expectedLines, layout.TextLines.Count);
  490. }
  491. }
  492. [Fact]
  493. public void Should_Produce_Fixed_Height_Lines()
  494. {
  495. using (Start())
  496. {
  497. var layout = new TextLayout(
  498. MultiLineText,
  499. Typeface.Default,
  500. 12,
  501. Brushes.Black,
  502. lineHeight: 50);
  503. foreach (var line in layout.TextLines)
  504. {
  505. Assert.Equal(50, line.Height);
  506. }
  507. }
  508. }
  509. private const string Text = "日本でTest一番読まれている英字新聞・ジャパンタイムズが発信する国内外ニュースと、様々なジャンルの特集記事。";
  510. [Fact(Skip = "Only used for profiling.")]
  511. public void Should_Wrap()
  512. {
  513. using (Start())
  514. {
  515. for (var i = 0; i < 2000; i++)
  516. {
  517. var layout = new TextLayout(
  518. Text,
  519. Typeface.Default,
  520. 12,
  521. Brushes.Black,
  522. textWrapping: TextWrapping.Wrap,
  523. maxWidth: 50);
  524. }
  525. }
  526. }
  527. [Fact]
  528. public void Should_Process_Multiple_NewLines_Properly()
  529. {
  530. using (Start())
  531. {
  532. var text = "123\r\n\r\n456\r\n\r\n";
  533. var layout = new TextLayout(
  534. text,
  535. Typeface.Default,
  536. 12.0f,
  537. Brushes.Black);
  538. Assert.Equal(5, layout.TextLines.Count);
  539. Assert.Equal("123\r\n", layout.TextLines[0].TextRuns[0].Text.ToString());
  540. Assert.Equal("\r\n", layout.TextLines[1].TextRuns[0].Text.ToString());
  541. Assert.Equal("456\r\n", layout.TextLines[2].TextRuns[0].Text.ToString());
  542. Assert.Equal("\r\n", layout.TextLines[3].TextRuns[0].Text.ToString());
  543. }
  544. }
  545. [Fact]
  546. public void Should_Wrap_Min_OneCharacter_EveryLine()
  547. {
  548. using (Start())
  549. {
  550. var layout = new TextLayout(
  551. SingleLineText,
  552. Typeface.Default,
  553. 12,
  554. Brushes.Black,
  555. textWrapping: TextWrapping.Wrap,
  556. maxWidth: 3);
  557. //every character should be new line as there not enough space for even one character
  558. Assert.Equal(SingleLineText.Length, layout.TextLines.Count);
  559. }
  560. }
  561. [Fact]
  562. public void Should_HitTestTextRange_RightToLeft()
  563. {
  564. using (Start())
  565. {
  566. const int start = 0;
  567. const int length = 10;
  568. var layout = new TextLayout(
  569. RightToLeftText,
  570. Typeface.Default,
  571. 12,
  572. Brushes.Black);
  573. var selectedText = new TextLayout(
  574. RightToLeftText.Substring(start, length),
  575. Typeface.Default,
  576. 12,
  577. Brushes.Black);
  578. var rects = layout.HitTestTextRange(start, length).ToArray();
  579. Assert.Equal(1, rects.Length);
  580. var selectedRect = rects[0];
  581. Assert.Equal(selectedText.WidthIncludingTrailingWhitespace, selectedRect.Width, 2);
  582. }
  583. }
  584. [Fact]
  585. public void Should_HitTestTextRange_BiDi()
  586. {
  587. const string text = "זה כיףabcDEFזה כיף";
  588. using (Start())
  589. {
  590. var layout = new TextLayout(
  591. text,
  592. Typeface.Default,
  593. 12.0f,
  594. Brushes.Black.ToImmutable());
  595. var textLine = layout.TextLines[0];
  596. var start = textLine.GetDistanceFromCharacterHit(new CharacterHit(5, 1));
  597. var end = textLine.GetDistanceFromCharacterHit(new CharacterHit(6, 1));
  598. var rects = layout.HitTestTextRange(0, 7).ToArray();
  599. Assert.Equal(1, rects.Length);
  600. var expected = rects[0];
  601. Assert.Equal(expected.Left, start);
  602. Assert.Equal(expected.Right, end);
  603. }
  604. }
  605. [Fact]
  606. public void Should_HitTestTextRange()
  607. {
  608. using (Start())
  609. {
  610. var layout = new TextLayout(
  611. SingleLineText,
  612. Typeface.Default,
  613. 12.0f,
  614. Brushes.Black.ToImmutable());
  615. var lineRects = layout.HitTestTextRange(0, SingleLineText.Length).ToList();
  616. Assert.Equal(layout.TextLines.Count, lineRects.Count);
  617. for (var i = 0; i < layout.TextLines.Count; i++)
  618. {
  619. var textLine = layout.TextLines[i];
  620. var rect = lineRects[i];
  621. Assert.Equal(textLine.WidthIncludingTrailingWhitespace, rect.Width);
  622. }
  623. var rects = layout.TextLines
  624. .SelectMany(x => x.TextRuns.Cast<ShapedTextRun>())
  625. .SelectMany(x => x.ShapedBuffer, (_, glyph) => glyph.GlyphAdvance)
  626. .ToArray();
  627. for (var i = 0; i < SingleLineText.Length; i++)
  628. {
  629. for (var j = 1; i + j < SingleLineText.Length; j++)
  630. {
  631. var expected = rects.AsSpan(i, j).ToArray().Sum();
  632. var actual = layout.HitTestTextRange(i, j).Sum(x => x.Width);
  633. Assert.Equal(expected, actual);
  634. }
  635. }
  636. }
  637. }
  638. [Fact]
  639. public void Should_Wrap_RightToLeft()
  640. {
  641. const string text =
  642. "يَجِبُ عَلَى الإنْسَانِ أن يَكُونَ أمِيْنَاً وَصَادِقَاً مَعَ نَفْسِهِ وَمَعَ أَهْلِهِ وَجِيْرَانِهِ وَأَنْ يَبْذُلَ كُلَّ جُهْدٍ فِي إِعْلاءِ شَأْنِ الوَطَنِ وَأَنْ يَعْمَلَ عَلَى مَا يَجْلِبُ السَّعَادَةَ لِلنَّاسِ . ولَن يَتِمَّ لَهُ ذلِك إِلا بِأَنْ يُقَدِّمَ المَنْفَعَةَ العَامَّةَ عَلَى المَنْفَعَةِ الخَاصَّةِ وَهذَا مِثَالٌ لِلتَّضْحِيَةِ .";
  643. using (Start())
  644. {
  645. for (var maxWidth = 366; maxWidth < 900; maxWidth += 33)
  646. {
  647. var layout = new TextLayout(
  648. text,
  649. Typeface.Default,
  650. 12.0f,
  651. Brushes.Black.ToImmutable(),
  652. textWrapping: TextWrapping.Wrap,
  653. flowDirection: FlowDirection.RightToLeft,
  654. maxWidth: maxWidth);
  655. foreach (var textLine in layout.TextLines)
  656. {
  657. Assert.True(textLine.Width <= maxWidth);
  658. var actual = new string(textLine.TextRuns.Cast<ShapedTextRun>()
  659. .OrderBy(x => TextTestHelper.GetStartCharIndex(x.Text))
  660. .SelectMany(x => x.Text.ToString())
  661. .ToArray());
  662. var expected = text.Substring(textLine.FirstTextSourceIndex, textLine.Length);
  663. Assert.Equal(expected, actual);
  664. }
  665. }
  666. }
  667. }
  668. [Fact]
  669. public void Should_Layout_Empty_String()
  670. {
  671. using (Start())
  672. {
  673. var layout = new TextLayout(
  674. string.Empty,
  675. Typeface.Default,
  676. 12,
  677. Brushes.Black);
  678. Assert.True(layout.Height > 0);
  679. }
  680. }
  681. [Fact]
  682. public void Should_HitTestPoint_RightToLeft()
  683. {
  684. using (Start())
  685. {
  686. var text = "אאא AAA";
  687. var layout = new TextLayout(
  688. text,
  689. Typeface.Default,
  690. 12,
  691. Brushes.Black,
  692. flowDirection: FlowDirection.RightToLeft);
  693. var firstRun = layout.TextLines[0].TextRuns[0] as ShapedTextRun;
  694. var hit = layout.HitTestPoint(new Point());
  695. Assert.Equal(4, hit.TextPosition);
  696. var currentX = 0.0;
  697. for (var i = 0; i < firstRun.GlyphRun.GlyphInfos.Count; i++)
  698. {
  699. var cluster = firstRun.GlyphRun.GlyphInfos[i].GlyphCluster;
  700. var advance = firstRun.GlyphRun.GlyphInfos[i].GlyphAdvance;
  701. hit = layout.HitTestPoint(new Point(currentX, 0));
  702. Assert.Equal(cluster, hit.TextPosition);
  703. var hitRange = layout.HitTestTextRange(hit.TextPosition, 1);
  704. var distance = hitRange.First().Left;
  705. Assert.Equal(currentX, distance, 2);
  706. currentX += advance;
  707. }
  708. var secondRun = layout.TextLines[0].TextRuns[1] as ShapedTextRun;
  709. hit = layout.HitTestPoint(new Point(firstRun.Size.Width, 0));
  710. Assert.Equal(7, hit.TextPosition);
  711. hit = layout.HitTestPoint(new Point(layout.TextLines[0].WidthIncludingTrailingWhitespace, 0));
  712. Assert.Equal(0, hit.TextPosition);
  713. currentX = firstRun.Size.Width + 0.5;
  714. for (var i = 0; i < secondRun.GlyphRun.GlyphInfos.Count; i++)
  715. {
  716. var cluster = secondRun.GlyphRun.GlyphInfos[i].GlyphCluster;
  717. var advance = secondRun.GlyphRun.GlyphInfos[i].GlyphAdvance;
  718. hit = layout.HitTestPoint(new Point(currentX, 0));
  719. Assert.Equal(cluster, hit.CharacterHit.FirstCharacterIndex);
  720. var hitRange = layout.HitTestTextRange(hit.CharacterHit.FirstCharacterIndex, hit.CharacterHit.TrailingLength);
  721. var distance = hitRange.First().Left + 0.5;
  722. Assert.Equal(currentX, distance, 2);
  723. currentX += advance;
  724. }
  725. }
  726. }
  727. [Fact]
  728. public void Should_Get_CharacterHit_From_Distance_RTL()
  729. {
  730. using (Start())
  731. {
  732. var text = "أَبْجَدِيَّة عَرَبِيَّة";
  733. var layout = new TextLayout(
  734. text,
  735. Typeface.Default,
  736. 12,
  737. Brushes.Black);
  738. var textLine = layout.TextLines[0];
  739. var firstRun = (ShapedTextRun)textLine.TextRuns[0];
  740. var firstCluster = firstRun.ShapedBuffer[0].GlyphCluster;
  741. var characterHit = textLine.GetCharacterHitFromDistance(0);
  742. Assert.Equal(firstCluster, characterHit.FirstCharacterIndex);
  743. Assert.Equal(text.Length, characterHit.FirstCharacterIndex + characterHit.TrailingLength);
  744. var distance = textLine.GetDistanceFromCharacterHit(characterHit);
  745. Assert.Equal(0, distance);
  746. distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(characterHit.FirstCharacterIndex));
  747. var firstAdvance = firstRun.ShapedBuffer[0].GlyphAdvance;
  748. Assert.Equal(firstAdvance, distance, 5);
  749. var rect = layout.HitTestTextPosition(22);
  750. Assert.Equal(firstAdvance, rect.Left, 5);
  751. rect = layout.HitTestTextPosition(23);
  752. Assert.Equal(0, rect.Left, 5);
  753. }
  754. }
  755. [Fact]
  756. public void Should_Get_CharacterHit_From_Distance_RTL_With_TextStyles()
  757. {
  758. using (Start())
  759. {
  760. var text = "أَبْجَدِيَّة عَرَبِيَّة";
  761. var i = 0;
  762. var graphemeEnumerator = new GraphemeEnumerator(text);
  763. while (graphemeEnumerator.MoveNext(out var grapheme))
  764. {
  765. var textStyleOverrides = new[] { new ValueSpan<TextRunProperties>(i, grapheme.Length, new GenericTextRunProperties(Typeface.Default, 12, foregroundBrush: Brushes.Red)) };
  766. i += grapheme.Length;
  767. var layout = new TextLayout(
  768. text,
  769. Typeface.Default,
  770. 12,
  771. Brushes.Black,
  772. textStyleOverrides: textStyleOverrides);
  773. var textLine = layout.TextLines[0];
  774. var shapedRuns = textLine.TextRuns.Cast<ShapedTextRun>().ToList();
  775. var clusters = shapedRuns.SelectMany(x => x.ShapedBuffer, (_, glyph) => glyph.GlyphCluster).ToList();
  776. var glyphAdvances = shapedRuns.SelectMany(x => x.ShapedBuffer, (_, glyph) => glyph.GlyphAdvance).ToList();
  777. var currentX = 0.0;
  778. var cluster = text.Length;
  779. for (int j = 0; j < clusters.Count - 1; j++)
  780. {
  781. var glyphAdvance = glyphAdvances[j];
  782. var characterHit = textLine.GetCharacterHitFromDistance(currentX);
  783. Assert.Equal(cluster, characterHit.FirstCharacterIndex + characterHit.TrailingLength);
  784. var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(cluster));
  785. Assert.Equal(currentX, distance, 5);
  786. currentX += glyphAdvance;
  787. if(glyphAdvance > 0)
  788. {
  789. cluster = clusters[j];
  790. }
  791. }
  792. }
  793. }
  794. }
  795. [InlineData("mgfg🧐df f sdf", "g🧐d", 20, 40)]
  796. [InlineData("وه. وقد تعرض لانتقادات", "دات", 5, 30)]
  797. [InlineData("وه. وقد تعرض لانتقادات", "تعرض", 20, 50)]
  798. [InlineData(" علمية 😱ومضللة ،", " علمية 😱ومضللة ،", 40, 100)]
  799. [InlineData("في عام 2018 ، رفعت ل", "في عام 2018 ، رفعت ل", 100, 120)]
  800. [Theory]
  801. public void HitTestTextRange_Range_ValidLength(string text, string textToSelect, double minWidth, double maxWidth)
  802. {
  803. using (Start())
  804. {
  805. var layout = new TextLayout(text, Typeface.Default, 12, Brushes.Black);
  806. var start = text.IndexOf(textToSelect);
  807. var selectionRectangles = layout.HitTestTextRange(start, textToSelect.Length);
  808. Assert.Equal(1, selectionRectangles.Count());
  809. var rect = selectionRectangles.First();
  810. Assert.InRange(rect.Width, minWidth, maxWidth);
  811. }
  812. }
  813. [InlineData("012🧐210", 2, 4, FlowDirection.LeftToRight, "14.40234375,40.8046875")]
  814. [InlineData("210🧐012", 2, 4, FlowDirection.RightToLeft, "0,7.201171875;21.603515625,33.603515625;48.005859375,55.20703125")]
  815. [InlineData("שנב🧐שנב", 2, 4, FlowDirection.LeftToRight, "11.268,38.208")]
  816. [InlineData("שנב🧐שנב", 2, 4, FlowDirection.RightToLeft, "11.268,38.208")]
  817. [Theory]
  818. public void Should_HitTestTextRangeBetweenRuns(string text, int start, int length,
  819. FlowDirection flowDirection, string expected)
  820. {
  821. using (Start())
  822. {
  823. var expectedRects = expected.Split(';').Select(x =>
  824. {
  825. var startEnd = x.Split(',');
  826. var start = double.Parse(startEnd[0], CultureInfo.InvariantCulture);
  827. var end = double.Parse(startEnd[1], CultureInfo.InvariantCulture);
  828. return new Rect(start, 0, end - start, 0);
  829. }).ToArray();
  830. var textLayout = new TextLayout(text, Typeface.Default, 12, Brushes.Black, flowDirection: flowDirection);
  831. var rects = textLayout.HitTestTextRange(start, length).ToArray();
  832. Assert.Equal(expectedRects.Length, rects.Length);
  833. var endX = textLayout.TextLines[0].GetDistanceFromCharacterHit(new CharacterHit(2));
  834. var startX = textLayout.TextLines[0].GetDistanceFromCharacterHit(new CharacterHit(5, 1));
  835. for (int i = 0; i < expectedRects.Length; i++)
  836. {
  837. var expectedRect = expectedRects[i];
  838. Assert.Equal(expectedRect.Left, rects[i].Left, 2);
  839. Assert.Equal(expectedRect.Right, rects[i].Right, 2);
  840. }
  841. }
  842. }
  843. [Fact]
  844. public void Should_HitTestTextRangeWithLineBreaks()
  845. {
  846. using (Start())
  847. {
  848. var beforeLinebreak = "Line before linebreak";
  849. var afterLinebreak = "Line after linebreak";
  850. var text = beforeLinebreak + Environment.NewLine + "" + Environment.NewLine + afterLinebreak;
  851. var textLayout = new TextLayout(text, Typeface.Default, 12, Brushes.Black);
  852. var end = text.Length - afterLinebreak.Length + 1;
  853. var rects = textLayout.HitTestTextRange(0, end).ToArray();
  854. Assert.Equal(3, rects.Length);
  855. var endX = textLayout.TextLines[2].GetDistanceFromCharacterHit(new CharacterHit(end));
  856. //First character should be covered
  857. Assert.Equal(7.201171875, endX, 2);
  858. }
  859. }
  860. [Fact]
  861. public void Should_HitTestTextPosition_EndOfLine_RTL()
  862. {
  863. var text = "גש\r\n";
  864. using (Start())
  865. {
  866. var textLayout = new TextLayout(text, Typeface.Default, 12, Brushes.Black, flowDirection: FlowDirection.RightToLeft);
  867. var rect = textLayout.HitTestTextPosition(text.Length);
  868. Assert.Equal(16.32, rect.Top);
  869. }
  870. }
  871. [Win32Fact("Font only available on Windows")]
  872. public void Should_Handle_TextStyle_With_Ligature()
  873. {
  874. using (Start())
  875. {
  876. var text = "fi";
  877. var typeface = new Typeface("Calibri");
  878. var textLayout = new TextLayout(text, typeface, 12, Brushes.Black,
  879. textStyleOverrides: new[]
  880. {
  881. new ValueSpan<TextRunProperties>(1, 1,
  882. new GenericTextRunProperties(typeface, foregroundBrush: Brushes.White))
  883. });
  884. Assert.NotNull(textLayout);
  885. }
  886. }
  887. [Fact]
  888. public void Should_Measure_TextLayoutSymbolWithAndWidthIncludingTrailingWhitespace()
  889. {
  890. const string symbolsFont = "resm:Avalonia.Skia.UnitTests.Fonts?assembly=Avalonia.Skia.UnitTests#Symbols";
  891. using (Start())
  892. {
  893. var textLayout = new TextLayout("\ue971", new Typeface(symbolsFont), 12.0, Brushes.White);
  894. Assert.Equal(new Size(12.0, 12.0), new Size(textLayout.Width, textLayout.Height));
  895. Assert.Equal(12.0, textLayout.WidthIncludingTrailingWhitespace);
  896. }
  897. }
  898. [Fact]
  899. public void Should_Wrap_With_LineEnd()
  900. {
  901. using (Start())
  902. {
  903. var defaultProperties =
  904. new GenericTextRunProperties(Typeface.Default, 72, foregroundBrush: Brushes.Black);
  905. var paragraphProperties = new GenericTextParagraphProperties(defaultProperties, textWrapping: TextWrapping.Wrap);
  906. var textLayout = new TextLayout(new SingleBufferTextSource("01", defaultProperties, true), paragraphProperties, maxWidth: 36);
  907. Assert.Equal(2, textLayout.TextLines.Count);
  908. var lastLine = textLayout.TextLines.Last();
  909. Assert.Equal(2, lastLine.TextRuns.Count);
  910. var lastRun = lastLine.TextRuns.Last();
  911. Assert.IsAssignableFrom<TextEndOfLine>(lastRun);
  912. }
  913. }
  914. [Fact]
  915. public void Should_Measure_TextLayoutSymbolWithAndWidthIncludingTrailingWhitespaceAndMinTextWidth()
  916. {
  917. using (Start())
  918. {
  919. var typeFace = new Typeface("Courier New");
  920. var textLayout0 = new TextLayout("aaaa", typeFace, 12.0, Brushes.White);
  921. Assert.Equal(textLayout0.WidthIncludingTrailingWhitespace, textLayout0.Width);
  922. var textLayout01 = new TextLayout("a a", typeFace, 12.0, Brushes.White);
  923. var textLayout1 = new TextLayout("a a ", typeFace, 12.0, Brushes.White);
  924. Assert.Equal(new Size(textLayout0.Width, textLayout0.Height), new Size(textLayout1.WidthIncludingTrailingWhitespace, textLayout1.Height));
  925. Assert.Equal(textLayout0.WidthIncludingTrailingWhitespace, textLayout1.WidthIncludingTrailingWhitespace);
  926. var textLayout2 = new TextLayout(" aa ", typeFace, 12.0, Brushes.White);
  927. Assert.Equal(new Size(textLayout1.Width, textLayout1.Height), new Size(textLayout2.Width, textLayout2.Height));
  928. Assert.Equal(textLayout0.WidthIncludingTrailingWhitespace, textLayout2.WidthIncludingTrailingWhitespace);
  929. Assert.Equal(textLayout01.Width, textLayout2.Width);
  930. var textLayout3 = new TextLayout(" ", typeFace, 12.0, Brushes.White);
  931. Assert.Equal(new Size(0, textLayout0.Height), new Size(textLayout3.Width, textLayout3.Height));
  932. Assert.Equal(textLayout0.WidthIncludingTrailingWhitespace, textLayout3.WidthIncludingTrailingWhitespace);
  933. Assert.Equal(0, textLayout3.Width);
  934. }
  935. }
  936. private static void AssertGreaterThan(double x, double y, string message) => Assert.True(x > y, $"{message}. {x} is not > {y}");
  937. private static IDisposable Start()
  938. {
  939. var disposable = UnitTestApplication.Start(TestServices.MockPlatformRenderInterface
  940. .With(renderInterface: new PlatformRenderInterface(null),
  941. textShaperImpl: new TextShaperImpl(),
  942. fontManagerImpl: new CustomFontManagerImpl()));
  943. return disposable;
  944. }
  945. }
  946. }