LayoutBuilder.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. #if MONOGAME || FNA
  5. using Microsoft.Xna.Framework;
  6. #elif STRIDE
  7. using Stride.Core.Mathematics;
  8. #else
  9. using System.Drawing;
  10. using Color = Veldrid.RgbaFloat;
  11. #endif
  12. namespace FontStashSharp.RichText
  13. {
  14. internal class LayoutBuilder
  15. {
  16. public const int NewLineWidth = 0;
  17. public const string Commands = "cfivst";
  18. private string _text;
  19. private SpriteFontBase _font;
  20. private bool _measureRun;
  21. private readonly List<TextLine> _lines = new List<TextLine>();
  22. private TextLine _currentLine;
  23. private int lineTop, lineBottom;
  24. private int? width;
  25. private int _lineCount;
  26. private int _currentLineWidth;
  27. private int _currentLineChunks;
  28. private readonly StringBuilder _stringBuilder = new StringBuilder();
  29. private Color? _currentColor;
  30. private SpriteFontBase _currentFont;
  31. private int _currentVerticalOffset;
  32. private TextStyle _currentTextStyle;
  33. public List<TextLine> Lines => _lines;
  34. public int VerticalSpacing { get; set; }
  35. public bool SupportsCommands { get; set; } = true;
  36. public bool CalculateGlyphs { get; set; }
  37. public bool ShiftByTop { get; set; } = true;
  38. public char CommandPrefix { get; set; } = '/';
  39. private bool IsCommand(int i)
  40. {
  41. if (!SupportsCommands ||
  42. i >= _text.Length - 2 ||
  43. _text[i] != CommandPrefix ||
  44. Commands.IndexOf(_text[i + 1]) == -1)
  45. {
  46. return false;
  47. }
  48. ++i;
  49. var command = _text[i].ToString();
  50. if (command == "t")
  51. {
  52. switch (_text[i + 1])
  53. {
  54. case 's':
  55. case 'u':
  56. case 'd':
  57. break;
  58. default:
  59. return false;
  60. }
  61. }
  62. else if (_text[i + 1] == 'd')
  63. {
  64. switch (command)
  65. {
  66. case "c":
  67. case "f":
  68. case "v":
  69. break;
  70. default:
  71. return false;
  72. }
  73. }
  74. else
  75. {
  76. if (_text[i + 1] != '[')
  77. {
  78. return false;
  79. }
  80. // Find end
  81. var startPos = i + 2;
  82. int j;
  83. var foundEnclosing = false;
  84. for (j = startPos; j < _text.Length; ++j)
  85. {
  86. if (_text[j] == ']')
  87. {
  88. // Found enclosing 'j'
  89. foundEnclosing = true;
  90. break;
  91. }
  92. else if (_text[j] == '[')
  93. {
  94. break;
  95. }
  96. }
  97. if (!foundEnclosing)
  98. {
  99. return false;
  100. }
  101. }
  102. return true;
  103. }
  104. private bool ProcessCommand(ref int i, ref ChunkInfo r, out bool chunkFilled)
  105. {
  106. chunkFilled = false;
  107. if (!IsCommand(i))
  108. {
  109. return false;
  110. }
  111. ++i;
  112. var command = _text[i].ToString();
  113. if (command == "t")
  114. {
  115. switch (_text[i + 1])
  116. {
  117. case 's':
  118. _currentTextStyle = TextStyle.Strikethrough;
  119. break;
  120. case 'u':
  121. _currentTextStyle = TextStyle.Underline;
  122. break;
  123. case 'd':
  124. _currentTextStyle = TextStyle.None;
  125. break;
  126. }
  127. i += 2;
  128. }
  129. else if (_text[i + 1] == 'd')
  130. {
  131. switch (command)
  132. {
  133. case "c":
  134. _currentColor = null;
  135. break;
  136. case "f":
  137. // Switch to default font
  138. _currentFont = _font;
  139. break;
  140. case "v":
  141. _currentVerticalOffset = 0;
  142. break;
  143. }
  144. i += 2;
  145. }
  146. else
  147. {
  148. // Find end
  149. var startPos = i + 2;
  150. int j;
  151. for (j = startPos; j < _text.Length; ++j)
  152. {
  153. if (_text[j] == ']')
  154. {
  155. // Found enclosing 'j'
  156. break;
  157. }
  158. }
  159. var parameters = _text.Substring(startPos, j - startPos);
  160. switch (command)
  161. {
  162. case "c":
  163. _currentColor = ColorStorage.FromName(parameters);
  164. break;
  165. case "f":
  166. if (RichTextDefaults.FontResolver == null)
  167. {
  168. throw new Exception($"FontResolver isnt set");
  169. }
  170. _currentFont = RichTextDefaults.FontResolver(parameters);
  171. break;
  172. case "s":
  173. var size = int.Parse(parameters);
  174. r.Type = ChunkInfoType.Space;
  175. r.X = size;
  176. r.Y = 0;
  177. r.LineEnd = false;
  178. chunkFilled = true;
  179. break;
  180. case "v":
  181. _currentVerticalOffset = int.Parse(parameters);
  182. break;
  183. case "i":
  184. if (RichTextDefaults.ImageResolver == null)
  185. {
  186. throw new Exception($"ImageResolver isnt set");
  187. }
  188. var renderable = RichTextDefaults.ImageResolver(parameters);
  189. r.Type = ChunkInfoType.Image;
  190. r.Renderable = renderable;
  191. r.LineEnd = false;
  192. chunkFilled = true;
  193. break;
  194. }
  195. i = j + 1;
  196. }
  197. return true;
  198. }
  199. private ChunkInfo GetNextChunk(ref int i, int? remainingWidth)
  200. {
  201. var r = new ChunkInfo
  202. {
  203. LineEnd = true
  204. };
  205. // Process commands at the beginning of the chunk
  206. bool chunkFilled;
  207. while (ProcessCommand(ref i, ref r, out chunkFilled))
  208. {
  209. if (chunkFilled)
  210. {
  211. // Content chunk(image or space) is filled, return it
  212. return r;
  213. }
  214. }
  215. _stringBuilder.Clear();
  216. r.StartIndex = r.EndIndex = i;
  217. Point? lastBreakMeasure = null;
  218. var lastBreakIndex = i;
  219. for (; i < _text.Length; ++i, ++r.EndIndex)
  220. {
  221. var c = _text[i];
  222. if (char.IsHighSurrogate(c))
  223. {
  224. _stringBuilder.Append(c);
  225. continue;
  226. }
  227. if (SupportsCommands &&
  228. c == CommandPrefix &&
  229. i < _text.Length - 1)
  230. {
  231. if (_text[i + 1] == 'n')
  232. {
  233. var sz2 = new Point(r.X + NewLineWidth, Math.Max(r.Y, _currentFont.LineHeight));
  234. // Break right here
  235. r.X = sz2.X;
  236. r.Y = sz2.Y;
  237. i += 2;
  238. break;
  239. }
  240. if (i < _text.Length - 1 && _text[i + 1] == CommandPrefix)
  241. {
  242. // Two '\' means one
  243. ++i; ++r.EndIndex;
  244. }
  245. else if (IsCommand(i))
  246. {
  247. // Return right here, so the command
  248. // would be processed in the next chunk
  249. r.LineEnd = false;
  250. break;
  251. }
  252. }
  253. _stringBuilder.Append(c);
  254. Point sz;
  255. if (c != '\n')
  256. {
  257. var v = _currentFont.MeasureString(_stringBuilder);
  258. sz = new Point((int)v.X, _font.LineHeight);
  259. }
  260. else
  261. {
  262. sz = new Point(r.X + NewLineWidth, Math.Max(r.Y, _font.LineHeight));
  263. // Break right here
  264. ++r.EndIndex;
  265. ++i;
  266. r.X = sz.X;
  267. r.Y = sz.Y;
  268. break;
  269. }
  270. if (remainingWidth != null && sz.X > remainingWidth.Value && i > r.StartIndex &&
  271. (lastBreakMeasure != null || _currentLineChunks == 0))
  272. {
  273. if (lastBreakMeasure != null)
  274. {
  275. r.X = lastBreakMeasure.Value.X;
  276. r.Y = lastBreakMeasure.Value.Y;
  277. r.EndIndex = i = lastBreakIndex;
  278. }
  279. break;
  280. }
  281. if (char.IsWhiteSpace(c) || c == '.')
  282. {
  283. lastBreakMeasure = sz;
  284. lastBreakIndex = i + 1;
  285. }
  286. r.X = sz.X;
  287. r.Y = sz.Y;
  288. }
  289. return r;
  290. }
  291. private void ResetCurrents()
  292. {
  293. _currentColor = null;
  294. _currentFont = _font;
  295. _currentVerticalOffset = 0;
  296. _currentTextStyle = TextStyle.None;
  297. }
  298. private void StartLine(int startIndex, int? rowWidth)
  299. {
  300. if (!_measureRun)
  301. {
  302. _currentLine = new TextLine
  303. {
  304. TextStartIndex = startIndex
  305. };
  306. }
  307. lineTop = 0;
  308. lineBottom = 0;
  309. _currentLineWidth = 0;
  310. _currentLineChunks = 0;
  311. width = rowWidth;
  312. }
  313. private void EndLine(ref Point size)
  314. {
  315. var lineHeight = lineBottom - lineTop;
  316. ++_lineCount;
  317. if (_currentLineWidth > size.X)
  318. {
  319. size.X = _currentLineWidth;
  320. }
  321. size.Y += lineHeight;
  322. if (!_measureRun)
  323. {
  324. if (ShiftByTop)
  325. {
  326. // Shift all chunks top by lineTop
  327. foreach (var lineChunk in _currentLine.Chunks)
  328. {
  329. lineChunk.VerticalOffset -= lineTop;
  330. }
  331. }
  332. _currentLine.Size.Y = lineHeight;
  333. // New line
  334. _lines.Add(_currentLine);
  335. }
  336. }
  337. public Point Layout(string text, SpriteFontBase font, int? rowWidth, bool measureRun = false)
  338. {
  339. if (!measureRun)
  340. {
  341. _lines.Clear();
  342. }
  343. _lineCount = 0;
  344. var size = Utility.PointZero;
  345. if (string.IsNullOrEmpty(text))
  346. {
  347. return size;
  348. }
  349. _text = text;
  350. _font = font;
  351. _measureRun = measureRun;
  352. ResetCurrents();
  353. var i = 0;
  354. StartLine(0, rowWidth);
  355. while (i < _text.Length)
  356. {
  357. var c = GetNextChunk(ref i, width);
  358. if (width != null && c.Width > width.Value && _currentLineChunks > 0)
  359. {
  360. // New chunk doesn't fit in the line
  361. // Hence move it to the second
  362. EndLine(ref size);
  363. StartLine(i, rowWidth);
  364. c.LineEnd = false;
  365. }
  366. width -= c.Width;
  367. if (_currentVerticalOffset < lineTop)
  368. {
  369. lineTop = _currentVerticalOffset;
  370. }
  371. if (_currentVerticalOffset + c.Height > lineBottom)
  372. {
  373. lineBottom = _currentVerticalOffset + c.Height;
  374. }
  375. _currentLineWidth += c.Width;
  376. if (!_measureRun)
  377. {
  378. Point? startPos = null;
  379. if (CalculateGlyphs)
  380. {
  381. startPos = new Point(_currentLine.Size.X, size.Y);
  382. }
  383. _currentLine.Size.X += c.Width;
  384. BaseChunk chunk = null;
  385. switch (c.Type)
  386. {
  387. case ChunkInfoType.Text:
  388. var t = _text.Substring(c.StartIndex, c.EndIndex - c.StartIndex);
  389. if (SupportsCommands)
  390. {
  391. t = t.Replace("//", "/");
  392. }
  393. var textChunk = new TextChunk(_currentFont, t, new Point(c.X, c.Y), startPos)
  394. {
  395. Style = _currentTextStyle
  396. };
  397. chunk = textChunk;
  398. break;
  399. case ChunkInfoType.Space:
  400. chunk = new SpaceChunk(c.X);
  401. break;
  402. case ChunkInfoType.Image:
  403. chunk = new ImageChunk(c.Renderable);
  404. break;
  405. }
  406. chunk.Color = _currentColor;
  407. chunk.VerticalOffset = _currentVerticalOffset;
  408. var asText = chunk as TextChunk;
  409. if (asText != null)
  410. {
  411. _currentLine.Count += asText.Count;
  412. }
  413. _currentLine.Chunks.Add(chunk);
  414. }
  415. ++_currentLineChunks;
  416. if (c.LineEnd)
  417. {
  418. EndLine(ref size);
  419. StartLine(i, rowWidth);
  420. }
  421. }
  422. // Add last line if it isnt empty
  423. if (_currentLineChunks > 0)
  424. {
  425. EndLine(ref size);
  426. }
  427. // If text ends with '\n', then add additional line
  428. if (_text[_text.Length - 1] == '\n')
  429. {
  430. var lineSize = _currentFont.MeasureString(" ");
  431. if (!_measureRun)
  432. {
  433. var additionalLine = new TextLine
  434. {
  435. TextStartIndex = _text.Length
  436. };
  437. additionalLine.Size.Y = (int)lineSize.Y;
  438. _lines.Add(additionalLine);
  439. }
  440. size.Y += (int)lineSize.Y;
  441. }
  442. // Index lines and chunks
  443. if (!_measureRun)
  444. {
  445. for (i = 0; i < _lines.Count; ++i)
  446. {
  447. _currentLine = _lines[i];
  448. _currentLine.LineIndex = i;
  449. for (var j = 0; j < _currentLine.Chunks.Count; ++j)
  450. {
  451. var chunk = _currentLine.Chunks[j];
  452. chunk.LineIndex = _currentLine.LineIndex;
  453. chunk.ChunkIndex = j;
  454. }
  455. }
  456. }
  457. size.Y += (_lineCount - 1) * VerticalSpacing;
  458. return size;
  459. }
  460. }
  461. }