TextFormatter.cs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text;
  6. namespace Terminal.Gui {
  7. /// <summary>
  8. /// Text alignment enumeration, controls how text is displayed.
  9. /// </summary>
  10. public enum TextAlignment {
  11. /// <summary>
  12. /// The text will be left-aligned.
  13. /// </summary>
  14. Left,
  15. /// <summary>
  16. /// The text will be right-aligned.
  17. /// </summary>
  18. Right,
  19. /// <summary>
  20. /// The text will be centered horizontally.
  21. /// </summary>
  22. Centered,
  23. /// <summary>
  24. /// The text will be justified (spaces will be added to existing spaces such that
  25. /// the text fills the container horizontally).
  26. /// </summary>
  27. Justified
  28. }
  29. /// <summary>
  30. /// Vertical text alignment enumeration, controls how text is displayed.
  31. /// </summary>
  32. public enum VerticalTextAlignment {
  33. /// <summary>
  34. /// The text will be top-aligned.
  35. /// </summary>
  36. Top,
  37. /// <summary>
  38. /// The text will be bottom-aligned.
  39. /// </summary>
  40. Bottom,
  41. /// <summary>
  42. /// The text will centered vertically.
  43. /// </summary>
  44. Middle,
  45. /// <summary>
  46. /// The text will be justified (spaces will be added to existing spaces such that
  47. /// the text fills the container vertically).
  48. /// </summary>
  49. Justified
  50. }
  51. /// TextDirection [H] = Horizontal [V] = Vertical
  52. /// =============
  53. /// LeftRight_TopBottom [H] Normal
  54. /// TopBottom_LeftRight [V] Normal
  55. ///
  56. /// RightLeft_TopBottom [H] Invert Text
  57. /// TopBottom_RightLeft [V] Invert Lines
  58. ///
  59. /// LeftRight_BottomTop [H] Invert Lines
  60. /// BottomTop_LeftRight [V] Invert Text
  61. ///
  62. /// RightLeft_BottomTop [H] Invert Text + Invert Lines
  63. /// BottomTop_RightLeft [V] Invert Text + Invert Lines
  64. ///
  65. /// <summary>
  66. /// Text direction enumeration, controls how text is displayed.
  67. /// </summary>
  68. public enum TextDirection {
  69. /// <summary>
  70. /// Normal horizontal direction.
  71. /// <code>HELLO<br/>WORLD</code>
  72. /// </summary>
  73. LeftRight_TopBottom,
  74. /// <summary>
  75. /// Normal vertical direction.
  76. /// <code>H W<br/>E O<br/>L R<br/>L L<br/>O D</code>
  77. /// </summary>
  78. TopBottom_LeftRight,
  79. /// <summary>
  80. /// This is a horizontal direction. <br/> RTL
  81. /// <code>OLLEH<br/>DLROW</code>
  82. /// </summary>
  83. RightLeft_TopBottom,
  84. /// <summary>
  85. /// This is a vertical direction.
  86. /// <code>W H<br/>O E<br/>R L<br/>L L<br/>D O</code>
  87. /// </summary>
  88. TopBottom_RightLeft,
  89. /// <summary>
  90. /// This is a horizontal direction.
  91. /// <code>WORLD<br/>HELLO</code>
  92. /// </summary>
  93. LeftRight_BottomTop,
  94. /// <summary>
  95. /// This is a vertical direction.
  96. /// <code>O D<br/>L L<br/>L R<br/>E O<br/>H W</code>
  97. /// </summary>
  98. BottomTop_LeftRight,
  99. /// <summary>
  100. /// This is a horizontal direction.
  101. /// <code>DLROW<br/>OLLEH</code>
  102. /// </summary>
  103. RightLeft_BottomTop,
  104. /// <summary>
  105. /// This is a vertical direction.
  106. /// <code>D O<br/>L L<br/>R L<br/>O E<br/>W H</code>
  107. /// </summary>
  108. BottomTop_RightLeft
  109. }
  110. /// <summary>
  111. /// Provides text formatting. Supports <see cref="View.HotKey"/>s, horizontal alignment, vertical alignment, multiple lines, and word-based line wrap.
  112. /// </summary>
  113. public class TextFormatter {
  114. #region Static Members
  115. static string StripCRLF (string str, bool keepNewLine = false)
  116. {
  117. var runes = str.ToRuneList ();
  118. for (int i = 0; i < runes.Count; i++) {
  119. switch ((char)runes [i].Value) {
  120. case '\n':
  121. if (!keepNewLine) {
  122. runes.RemoveAt (i);
  123. }
  124. break;
  125. case '\r':
  126. if ((i + 1) < runes.Count && runes [i + 1].Value == '\n') {
  127. runes.RemoveAt (i);
  128. if (!keepNewLine) {
  129. runes.RemoveAt (i);
  130. }
  131. i++;
  132. } else {
  133. if (!keepNewLine) {
  134. runes.RemoveAt (i);
  135. }
  136. }
  137. break;
  138. }
  139. }
  140. return StringExtensions.ToString (runes);
  141. }
  142. static string ReplaceCRLFWithSpace (string str)
  143. {
  144. var runes = str.ToRuneList ();
  145. for (int i = 0; i < runes.Count; i++) {
  146. switch (runes [i].Value) {
  147. case '\n':
  148. runes [i] = (Rune)' ';
  149. break;
  150. case '\r':
  151. if ((i + 1) < runes.Count && runes [i + 1].Value == '\n') {
  152. runes [i] = (Rune)' ';
  153. runes.RemoveAt (i + 1);
  154. i++;
  155. } else {
  156. runes [i] = (Rune)' ';
  157. }
  158. break;
  159. }
  160. }
  161. return StringExtensions.ToString (runes);
  162. }
  163. /// <summary>
  164. /// Splits all newlines in the <paramref name="text"/> into a list
  165. /// and supports both CRLF and LF, preserving the ending newline.
  166. /// </summary>
  167. /// <param name="text">The text.</param>
  168. /// <returns>A list of text without the newline characters.</returns>
  169. public static List<string> SplitNewLine (string text)
  170. {
  171. var runes = text.ToRuneList ();
  172. var lines = new List<string> ();
  173. var start = 0;
  174. var end = 0;
  175. for (int i = 0; i < runes.Count; i++) {
  176. end = i;
  177. switch (runes [i].Value) {
  178. case '\n':
  179. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  180. i++;
  181. start = i;
  182. break;
  183. case '\r':
  184. if ((i + 1) < runes.Count && runes [i + 1].Value == '\n') {
  185. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  186. i += 2;
  187. start = i;
  188. } else {
  189. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  190. i++;
  191. start = i;
  192. }
  193. break;
  194. }
  195. }
  196. if (runes.Count > 0 && lines.Count == 0) {
  197. lines.Add (StringExtensions.ToString (runes));
  198. } else if (runes.Count > 0 && start < runes.Count) {
  199. lines.Add (StringExtensions.ToString (runes.GetRange (start, runes.Count - start)));
  200. } else {
  201. lines.Add ("");
  202. }
  203. return lines;
  204. }
  205. /// <summary>
  206. /// Adds trailing whitespace or truncates <paramref name="text"/>
  207. /// so that it fits exactly <paramref name="width"/> console units.
  208. /// Note that some unicode characters take 2+ columns
  209. /// </summary>
  210. /// <param name="text"></param>
  211. /// <param name="width"></param>
  212. /// <returns></returns>
  213. public static string ClipOrPad (string text, int width)
  214. {
  215. if (string.IsNullOrEmpty (text))
  216. return text;
  217. // if value is not wide enough
  218. if (text.EnumerateRunes ().Sum (c => c.GetColumns ()) < width) {
  219. // pad it out with spaces to the given alignment
  220. int toPad = width - (text.EnumerateRunes ().Sum (c => c.GetColumns ()));
  221. return text + new string (' ', toPad);
  222. }
  223. // value is too wide
  224. return new string (text.TakeWhile (c => (width -= ((Rune)c).GetColumns ()) >= 0).ToArray ());
  225. }
  226. /// <summary>
  227. /// Formats the provided text to fit within the width provided using word wrapping.
  228. /// </summary>
  229. /// <param name="text">The text to word wrap</param>
  230. /// <param name="width">The number of columns to constrain the text to</param>
  231. /// <param name="preserveTrailingSpaces">If <see langword="true"/> trailing spaces at the end of wrapped lines will be preserved.
  232. /// If <see langword="false"/>, trailing spaces at the end of wrapped lines will be trimmed.</param>
  233. /// <param name="tabWidth">The number of columns used for a tab.</param>
  234. /// <param name="textDirection">The text direction.</param>
  235. /// <returns>A list of word wrapped lines.</returns>
  236. /// <remarks>
  237. /// <para>
  238. /// This method does not do any justification.
  239. /// </para>
  240. /// <para>
  241. /// This method strips Newline ('\n' and '\r\n') sequences before processing.
  242. /// </para>
  243. /// <para>
  244. /// If <paramref name="preserveTrailingSpaces"/> is <see langword="false"/> at most one space will be preserved at the end of the last line.
  245. /// </para>
  246. /// </remarks>
  247. public static List<string> WordWrapText (string text, int width, bool preserveTrailingSpaces = false, int tabWidth = 0,
  248. TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  249. {
  250. if (width < 0) {
  251. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  252. }
  253. int start = 0, end;
  254. var lines = new List<string> ();
  255. if (string.IsNullOrEmpty (text)) {
  256. return lines;
  257. }
  258. var runes = StripCRLF (text).ToRuneList ();
  259. if (preserveTrailingSpaces) {
  260. while ((end = start) < runes.Count) {
  261. end = GetNextWhiteSpace (start, width, out bool incomplete);
  262. if (end == 0 && incomplete) {
  263. start = text.GetRuneCount ();
  264. break;
  265. }
  266. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  267. start = end;
  268. if (incomplete) {
  269. start = text.GetRuneCount ();
  270. break;
  271. }
  272. }
  273. } else {
  274. if (IsHorizontalDirection (textDirection)) {
  275. //if (GetLengthThatFits (runes.GetRange (start, runes.Count - start), width) > 0) {
  276. // // while there's still runes left and end is not past end...
  277. // while (start < runes.Count &&
  278. // (end = start + Math.Max (GetLengthThatFits (runes.GetRange (start, runes.Count - start), width) - 1, 0)) < runes.Count) {
  279. // // end now points to start + LengthThatFits
  280. // // Walk back over trailing spaces
  281. // while (runes [end] == ' ' && end > start) {
  282. // end--;
  283. // }
  284. // // end now points to start + LengthThatFits - any trailing spaces; start saving new line
  285. // var line = runes.GetRange (start, end - start + 1);
  286. // if (end == start && width > 1) {
  287. // // it was all trailing spaces; now walk forward to next non-space
  288. // do {
  289. // start++;
  290. // } while (start < runes.Count && runes [start] == ' ');
  291. // // start now points to first non-space we haven't seen yet or we're done
  292. // if (start < runes.Count) {
  293. // // we're not done. we have remaining = width - line.Count columns left;
  294. // var remaining = width - line.Count;
  295. // if (remaining > 1) {
  296. // // add a space for all the spaces we walked over
  297. // line.Add (' ');
  298. // }
  299. // var count = GetLengthThatFits (runes.GetRange (start, runes.Count - start), width - line.Count);
  300. // // [start..count] now has rest of line
  301. // line.AddRange (runes.GetRange (start, count));
  302. // start += count;
  303. // }
  304. // } else {
  305. // start += line.Count;
  306. // }
  307. // //// if the previous line was just a ' ' and the new line is just a ' '
  308. // //// don't add new line
  309. // //if (line [0] == ' ' && (lines.Count > 0 && lines [lines.Count - 1] [0] == ' ')) {
  310. // //} else {
  311. // //}
  312. // lines.Add (string.Make (line));
  313. // // move forward to next non-space
  314. // while (width > 1 && start < runes.Count && runes [start] == ' ') {
  315. // start++;
  316. // }
  317. // }
  318. //}
  319. while ((end = start + Math.Max (GetLengthThatFits (runes.GetRange (start, runes.Count - start), width), 1)) < runes.Count) {
  320. while (runes [end].Value != ' ' && end > start)
  321. end--;
  322. if (end == start)
  323. end = start + GetLengthThatFits (runes.GetRange (end, runes.Count - end), width);
  324. var str = StringExtensions.ToString (runes.GetRange (start, end - start));
  325. if (end > start && str.GetColumns () <= width) {
  326. lines.Add (str);
  327. start = end;
  328. if (runes [end].Value == ' ') {
  329. start++;
  330. }
  331. } else {
  332. end++;
  333. start = end;
  334. }
  335. }
  336. } else {
  337. while ((end = start + width) < runes.Count) {
  338. while (runes [end].Value != ' ' && end > start) {
  339. end--;
  340. }
  341. if (end == start) {
  342. end = start + width;
  343. }
  344. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  345. start = end;
  346. if (runes [end].Value == ' ') {
  347. start++;
  348. }
  349. }
  350. }
  351. }
  352. int GetNextWhiteSpace (int from, int cWidth, out bool incomplete, int cLength = 0)
  353. {
  354. var lastFrom = from;
  355. var to = from;
  356. var length = cLength;
  357. incomplete = false;
  358. while (length < cWidth && to < runes.Count) {
  359. var rune = runes [to];
  360. if (IsHorizontalDirection (textDirection)) {
  361. length += rune.GetColumns ();
  362. } else {
  363. length++;
  364. }
  365. if (length > cWidth) {
  366. if (to >= runes.Count || (length > 1 && cWidth <= 1)) {
  367. incomplete = true;
  368. }
  369. return to;
  370. }
  371. if (rune.Value == ' ') {
  372. if (length == cWidth) {
  373. return to + 1;
  374. } else if (length > cWidth) {
  375. return to;
  376. } else {
  377. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  378. }
  379. } else if (rune.Value == '\t') {
  380. length += tabWidth + 1;
  381. if (length == tabWidth && tabWidth > cWidth) {
  382. return to + 1;
  383. } else if (length > cWidth && tabWidth > cWidth) {
  384. return to;
  385. } else {
  386. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  387. }
  388. }
  389. to++;
  390. }
  391. if (cLength > 0 && to < runes.Count && runes [to].Value != ' ' && runes [to].Value != '\t') {
  392. return from;
  393. } else if (cLength > 0 && to < runes.Count && (runes [to].Value == ' ' || runes [to].Value == '\t')) {
  394. return lastFrom;
  395. } else {
  396. return to;
  397. }
  398. }
  399. if (start < text.GetRuneCount ()) {
  400. var str = StringExtensions.ToString (runes.GetRange (start, runes.Count - start));
  401. if (IsVerticalDirection (textDirection) || preserveTrailingSpaces || (!preserveTrailingSpaces && str.GetColumns () <= width)) {
  402. lines.Add (str);
  403. }
  404. }
  405. return lines;
  406. }
  407. /// <summary>
  408. /// Justifies text within a specified width.
  409. /// </summary>
  410. /// <param name="text">The text to justify.</param>
  411. /// <param name="width">The number of columns to clip the text to. Text longer than <paramref name="width"/> will be clipped.</param>
  412. /// <param name="talign">Alignment.</param>
  413. /// <param name="textDirection">The text direction.</param>
  414. /// <returns>Justified and clipped text.</returns>
  415. public static string ClipAndJustify (string text, int width, TextAlignment talign, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  416. {
  417. return ClipAndJustify (text, width, talign == TextAlignment.Justified, textDirection);
  418. }
  419. /// <summary>
  420. /// Justifies text within a specified width.
  421. /// </summary>
  422. /// <param name="text">The text to justify.</param>
  423. /// <param name="width">The number of columns to clip the text to. Text longer than <paramref name="width"/> will be clipped.</param>
  424. /// <param name="justify">Justify.</param>
  425. /// <param name="textDirection">The text direction.</param>
  426. /// <returns>Justified and clipped text.</returns>
  427. public static string ClipAndJustify (string text, int width, bool justify, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  428. {
  429. if (width < 0) {
  430. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  431. }
  432. if (string.IsNullOrEmpty (text)) {
  433. return text;
  434. }
  435. var runes = text.ToRuneList ();
  436. int slen = runes.Count;
  437. if (slen > width) {
  438. if (IsHorizontalDirection (textDirection)) {
  439. return StringExtensions.ToString (runes.GetRange (0, GetLengthThatFits (text, width)));
  440. } else {
  441. return StringExtensions.ToString (runes.GetRange (0, width));
  442. }
  443. } else {
  444. if (justify) {
  445. return Justify (text, width, ' ', textDirection);
  446. } else if (IsHorizontalDirection (textDirection) && text.GetColumns () > width) {
  447. return StringExtensions.ToString (runes.GetRange (0, GetLengthThatFits (text, width)));
  448. }
  449. return text;
  450. }
  451. }
  452. /// <summary>
  453. /// Justifies the text to fill the width provided. Space will be added between words (demarked by spaces and tabs) to
  454. /// make the text just fit <c>width</c>. Spaces will not be added to the ends.
  455. /// </summary>
  456. /// <param name="text"></param>
  457. /// <param name="width"></param>
  458. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  459. /// <param name="textDirection">The text direction.</param>
  460. /// <returns>The justified text.</returns>
  461. public static string Justify (string text, int width, char spaceChar = ' ', TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  462. {
  463. if (width < 0) {
  464. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  465. }
  466. if (string.IsNullOrEmpty (text)) {
  467. return text;
  468. }
  469. var words = text.Split (' ');
  470. int textCount;
  471. if (IsHorizontalDirection (textDirection)) {
  472. textCount = words.Sum (arg => arg.GetColumns ());
  473. } else {
  474. textCount = words.Sum (arg => arg.GetRuneCount ());
  475. }
  476. var spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  477. var extras = words.Length > 1 ? (width - textCount) % (words.Length - 1) : 0;
  478. var s = new System.Text.StringBuilder ();
  479. for (int w = 0; w < words.Length; w++) {
  480. var x = words [w];
  481. s.Append (x);
  482. if (w + 1 < words.Length)
  483. for (int i = 0; i < spaces; i++)
  484. s.Append (spaceChar);
  485. if (extras > 0) {
  486. for (int i = 0; i < 1; i++)
  487. s.Append (spaceChar);
  488. extras--;
  489. }
  490. if (w + 1 == words.Length - 1) {
  491. for (int i = 0; i < extras; i++)
  492. s.Append (spaceChar);
  493. }
  494. }
  495. return s.ToString ();
  496. }
  497. static char [] whitespace = new char [] { ' ', '\t' };
  498. /// <summary>
  499. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  500. /// </summary>
  501. /// <param name="text"></param>
  502. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  503. /// <param name="talign">Specifies how the text will be aligned horizontally.</param>
  504. /// <param name="wordWrap">If <see langword="true"/>, the text will be wrapped to new lines no longer than <paramref name="width"/>.
  505. /// If <see langword="false"/>, forces text to fit a single line. Line breaks are converted to spaces. The text will be clipped to <paramref name="width"/>.</param>
  506. /// <param name="preserveTrailingSpaces">If <see langword="true"/> trailing spaces at the end of wrapped lines will be preserved.
  507. /// If <see langword="false"/>, trailing spaces at the end of wrapped lines will be trimmed.</param>
  508. /// <param name="tabWidth">The number of columns used for a tab.</param>
  509. /// <param name="textDirection">The text direction.</param>
  510. /// <returns>A list of word wrapped lines.</returns>
  511. /// <remarks>
  512. /// <para>
  513. /// An empty <paramref name="text"/> string will result in one empty line.
  514. /// </para>
  515. /// <para>
  516. /// If <paramref name="width"/> is 0, a single, empty line will be returned.
  517. /// </para>
  518. /// <para>
  519. /// If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.
  520. /// </para>
  521. /// </remarks>
  522. public static List<string> Format (string text, int width, TextAlignment talign, bool wordWrap, bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  523. {
  524. return Format (text, width, talign == TextAlignment.Justified, wordWrap, preserveTrailingSpaces, tabWidth, textDirection);
  525. }
  526. /// <summary>
  527. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  528. /// </summary>
  529. /// <param name="text"></param>
  530. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  531. /// <param name="justify">Specifies whether the text should be justified.</param>
  532. /// <param name="wordWrap">If <see langword="true"/>, the text will be wrapped to new lines no longer than <paramref name="width"/>.
  533. /// If <see langword="false"/>, forces text to fit a single line. Line breaks are converted to spaces. The text will be clipped to <paramref name="width"/>.</param>
  534. /// <param name="preserveTrailingSpaces">If <see langword="true"/> trailing spaces at the end of wrapped lines will be preserved.
  535. /// If <see langword="false"/>, trailing spaces at the end of wrapped lines will be trimmed.</param>
  536. /// <param name="tabWidth">The number of columns used for a tab.</param>
  537. /// <param name="textDirection">The text direction.</param>
  538. /// <returns>A list of word wrapped lines.</returns>
  539. /// <remarks>
  540. /// <para>
  541. /// An empty <paramref name="text"/> string will result in one empty line.
  542. /// </para>
  543. /// <para>
  544. /// If <paramref name="width"/> is 0, a single, empty line will be returned.
  545. /// </para>
  546. /// <para>
  547. /// If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.
  548. /// </para>
  549. /// </remarks>
  550. public static List<string> Format (string text, int width, bool justify, bool wordWrap,
  551. bool preserveTrailingSpaces = false, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  552. {
  553. if (width < 0) {
  554. throw new ArgumentOutOfRangeException ("width cannot be negative");
  555. }
  556. List<string> lineResult = new List<string> ();
  557. if (string.IsNullOrEmpty (text) || width == 0) {
  558. lineResult.Add (string.Empty);
  559. return lineResult;
  560. }
  561. if (wordWrap == false) {
  562. text = ReplaceCRLFWithSpace (text);
  563. lineResult.Add (ClipAndJustify (text, width, justify, textDirection));
  564. return lineResult;
  565. }
  566. var runes = StripCRLF (text, true).ToRuneList ();
  567. int runeCount = runes.Count;
  568. int lp = 0;
  569. for (int i = 0; i < runeCount; i++) {
  570. Rune c = runes [i];
  571. if (c.Value == '\n') {
  572. var wrappedLines = WordWrapText (StringExtensions.ToString (runes.GetRange (lp, i - lp)), width, preserveTrailingSpaces, tabWidth, textDirection);
  573. foreach (var line in wrappedLines) {
  574. lineResult.Add (ClipAndJustify (line, width, justify, textDirection));
  575. }
  576. if (wrappedLines.Count == 0) {
  577. lineResult.Add (string.Empty);
  578. }
  579. lp = i + 1;
  580. }
  581. }
  582. foreach (var line in WordWrapText (StringExtensions.ToString (runes.GetRange (lp, runeCount - lp)), width, preserveTrailingSpaces, tabWidth, textDirection)) {
  583. lineResult.Add (ClipAndJustify (line, width, justify, textDirection));
  584. }
  585. return lineResult;
  586. }
  587. /// <summary>
  588. /// Computes the number of lines needed to render the specified text given the width.
  589. /// </summary>
  590. /// <returns>Number of lines.</returns>
  591. /// <param name="text">Text, may contain newlines.</param>
  592. /// <param name="width">The minimum width for the text.</param>
  593. public static int MaxLines (string text, int width)
  594. {
  595. var result = TextFormatter.Format (text, width, false, true);
  596. return result.Count;
  597. }
  598. /// <summary>
  599. /// Computes the maximum width needed to render the text (single line or multiple lines, word wrapped) given
  600. /// a number of columns to constrain the text to.
  601. /// </summary>
  602. /// <returns>Width of the longest line after formatting the text constrained by <paramref name="maxColumns"/>.</returns>
  603. /// <param name="text">Text, may contain newlines.</param>
  604. /// <param name="maxColumns">The number of columns to constrain the text to for formatting.</param>
  605. public static int MaxWidth (string text, int maxColumns)
  606. {
  607. var result = TextFormatter.Format (text: text, width: maxColumns, justify: false, wordWrap: true);
  608. var max = 0;
  609. result.ForEach (s => {
  610. var m = 0;
  611. s.ToRuneList ().ForEach (r => m += Math.Max (r.GetColumns (), 1));
  612. if (m > max) {
  613. max = m;
  614. }
  615. });
  616. return max;
  617. }
  618. /// <summary>
  619. /// Returns the width of the widest line in the text, accounting for wide-glyphs (uses <see cref="StringExtensions.GetColumns"/>).
  620. /// <paramref name="text"/> if it contains newlines.
  621. /// </summary>
  622. /// <param name="text">Text, may contain newlines.</param>
  623. /// <returns>The length of the longest line.</returns>
  624. public static int MaxWidthLine (string text)
  625. {
  626. var result = TextFormatter.SplitNewLine (text);
  627. return result.Max (x => x.GetColumns ());
  628. }
  629. /// <summary>
  630. /// Gets the maximum characters width from the list based on the <paramref name="startIndex"/>
  631. /// and the <paramref name="length"/>.
  632. /// </summary>
  633. /// <param name="lines">The lines.</param>
  634. /// <param name="startIndex">The start index.</param>
  635. /// <param name="length">The length.</param>
  636. /// <returns>The maximum characters width.</returns>
  637. public static int GetSumMaxCharWidth (List<string> lines, int startIndex = -1, int length = -1)
  638. {
  639. var max = 0;
  640. for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? lines.Count : startIndex + length); i++) {
  641. var runes = lines [i];
  642. if (runes.Length > 0)
  643. max += runes.EnumerateRunes ().Max (r => Math.Max (r.GetColumns (), 1));
  644. }
  645. return max;
  646. }
  647. /// <summary>
  648. /// Gets the maximum characters width from the text based on the <paramref name="startIndex"/>
  649. /// and the <paramref name="length"/>.
  650. /// </summary>
  651. /// <param name="text">The text.</param>
  652. /// <param name="startIndex">The start index.</param>
  653. /// <param name="length">The length.</param>
  654. /// <returns>The maximum characters width.</returns>
  655. public static int GetSumMaxCharWidth (string text, int startIndex = -1, int length = -1)
  656. {
  657. var max = 0;
  658. var runes = text.ToRunes ();
  659. for (int i = (startIndex == -1 ? 0 : startIndex); i < (length == -1 ? runes.Length : startIndex + length); i++) {
  660. max += Math.Max (runes [i].GetColumns (), 1);
  661. }
  662. return max;
  663. }
  664. /// <summary>
  665. /// Gets the number of the Runes in a <see cref="string"/> that will fit in <paramref name="columns"/>.
  666. /// </summary>
  667. /// <param name="text">The text.</param>
  668. /// <param name="columns">The width.</param>
  669. /// <returns>The index of the text that fit the width.</returns>
  670. public static int GetLengthThatFits (string text, int columns) => GetLengthThatFits (text?.ToRuneList (), columns);
  671. /// <summary>
  672. /// Gets the number of the Runes in a list of Runes that will fit in <paramref name="columns"/>.
  673. /// </summary>
  674. /// <param name="runes">The list of runes.</param>
  675. /// <param name="columns">The width.</param>
  676. /// <returns>The index of the last Rune in <paramref name="runes"/> that fit in <paramref name="columns"/>.</returns>
  677. public static int GetLengthThatFits (List<Rune> runes, int columns)
  678. {
  679. if (runes == null || runes.Count == 0) {
  680. return 0;
  681. }
  682. var runesLength = 0;
  683. var runeIdx = 0;
  684. for (; runeIdx < runes.Count; runeIdx++) {
  685. var runeWidth = Math.Max (runes [runeIdx].GetColumns (), 1);
  686. if (runesLength + runeWidth > columns) {
  687. break;
  688. }
  689. runesLength += runeWidth;
  690. }
  691. return runeIdx;
  692. }
  693. /// <summary>
  694. /// Gets the index position from the list based on the <paramref name="width"/>.
  695. /// </summary>
  696. /// <param name="lines">The lines.</param>
  697. /// <param name="width">The width.</param>
  698. /// <returns>The index of the list that fit the width.</returns>
  699. public static int GetMaxColsForWidth (List<string> lines, int width)
  700. {
  701. var runesLength = 0;
  702. var lineIdx = 0;
  703. for (; lineIdx < lines.Count; lineIdx++) {
  704. var runes = lines [lineIdx].ToRuneList ();
  705. var maxRruneWidth = runes.Count > 0
  706. ? runes.Max (r => Math.Max (r.GetColumns (), 1)) : 1;
  707. if (runesLength + maxRruneWidth > width) {
  708. break;
  709. }
  710. runesLength += maxRruneWidth;
  711. }
  712. return lineIdx;
  713. }
  714. /// <summary>
  715. /// Calculates the rectangle required to hold text, assuming no word wrapping or justification.
  716. /// </summary>
  717. /// <param name="x">The x location of the rectangle</param>
  718. /// <param name="y">The y location of the rectangle</param>
  719. /// <param name="text">The text to measure</param>
  720. /// <param name="direction">The text direction.</param>
  721. /// <returns></returns>
  722. public static Rect CalcRect (int x, int y, string text, TextDirection direction = TextDirection.LeftRight_TopBottom)
  723. {
  724. if (string.IsNullOrEmpty (text)) {
  725. return new Rect (new Point (x, y), Size.Empty);
  726. }
  727. int w, h;
  728. if (IsHorizontalDirection (direction)) {
  729. int mw = 0;
  730. int ml = 1;
  731. int cols = 0;
  732. foreach (var rune in text.EnumerateRunes ()) {
  733. if (rune.Value == '\n') {
  734. ml++;
  735. if (cols > mw) {
  736. mw = cols;
  737. }
  738. cols = 0;
  739. } else if (rune.Value != '\r') {
  740. cols++;
  741. var rw = ((Rune)rune).GetColumns ();
  742. if (rw > 0) {
  743. rw--;
  744. }
  745. cols += rw;
  746. }
  747. }
  748. if (cols > mw) {
  749. mw = cols;
  750. }
  751. w = mw;
  752. h = ml;
  753. } else {
  754. int vw = 1, cw = 1;
  755. int vh = 0;
  756. int rows = 0;
  757. foreach (var rune in text.EnumerateRunes ()) {
  758. if (rune.Value == '\n') {
  759. vw++;
  760. if (rows > vh) {
  761. vh = rows;
  762. }
  763. rows = 0;
  764. cw = 1;
  765. } else if (rune.Value != '\r') {
  766. rows++;
  767. var rw = ((Rune)rune).GetColumns ();
  768. if (cw < rw) {
  769. cw = rw;
  770. vw++;
  771. }
  772. }
  773. }
  774. if (rows > vh) {
  775. vh = rows;
  776. }
  777. w = vw;
  778. h = vh;
  779. }
  780. return new Rect (x, y, w, h);
  781. }
  782. /// <summary>
  783. /// Finds the hotkey and its location in text.
  784. /// </summary>
  785. /// <param name="text">The text to look in.</param>
  786. /// <param name="hotKeySpecifier">The hotkey specifier (e.g. '_') to look for.</param>
  787. /// <param name="firstUpperCase">If <c>true</c> the legacy behavior of identifying the first upper case character as the hotkey will be enabled.
  788. /// Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.</param>
  789. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  790. /// <param name="hotKey">Outputs the hotKey.</param>
  791. /// <returns><c>true</c> if a hotkey was found; <c>false</c> otherwise.</returns>
  792. public static bool FindHotKey (string text, Rune hotKeySpecifier, bool firstUpperCase, out int hotPos, out Key hotKey)
  793. {
  794. if (string.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF) {
  795. hotPos = -1;
  796. hotKey = Key.Unknown;
  797. return false;
  798. }
  799. Rune hot_key = (Rune)0;
  800. int hot_pos = -1;
  801. // Use first hot_key char passed into 'hotKey'.
  802. // TODO: Ignore hot_key of two are provided
  803. // TODO: Do not support non-alphanumeric chars that can't be typed
  804. int i = 0;
  805. foreach (Rune c in text.EnumerateRunes ()) {
  806. if ((char)c.Value != 0xFFFD) {
  807. if (c == hotKeySpecifier) {
  808. hot_pos = i;
  809. } else if (hot_pos > -1) {
  810. hot_key = c;
  811. break;
  812. }
  813. }
  814. i++;
  815. }
  816. // Legacy support - use first upper case char if the specifier was not found
  817. if (hot_pos == -1 && firstUpperCase) {
  818. i = 0;
  819. foreach (Rune c in text.EnumerateRunes ()) {
  820. if ((char)c.Value != 0xFFFD) {
  821. if (Rune.IsUpper (c)) {
  822. hot_key = c;
  823. hot_pos = i;
  824. break;
  825. }
  826. }
  827. i++;
  828. }
  829. }
  830. if (hot_key != (Rune)0 && hot_pos != -1) {
  831. hotPos = hot_pos;
  832. if (Rune.IsValid (hot_key.Value) && char.IsLetterOrDigit ((char)hot_key.Value)) {
  833. hotKey = (Key)char.ToUpperInvariant ((char)hot_key.Value);
  834. return true;
  835. }
  836. }
  837. hotPos = -1;
  838. hotKey = Key.Unknown;
  839. return false;
  840. }
  841. /// <summary>
  842. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying
  843. /// it as the hotkey.
  844. /// </summary>
  845. /// <param name="text">The text to tag the hotkey in.</param>
  846. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  847. /// <returns>The text with the hotkey tagged.</returns>
  848. /// <remarks>
  849. /// The returned string will not render correctly without first un-doing the tag. To undo the tag, search for
  850. /// </remarks>
  851. public string ReplaceHotKeyWithTag (string text, int hotPos)
  852. {
  853. // Set the high bit
  854. var runes = text.ToRuneList ();
  855. if (Rune.IsLetterOrDigit (runes [hotPos])) {
  856. runes [hotPos] = new Rune ((uint)runes [hotPos].Value);
  857. }
  858. return StringExtensions.ToString (runes);
  859. }
  860. /// <summary>
  861. /// Removes the hotkey specifier from text.
  862. /// </summary>
  863. /// <param name="text">The text to manipulate.</param>
  864. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  865. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  866. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  867. public static string RemoveHotKeySpecifier (string text, int hotPos, Rune hotKeySpecifier)
  868. {
  869. if (string.IsNullOrEmpty (text)) {
  870. return text;
  871. }
  872. // Scan
  873. string start = string.Empty;
  874. int i = 0;
  875. foreach (Rune c in text) {
  876. if (c == hotKeySpecifier && i == hotPos) {
  877. i++;
  878. continue;
  879. }
  880. start += c;
  881. i++;
  882. }
  883. return start;
  884. }
  885. #endregion // Static Members
  886. List<string> _lines = new List<string> ();
  887. string _text;
  888. TextAlignment _textAlignment;
  889. VerticalTextAlignment _textVerticalAlignment;
  890. TextDirection _textDirection;
  891. Key _hotKey;
  892. int _hotKeyPos = -1;
  893. Size _size;
  894. /// <summary>
  895. /// Event invoked when the <see cref="HotKey"/> is changed.
  896. /// </summary>
  897. public event EventHandler<KeyChangedEventArgs> HotKeyChanged;
  898. /// <summary>
  899. /// The text to be displayed. This string is never modified.
  900. /// </summary>
  901. public virtual string Text {
  902. get => _text;
  903. set {
  904. _text = value;
  905. if (_text != null && _text.GetRuneCount () > 0 && (Size.Width == 0 || Size.Height == 0 || Size.Width != _text.GetColumns ())) {
  906. // Provide a default size (width = length of longest line, height = 1)
  907. // TODO: It might makes more sense for the default to be width = length of first line?
  908. Size = new Size (TextFormatter.MaxWidth (Text, int.MaxValue), 1);
  909. }
  910. NeedsFormat = true;
  911. }
  912. }
  913. /// <summary>
  914. /// Used by <see cref="Text"/> to resize the view's <see cref="View.Bounds"/> with the <see cref="Size"/>.
  915. /// Setting <see cref="AutoSize"/> to true only work if the <see cref="View.Width"/> and <see cref="View.Height"/> are null or
  916. /// <see cref="LayoutStyle.Absolute"/> values and doesn't work with <see cref="LayoutStyle.Computed"/> layout,
  917. /// to avoid breaking the <see cref="Pos"/> and <see cref="Dim"/> settings.
  918. /// </summary>
  919. public bool AutoSize { get; set; }
  920. /// <summary>
  921. /// Gets or sets whether trailing spaces at the end of word-wrapped lines are preserved
  922. /// or not when <see cref="TextFormatter.WordWrap"/> is enabled.
  923. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be removed when
  924. /// <see cref="Text"/> is formatted for display. The default is <see langword="false"/>.
  925. /// </summary>
  926. public bool PreserveTrailingSpaces { get; set; }
  927. /// <summary>
  928. /// Controls the horizontal text-alignment property.
  929. /// </summary>
  930. /// <value>The text alignment.</value>
  931. public TextAlignment Alignment {
  932. get => _textAlignment;
  933. set {
  934. _textAlignment = value;
  935. NeedsFormat = true;
  936. }
  937. }
  938. /// <summary>
  939. /// Controls the vertical text-alignment property.
  940. /// </summary>
  941. /// <value>The text vertical alignment.</value>
  942. public VerticalTextAlignment VerticalAlignment {
  943. get => _textVerticalAlignment;
  944. set {
  945. _textVerticalAlignment = value;
  946. NeedsFormat = true;
  947. }
  948. }
  949. /// <summary>
  950. /// Controls the text-direction property.
  951. /// </summary>
  952. /// <value>The text vertical alignment.</value>
  953. public TextDirection Direction {
  954. get => _textDirection;
  955. set {
  956. _textDirection = value;
  957. NeedsFormat = true;
  958. }
  959. }
  960. /// <summary>
  961. /// Check if it is a horizontal direction
  962. /// </summary>
  963. public static bool IsHorizontalDirection (TextDirection textDirection)
  964. {
  965. switch (textDirection) {
  966. case TextDirection.LeftRight_TopBottom:
  967. case TextDirection.LeftRight_BottomTop:
  968. case TextDirection.RightLeft_TopBottom:
  969. case TextDirection.RightLeft_BottomTop:
  970. return true;
  971. default:
  972. return false;
  973. }
  974. }
  975. /// <summary>
  976. /// Check if it is a vertical direction
  977. /// </summary>
  978. public static bool IsVerticalDirection (TextDirection textDirection)
  979. {
  980. switch (textDirection) {
  981. case TextDirection.TopBottom_LeftRight:
  982. case TextDirection.TopBottom_RightLeft:
  983. case TextDirection.BottomTop_LeftRight:
  984. case TextDirection.BottomTop_RightLeft:
  985. return true;
  986. default:
  987. return false;
  988. }
  989. }
  990. /// <summary>
  991. /// Check if it is Left to Right direction
  992. /// </summary>
  993. public static bool IsLeftToRight (TextDirection textDirection)
  994. {
  995. switch (textDirection) {
  996. case TextDirection.LeftRight_TopBottom:
  997. case TextDirection.LeftRight_BottomTop:
  998. return true;
  999. default:
  1000. return false;
  1001. }
  1002. }
  1003. /// <summary>
  1004. /// Check if it is Top to Bottom direction
  1005. /// </summary>
  1006. public static bool IsTopToBottom (TextDirection textDirection)
  1007. {
  1008. switch (textDirection) {
  1009. case TextDirection.TopBottom_LeftRight:
  1010. case TextDirection.TopBottom_RightLeft:
  1011. return true;
  1012. default:
  1013. return false;
  1014. }
  1015. }
  1016. // TODO: This is not implemented!
  1017. /// <summary>
  1018. ///
  1019. /// </summary>
  1020. public bool WordWrap { get; set; } = false;
  1021. /// <summary>
  1022. /// Gets or sets the size of the area the text will be constrained to when formatted.
  1023. /// </summary>
  1024. /// <remarks>
  1025. /// Does not return the size the formatted text; just the value that was set.
  1026. /// </remarks>
  1027. public Size Size {
  1028. get {
  1029. return _size;
  1030. }
  1031. set {
  1032. _size = value;
  1033. NeedsFormat = true;
  1034. }
  1035. }
  1036. /// <summary>
  1037. /// The specifier character for the hotkey (e.g. '_'). Set to '\xffff' to disable hotkey support for this View instance. The default is '\xffff'.
  1038. /// </summary>
  1039. public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
  1040. /// <summary>
  1041. /// The position in the text of the hotkey. The hotkey will be rendered using the hot color.
  1042. /// </summary>
  1043. public int HotKeyPos { get => _hotKeyPos; set => _hotKeyPos = value; }
  1044. /// <summary>
  1045. /// Gets the hotkey. Will be an upper case letter or digit.
  1046. /// </summary>
  1047. public Key HotKey {
  1048. get => _hotKey;
  1049. internal set {
  1050. if (_hotKey != value) {
  1051. var oldKey = _hotKey;
  1052. _hotKey = value;
  1053. HotKeyChanged?.Invoke (this, new KeyChangedEventArgs (oldKey, value));
  1054. }
  1055. }
  1056. }
  1057. /// <summary>
  1058. /// Gets the cursor position from <see cref="HotKey"/>. If the <see cref="HotKey"/> is defined, the cursor will be positioned over it.
  1059. /// </summary>
  1060. public int CursorPosition { get; set; }
  1061. /// <summary>
  1062. /// Gets the size required to hold the formatted text, given the constraints placed by <see cref="Size"/>.
  1063. /// </summary>
  1064. /// <remarks>
  1065. /// Causes a format, resetting <see cref="NeedsFormat"/>.
  1066. /// </remarks>
  1067. /// <returns></returns>
  1068. public Size GetFormattedSize ()
  1069. {
  1070. var lines = Lines;
  1071. var width = Lines.Max (line => line.GetColumns ());
  1072. var height = Lines.Count;
  1073. return new Size (width, height);
  1074. }
  1075. /// <summary>
  1076. /// Gets the formatted lines.
  1077. /// </summary>
  1078. /// <remarks>
  1079. /// <para>
  1080. /// Upon a 'get' of this property, if the text needs to be formatted (if <see cref="NeedsFormat"/> is <c>true</c>)
  1081. /// <see cref="Format(string, int, bool, bool, bool, int, TextDirection)"/> will be called internally.
  1082. /// </para>
  1083. /// </remarks>
  1084. public List<string> Lines {
  1085. get {
  1086. // With this check, we protect against subclasses with overrides of Text
  1087. if (string.IsNullOrEmpty (Text) || Size.IsEmpty) {
  1088. _lines = new List<string> {
  1089. string.Empty
  1090. };
  1091. NeedsFormat = false;
  1092. return _lines;
  1093. }
  1094. if (NeedsFormat) {
  1095. var shown_text = _text;
  1096. if (FindHotKey (_text, HotKeySpecifier, true, out _hotKeyPos, out Key newHotKey)) {
  1097. HotKey = newHotKey;
  1098. shown_text = RemoveHotKeySpecifier (Text, _hotKeyPos, HotKeySpecifier);
  1099. shown_text = ReplaceHotKeyWithTag (shown_text, _hotKeyPos);
  1100. }
  1101. if (IsVerticalDirection (_textDirection)) {
  1102. var colsWidth = GetSumMaxCharWidth (shown_text, 0, 1);
  1103. _lines = Format (shown_text, Size.Height, _textVerticalAlignment == VerticalTextAlignment.Justified, Size.Width > colsWidth,
  1104. PreserveTrailingSpaces, 0, _textDirection);
  1105. if (!AutoSize) {
  1106. colsWidth = GetMaxColsForWidth (_lines, Size.Width);
  1107. if (_lines.Count > colsWidth) {
  1108. _lines.RemoveRange (colsWidth, _lines.Count - colsWidth);
  1109. }
  1110. }
  1111. } else {
  1112. _lines = Format (shown_text, Size.Width, _textAlignment == TextAlignment.Justified, Size.Height > 1,
  1113. PreserveTrailingSpaces, 0, _textDirection);
  1114. if (!AutoSize && _lines.Count > Size.Height) {
  1115. _lines.RemoveRange (Size.Height, _lines.Count - Size.Height);
  1116. }
  1117. }
  1118. NeedsFormat = false;
  1119. }
  1120. return _lines;
  1121. }
  1122. }
  1123. /// <summary>
  1124. /// Gets or sets whether the <see cref="TextFormatter"/> needs to format the text when <see cref="Draw(Rect, Attribute, Attribute, Rect, bool)"/> is called.
  1125. /// If it is <c>false</c> when Draw is called, the Draw call will be faster.
  1126. /// </summary>
  1127. /// <remarks>
  1128. /// <para>
  1129. /// This is set to true when the properties of <see cref="TextFormatter"/> are set.
  1130. /// </para>
  1131. /// </remarks>
  1132. public bool NeedsFormat { get; set; }
  1133. /// <summary>
  1134. /// Causes the <see cref="TextFormatter"/> to reformat the text.
  1135. /// </summary>
  1136. /// <returns>The formatted text.</returns>
  1137. public string Format ()
  1138. {
  1139. var sb = new StringBuilder ();
  1140. // Lines_get causes a Format
  1141. foreach (var line in Lines) {
  1142. sb.AppendLine (line.ToString ());
  1143. }
  1144. return sb.ToString ();
  1145. }
  1146. /// <summary>
  1147. /// Draws the text held by <see cref="TextFormatter"/> to <see cref="Application.Driver"/> using the colors specified.
  1148. /// </summary>
  1149. /// <param name="bounds">Specifies the screen-relative location and maximum size for drawing the text.</param>
  1150. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  1151. /// <param name="hotColor">The color to use to draw the hotkey</param>
  1152. /// <param name="containerBounds">Specifies the screen-relative location and maximum container size.</param>
  1153. /// <param name="fillRemaining">Determines if the bounds width will be used (default) or only the text width will be used.</param>
  1154. public void Draw (Rect bounds, Attribute normalColor, Attribute hotColor, Rect containerBounds = default, bool fillRemaining = true)
  1155. {
  1156. // With this check, we protect against subclasses with overrides of Text (like Button)
  1157. if (string.IsNullOrEmpty (_text)) {
  1158. return;
  1159. }
  1160. Application.Driver?.SetAttribute (normalColor);
  1161. // Use "Lines" to ensure a Format (don't use "lines"))
  1162. var linesFormated = Lines;
  1163. switch (_textDirection) {
  1164. case TextDirection.TopBottom_RightLeft:
  1165. case TextDirection.LeftRight_BottomTop:
  1166. case TextDirection.RightLeft_BottomTop:
  1167. case TextDirection.BottomTop_RightLeft:
  1168. linesFormated.Reverse ();
  1169. break;
  1170. }
  1171. var isVertical = IsVerticalDirection (_textDirection);
  1172. var maxBounds = bounds;
  1173. if (Application.Driver != null) {
  1174. maxBounds = containerBounds == default
  1175. ? bounds
  1176. : new Rect (Math.Max (containerBounds.X, bounds.X),
  1177. Math.Max (containerBounds.Y, bounds.Y),
  1178. Math.Max (Math.Min (containerBounds.Width, containerBounds.Right - bounds.Left), 0),
  1179. Math.Max (Math.Min (containerBounds.Height, containerBounds.Bottom - bounds.Top), 0));
  1180. }
  1181. if (maxBounds.Width == 0 || maxBounds.Height == 0) {
  1182. return;
  1183. }
  1184. // BUGBUG: v2 - TextFormatter should not change the clip region. If a caller wants to break out of the clip region it should do
  1185. // so explicitly.
  1186. //var savedClip = Application.Driver?.Clip;
  1187. //if (Application.Driver != null) {
  1188. // Application.Driver.Clip = maxBounds;
  1189. //}
  1190. var lineOffset = !isVertical && bounds.Y < 0 ? Math.Abs (bounds.Y) : 0;
  1191. for (int line = lineOffset; line < linesFormated.Count; line++) {
  1192. if ((isVertical && line > bounds.Width) || (!isVertical && line > bounds.Height))
  1193. continue;
  1194. if ((isVertical && line >= maxBounds.Left + maxBounds.Width)
  1195. || (!isVertical && line >= maxBounds.Top + maxBounds.Height + lineOffset))
  1196. break;
  1197. var runes = _lines [line].ToRunes ();
  1198. switch (_textDirection) {
  1199. case TextDirection.RightLeft_BottomTop:
  1200. case TextDirection.RightLeft_TopBottom:
  1201. case TextDirection.BottomTop_LeftRight:
  1202. case TextDirection.BottomTop_RightLeft:
  1203. runes = runes.Reverse ().ToArray ();
  1204. break;
  1205. }
  1206. // When text is justified, we lost left or right, so we use the direction to align.
  1207. int x, y;
  1208. // Horizontal Alignment
  1209. if (_textAlignment == TextAlignment.Right || (_textAlignment == TextAlignment.Justified && !IsLeftToRight (_textDirection))) {
  1210. if (isVertical) {
  1211. var runesWidth = GetSumMaxCharWidth (Lines, line);
  1212. x = bounds.Right - runesWidth;
  1213. CursorPosition = bounds.Width - runesWidth + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1214. } else {
  1215. var runesWidth = StringExtensions.ToString (runes).GetColumns ();
  1216. x = bounds.Right - runesWidth;
  1217. CursorPosition = bounds.Width - runesWidth + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1218. }
  1219. } else if (_textAlignment == TextAlignment.Left || _textAlignment == TextAlignment.Justified) {
  1220. if (isVertical) {
  1221. var runesWidth = line > 0 ? GetSumMaxCharWidth (Lines, 0, line) : 0;
  1222. x = bounds.Left + runesWidth;
  1223. } else {
  1224. x = bounds.Left;
  1225. }
  1226. CursorPosition = _hotKeyPos > -1 ? _hotKeyPos : 0;
  1227. } else if (_textAlignment == TextAlignment.Centered) {
  1228. if (isVertical) {
  1229. var runesWidth = GetSumMaxCharWidth (Lines, line);
  1230. x = bounds.Left + line + ((bounds.Width - runesWidth) / 2);
  1231. CursorPosition = (bounds.Width - runesWidth) / 2 + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1232. } else {
  1233. var runesWidth = StringExtensions.ToString (runes).GetColumns ();
  1234. x = bounds.Left + (bounds.Width - runesWidth) / 2;
  1235. CursorPosition = (bounds.Width - runesWidth) / 2 + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  1236. }
  1237. } else {
  1238. throw new ArgumentOutOfRangeException ();
  1239. }
  1240. // Vertical Alignment
  1241. if (_textVerticalAlignment == VerticalTextAlignment.Bottom || (_textVerticalAlignment == VerticalTextAlignment.Justified && !IsTopToBottom (_textDirection))) {
  1242. if (isVertical) {
  1243. y = bounds.Bottom - runes.Length;
  1244. } else {
  1245. y = bounds.Bottom - Lines.Count + line;
  1246. }
  1247. } else if (_textVerticalAlignment == VerticalTextAlignment.Top || _textVerticalAlignment == VerticalTextAlignment.Justified) {
  1248. if (isVertical) {
  1249. y = bounds.Top;
  1250. } else {
  1251. y = bounds.Top + line;
  1252. }
  1253. } else if (_textVerticalAlignment == VerticalTextAlignment.Middle) {
  1254. if (isVertical) {
  1255. var s = (bounds.Height - runes.Length) / 2;
  1256. y = bounds.Top + s;
  1257. } else {
  1258. var s = (bounds.Height - Lines.Count) / 2;
  1259. y = bounds.Top + line + s;
  1260. }
  1261. } else {
  1262. throw new ArgumentOutOfRangeException ();
  1263. }
  1264. var colOffset = bounds.X < 0 ? Math.Abs (bounds.X) : 0;
  1265. var start = isVertical ? bounds.Top : bounds.Left;
  1266. var size = isVertical ? bounds.Height : bounds.Width;
  1267. var current = start + colOffset;
  1268. for (var idx = (isVertical ? start - y : start - x) + colOffset; current < start + size; idx++) {
  1269. if (idx < 0 || x + current + colOffset < 0) {
  1270. current++;
  1271. continue;
  1272. } else if (!fillRemaining && idx > runes.Length - 1) {
  1273. break;
  1274. }
  1275. if ((!isVertical && idx > maxBounds.Left + maxBounds.Width - bounds.X + colOffset)
  1276. || (isVertical && idx > maxBounds.Top + maxBounds.Height - bounds.Y))
  1277. break;
  1278. var rune = (Rune)' ';
  1279. if (isVertical) {
  1280. Application.Driver?.Move (x, current);
  1281. if (idx >= 0 && idx < runes.Length) {
  1282. rune = runes [idx];
  1283. }
  1284. } else {
  1285. Application.Driver?.Move (current, y);
  1286. if (idx >= 0 && idx < runes.Length) {
  1287. rune = runes [idx];
  1288. }
  1289. }
  1290. if (HotKeyPos > -1 && idx == HotKeyPos) {
  1291. if ((isVertical && _textVerticalAlignment == VerticalTextAlignment.Justified) ||
  1292. (!isVertical && _textAlignment == TextAlignment.Justified)) {
  1293. CursorPosition = idx - start;
  1294. }
  1295. Application.Driver?.SetAttribute (hotColor);
  1296. Application.Driver?.AddRune (rune);
  1297. Application.Driver?.SetAttribute (normalColor);
  1298. } else {
  1299. Application.Driver?.AddRune (rune);
  1300. }
  1301. var runeWidth = Math.Max (rune.GetColumns (), 1);
  1302. if (isVertical) {
  1303. current++;
  1304. } else {
  1305. current += runeWidth;
  1306. }
  1307. var nextRuneWidth = idx + 1 > -1 && idx + 1 < runes.Length ? runes [idx + 1].GetColumns () : 0;
  1308. if (!isVertical && idx + 1 < runes.Length && current + nextRuneWidth > start + size) {
  1309. break;
  1310. }
  1311. }
  1312. }
  1313. //if (Application.Driver != null) {
  1314. // Application.Driver.Clip = (Rect)savedClip;
  1315. //}
  1316. }
  1317. }
  1318. }